- asset loader (needed for android)
[andemo] / src / android / assfile.c
1 #include <assert.h>
2 #include <fcntl.h>
3 #include <android/asset_manager.h>
4 #include "assfile.h"
5 #include "android_native_app_glue.h"
6
7 struct android_app *app;        /* defined in android/amain.c */
8
9 static int putback_buf = -1;
10
11 ass_file *ass_fopen(const char *fname, const char *mode)
12 {
13         AAsset *ass;
14         unsigned int flags = 0;
15         char prev = 0;
16
17         while(*mode) {
18                 switch(*mode) {
19                 case 'r':
20                         flags |= O_RDONLY;
21                         break;
22
23                 case 'w':
24                         flags |= O_WRONLY;
25                         break;
26
27                 case 'a':
28                         flags |= O_APPEND;
29                         break;
30
31                 case '+':
32                         if(prev == 'w' || prev == 'a') {
33                                 flags |= O_CREAT;
34                         }
35                         break;
36
37                 default:
38                         break;
39                 }
40                 prev = *mode++;
41         }
42
43         assert(app);
44         assert(app->activity);
45         assert(app->activity->assetManager);
46         if(!(ass = AAssetManager_open(app->activity->assetManager, fname, flags))) {
47                 return 0;
48         }
49         return (ass_file*)ass;
50 }
51
52 void ass_fclose(ass_file *fp)
53 {
54         AAsset_close((AAsset*)fp);
55 }
56
57 long ass_fseek(ass_file *fp, long offs, int whence)
58 {
59         return AAsset_seek((AAsset*)fp, offs, whence);
60 }
61
62 long ass_ftell(ass_file *fp)
63 {
64         return AAsset_seek((AAsset*)fp, 0, SEEK_CUR);
65 }
66
67 int ass_feof(ass_file *fp)
68 {
69         return AAsset_getRemainingLength((AAsset*)fp) == 0 ? 1 : 0;
70 }
71
72 size_t ass_fread(void *buf, size_t size, size_t count, ass_file *fp)
73 {
74         size_t nbytes = size * count;
75         size_t rdbytes = 0;
76
77         if(putback_buf >= 0) {
78                 *(unsigned char*)buf = (unsigned char)putback_buf;
79                 putback_buf = -1;
80                 --nbytes;
81                 ++rdbytes;
82                 buf = (unsigned char*)buf + 1;
83         }
84
85         return (rdbytes + AAsset_read((AAsset*)fp, buf, nbytes)) / size;
86 }
87
88 int ass_ungetc(int c, ass_file *fp)
89 {
90         putback_buf = c;
91         return 0;
92 }