summaryrefslogtreecommitdiff
path: root/io/param.c
blob: 7e776a8630acb11856731a701c0fb6a8e59a75fa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "../common.h"
#include "param.h"

#define INVALID_FORMAT_ERROR(fn) \
    nerv_error(L, "Invalid param file: %s", fn)
#define CHECK_FORMAT(exp, ret, fname) \
    do { \
        if ((exp) != (ret)) INVALID_FORMAT_ERROR(fn); \
    } while (0)

const char *nerv_param_file_tname = "nerv.ParamFile";
const char *nerv_param_file_handle_tname = "nerv.ParamFileHandle";
const char *nerv_param_chunk_info_tname = "nerv.ParamChunkInfo";
const char *nerv_param_chunk_data_tname = "nerv.ParamChunkData";

#define PARAM_HEADER_SIZE 16

enum {
    NORMAL,
    INVALID_FORMAT,
    END_OF_FILE,
    SECTION_OVERFLOW,
    WRITE_ERROR
};

size_t read_param_header_plain(FILE *fp, int *status) {
    static char buff[PARAM_HEADER_SIZE];
    int i;
    size_t size = 0;
    *status = NORMAL;
    if (fread(buff, 1, PARAM_HEADER_SIZE, fp) != PARAM_HEADER_SIZE)
    {
        if (feof(fp)) *status = END_OF_FILE;
        else *status = INVALID_FORMAT;
    }
    for (i = 0; i < PARAM_HEADER_SIZE; i++)
        if (isdigit(buff[i]))
            size = size * 10 + buff[i] - '0';
    fprintf(stderr, "header: %lu\n", size);
    return size;
}

#define CHECK_WRITE(status) \
    do { \
        if (status == SECTION_OVERFLOW) \
            nerv_error(L, "section overflowed"); \
        else if (status == WRITE_ERROR) \
            nerv_error(L, "error while writing"); \
    } while (0)

void write_param_header_plain(FILE *fp, size_t size, int *status) {
    static char buff[PARAM_HEADER_SIZE];
    int i;
    *status = NORMAL;
    for (i = PARAM_HEADER_SIZE - 3; i > 0; i--, size /= 10)
        buff[i] = size % 10 + '0';
    if (size)
    {
        *status = SECTION_OVERFLOW;
        return;
    }
    buff[0] = '[';
    buff[PARAM_HEADER_SIZE - 2] = ']';
    buff[PARAM_HEADER_SIZE - 1] = '\n';
    if (fwrite(buff, 1, PARAM_HEADER_SIZE, fp) != PARAM_HEADER_SIZE)
    {
        *status = WRITE_ERROR;
        return;
    }
}

ParamChunkData *get_param_chunk_data(FILE *fp, ParamChunkInfo *info) {
    ParamChunkData *pcd = (ParamChunkData *)malloc(sizeof(ParamChunkData));
    pcd->data = (char *)malloc(info->length);
    pcd->fp = fmemopen(pcd->data, info->length, "r");
    assert(fseeko(fp, info->offset, SEEK_SET) == 0);
    assert(fread(pcd->data, 1, info->length, fp) == (size_t)info->length);
    return pcd;
}

const char *read_param_metadata(lua_State *L, FILE *fp, const char *fn) {
#define LINEBUFF_SIZE 1024
    static char buff[7 + LINEBUFF_SIZE] = "return ";
    CHECK_FORMAT(fgets(buff + 7, LINEBUFF_SIZE, fp), buff + 7, fn);
    fprintf(stderr, "metadata: %s\n", buff);
    return buff;
}

void write_param_metadata(FILE *fp, const char *metadata_str, int *status) {
    size_t size = strlen(metadata_str);
    *status = NORMAL;
    if (fwrite(metadata_str, 1, size, fp) != size ||
        fprintf(fp, "\n") < 0)
    {
        *status = WRITE_ERROR;
        return;
    }
    fprintf(stderr, "metadata: %s\n", metadata_str);
}


