added assfile
[raydungeon] / libs / assfile / mod_path.c
1 /*
2 assfile - library for accessing assets with an fopen/fread-like interface
3 Copyright (C) 2018  John Tsiombikas <nuclear@member.fsf.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <ctype.h>
22 #include <errno.h>
23
24 #ifdef __MSVCRT__
25 #include <malloc.h>
26 #else
27 #include <alloca.h>
28 #endif
29
30 #include "assfile_impl.h"
31
32
33 static void *fop_open(const char *fname, void *udata);
34 static void fop_close(void *fp, void *udata);
35 static long fop_seek(void *fp, long offs, int whence, void *udata);
36 static long fop_read(void *fp, void *buf, long size, void *udata);
37
38
39 struct ass_fileops *ass_alloc_path(const char *path)
40 {
41         char *p;
42         struct ass_fileops *fop;
43
44         if(!(fop = malloc(sizeof *fop))) {
45                 return 0;
46         }
47         if(!(p = malloc(strlen(path) + 1))) {
48                 free(fop);
49                 return 0;
50         }
51         fop->udata = p;
52
53         while(*path) {
54                 *p++ = *path++;
55         }
56         while(p > (char*)fop->udata && (p[-1] == '/' || isspace(p[-1]))) p--;
57         *p = 0;
58
59         fop->open = fop_open;
60         fop->close = fop_close;
61         fop->seek = fop_seek;
62         fop->read = fop_read;
63         return fop;
64 }
65
66 void ass_free_path(struct ass_fileops *fop)
67 {
68         free(fop->udata);
69 }
70
71 static void *fop_open(const char *fname, void *udata)
72 {
73         const char *asspath = (char*)udata;
74         char *path;
75         FILE *fp;
76
77         path = alloca(strlen(asspath) + strlen(fname) + 2);
78         sprintf(path, "%s/%s", asspath, fname);
79
80         if(!(fp = fopen(path, "rb"))) {
81                 ass_errno = errno;
82                 return 0;
83         }
84         return fp;
85 }
86
87 static void fop_close(void *fp, void *udata)
88 {
89         fclose(fp);
90 }
91
92 static long fop_seek(void *fp, long offs, int whence, void *udata)
93 {
94         fseek(fp, offs, whence);
95         return ftell(fp);
96 }
97
98 static long fop_read(void *fp, void *buf, long size, void *udata)
99 {
100         return fread(buf, 1, size, fp);
101 }