int nerv_param_file_open_write(lua_State *L, const char *fn) {
    FILE *fp = fopen(fn, "w");
    ParamFileHandle *lfp;
    if (!fp) nerv_error(L, "Error while opening param file: %s", fn);
    lfp = (ParamFileHandle *)malloc(sizeof(ParamFileHandle));
    lfp->fp = fp;
    luaT_pushudata(L, lfp, nerv_param_file_handle_tname);
    lua_setfield(L, -2, "handle");
    luaT_pushmetatable(L, nerv_param_file_tname);
    lua_setmetatable(L, -2);
    return 1;
}

int nerv_param_file_open_read(lua_State *L, const char *fn) {
    FILE *fp = fopen(fn, "r");
    int i, status;
    size_t param_len;
    off_t offset;
    ParamFileHandle *lfp;

    if (!fp) nerv_error(L, "Error while opening param file: %s", fn);
    offset = ftello(fp);
    lua_newtable(L);
    fprintf(stderr, "%d\n", (int)offset);
    for (i = 0;; offset += param_len, i++)
    {
        ParamChunkInfo *pci;
        fprintf(stderr, "reading param chunk %d from %d\n", i, (int)offset);
        /* skip to the begining of param chunk i */
        CHECK_FORMAT(fseeko(fp, offset, SEEK_SET), 0, fn);
        /* read header */
        param_len = read_param_header_plain(fp, &status);
        if (status == END_OF_FILE) break;
        else if (status == INVALID_FORMAT)
            INVALID_FORMAT_ERROR(fn);
        /* read metadata */
        luaL_loadstring(L, read_param_metadata(L, fp, fn));
        CHECK_FORMAT(lua_pcall(L, 0, 1, 0), 0, fn);
        CHECK_FORMAT(lua_istable(L, -1), 1, fn);
        /* chunk info */
        pci = (ParamChunkInfo *)malloc(sizeof(ParamChunkInfo));
        pci->offset = ftello(fp);
        pci->length = param_len - (pci->offset - offset);
        fprintf(stderr, "%d + %d (skip %lu)\n", (int)pci->offset,
                (int)pci->length, param_len);
        luaT_pushudata(L, pci, nerv_param_chunk_info_tname);
        lua_setfield(L, -2, "chunk");
        lua_rawseti(L, -2, i);
    }
    lua_setfield(L, -2, "metadata");
    lfp = (ParamFileHandle *)malloc(sizeof(ParamFileHandle));
    lfp->fp = fp;
    luaT_pushudata(L, lfp, nerv_param_file_handle_tname);
    lua_setfield(L, -2, "handle");
    luaT_pushmetatable(L, nerv_param_file_tname);
    lua_setmetatable(L, -2);
    return 1;
}

int nerv_param_file___init(lua_State *L) {
    const char *fn = luaL_checkstring(L, 2);
    const char *mode = luaL_checkstring(L, 3);
    int rd = 1, bin = 0;
    size_t i, len = strlen(mode);
    lua_pushvalue(L, 1);
    for (i = 0; i < len; i++)
        switch (mode[i])
        {
            case 'r': rd = 1; break;
            case 'w': rd = 0; break;
            case 'b': bin = 1; break;
        }
    return rd ? nerv_param_file_open_read(L, fn) : \
                nerv_param_file_open_write(L, fn);
}

int nerv_param_file_new(lua_State *L) {
    const char *fn = luaL_checkstring(L, 1);
    const char *mode = luaL_checkstring(L, 2);
    int rd = 1, bin = 0;
    size_t i, len = strlen(mode);
    for (i = 0; i < len; i++)
        switch (mode[i])
        {
            case 'r': rd = 1; break;
            case 'w': rd = 0; break;
            case 'b': bin = 1; break;
        }
    lua_newtable(L);
    return rd ? nerv_param_file_open_read(L, fn) : \
                nerv_param_file_open_write(L, fn);
}

int nerv_param_file_write_chunkdata(lua_State *L) {
    ParamFileHandle *pfh;
    int status;
    off_t start;
    size_t size;
    const char *metadata_str = lua_tolstring(L, 2, NULL);
    lua_getfield(L, 1, "handle");
    pfh = luaT_checkudata(L, -1, nerv_param_file_handle_tname);
    start = ftello(pfh->fp);
    write_param_header_plain(pfh->fp, 0, &status); /* fill zeros */
    CHECK_WRITE(status);
    write_param_metadata(pfh->fp, metadata_str, &status);
    CHECK_WRITE(status);
    lua_getfield(L, 3, "save");
    if (lua_type(L, -1) != LUA_TFUNCTION)
        nerv_error(L, "\"save\" method must be implemented");
    lua_pushvalue(L, 3);
    lua_pushvalue(L, -3); /* pass handle as parameter to save() */
    lua_call(L, 2, 0); /* let the save() to write */
    size = ftello(pfh->fp) - start;
    fseeko(pfh->fp, start, SEEK_SET);
    /* write the calced size */
    write_param_header_plain(pfh->fp, size, &status);
    CHECK_WRITE(status);
    fseeko(pfh->fp, 0, SEEK_END);
    return 0;
}

int nerv_param_file_get_chunkdata(lua_State *L) {
    ParamFileHandle *pfh;
    ParamChunkInfo *pci;
    int k = luaL_checkinteger(L, 2);

    lua_getfield(L, 1, "handle");
    pfh = luaT_checkudata(L, -1, nerv_param_file_handle_tname);
    lua_pop(L, 1); /* pop handle */

    lua_getfield(L, 1, "metadata");
    /* now stack: self, k, metadata */
    lua_rawgeti(L, -1, k);
    /* now stack: self, k, metadata, ith{} */
    lua_getfield(L, -1, "chunk");
    pci = luaT_checkudata(L, -1, nerv_param_chunk_info_tname);

    luaT_pushudata(L, get_param_chunk_data(pfh->fp, pci),
                        nerv_param_chunk_data_tname);
    return 1;
}

int nerv_param_file_handle_destroy(lua_State *L) {
    ParamFileHandle *pfh = luaT_checkudata(L, 1,
                                nerv_param_file_handle_tname);
    fclose(pfh->fp);
    free(pfh);
    return 0;
}

static int nerv_param_chunk_destroy(lua_State *L) {
    ParamChunkInfo *pci = luaT_checkudata(L, 1, nerv_param_chunk_info_tname);
    free(pci);
    return 0;
}

static int nerv_param_chunk_data_destroy(lua_State *L) {
    ParamChunkData *pcd = luaT_checkudata(L, 1, nerv_param_chunk_data_tname);
    fclose(pcd->fp);
    free(pcd->data);
    free(pcd);
    return 0;
}

static const luaL_Reg nerv_param_file_methods[] = {
    {"get_chunkdata", nerv_param_file_get_chunkdata},
    {"_write_chunkdata", nerv_param_file_write_chunkdata},
    {"__init", nerv_param_file___init},
    {NULL, NULL}
};

void nerv_param_file_init(lua_State *L) {
    luaT_newmetatable(L, nerv_param_file_tname, NULL,
                        nerv_param_file_new,
                        NULL, NULL);
    luaL_register(L, NULL, nerv_param_file_methods);
    lua_pop(L, 1);
    luaT_newmetatable(L, nerv_param_file_handle_tname, NULL,
                        NULL, nerv_param_file_handle_destroy, NULL);
    luaT_newmetatable(L, nerv_param_chunk_info_tname, NULL,
                        NULL, nerv_param_chunk_destroy, NULL);
    luaT_newmetatable(L, nerv_param_chunk_data_tname, NULL,
                        NULL, nerv_param_chunk_data_destroy, NULL);
}