Make open() posix compliant api-wise. A few calls (those with O_CREAT) need the addit...
[kugel-rb.git] / apps / plugins / lua / liolib.c
blob7a43915f20363762743fe4756592f0f641f12f6c
1 /*
2 ** $Id: liolib.c,v 2.73.1.3 2008/01/18 17:47:43 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
5 */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
12 #define liolib_c
13 #define LUA_LIB
15 #include "lua.h"
17 #include "lauxlib.h"
18 #include "lualib.h"
19 #include "rocklibc.h"
23 #define IO_INPUT 1
24 #define IO_OUTPUT 2
27 static const char *const fnames[] = {"input", "output"};
30 static int pushresult (lua_State *L, int i, const char *filename) {
31 int en = errno;
32 if (i) {
33 lua_pushboolean(L, 1);
34 return 1;
36 else {
37 lua_pushnil(L);
38 if (filename)
39 lua_pushfstring(L, "%s: %s", filename, strerror(en));
40 else
41 lua_pushfstring(L, "%s", strerror(en));
42 lua_pushinteger(L, 0);
43 return 3;
48 static void fileerror (lua_State *L, int arg, const char *filename) {
49 lua_pushfstring(L, "%s: %s", filename, strerror(errno));
50 luaL_argerror(L, arg, lua_tostring(L, -1));
54 static int io_type (lua_State *L) {
55 void *ud;
56 luaL_checkany(L, 1);
57 ud = lua_touserdata(L, 1);
58 lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
59 if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
60 lua_pushnil(L); /* not a file */
61 else if (*((int *)ud) < 0)
62 lua_pushliteral(L, "closed file");
63 else
64 lua_pushliteral(L, "file");
65 return 1;
69 static int* tofile (lua_State *L) {
70 int *f = (int*) luaL_checkudata(L, 1, LUA_FILEHANDLE);
71 if (*f < 0)
72 luaL_error(L, "attempt to use a closed file");
73 return f;
79 ** When creating file handles, always creates a `closed' file handle
80 ** before opening the actual file; so, if there is a memory error, the
81 ** file is not left opened.
83 static int* newfile (lua_State *L) {
84 int *pf = (int *)lua_newuserdata(L, sizeof(int));
85 *pf = -1; /* file handle is currently `closed' */
86 luaL_getmetatable(L, LUA_FILEHANDLE);
87 lua_setmetatable(L, -2);
88 return pf;
93 ** function to close regular files
95 static int io_fclose (lua_State *L) {
96 int *p = tofile(L);
97 int ok = (rb->close(*p) == 0);
98 *p = -1;
99 return pushresult(L, ok, NULL);
103 static inline int aux_close (lua_State *L) {
104 return io_fclose(L);
108 static int io_close (lua_State *L) {
109 if (lua_isnone(L, 1))
110 lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
111 tofile(L); /* make sure argument is a file */
112 return aux_close(L);
116 static int io_gc (lua_State *L) {
117 int f = *(int*) luaL_checkudata(L, 1, LUA_FILEHANDLE);
118 /* ignore closed files */
119 if (f >= 0)
120 aux_close(L);
121 return 0;
125 static int io_tostring (lua_State *L) {
126 int f = *(int*) luaL_checkudata(L, 1, LUA_FILEHANDLE);
127 if (f < 0)
128 lua_pushliteral(L, "file (closed)");
129 else
130 lua_pushfstring(L, "file (%d)", f);
131 return 1;
135 static int io_open (lua_State *L) {
136 const char *filename = luaL_checkstring(L, 1);
137 const char *mode = luaL_optstring(L, 2, "r");
138 int *pf = newfile(L);
139 int flags = 0;
140 if(*(mode+1) == '+') {
141 flags = O_RDWR;
142 switch(*mode) {
143 case 'w':
144 flags |= O_TRUNC; break;
145 case 'a':
146 flags |= O_APPEND; break;
149 else {
150 switch(*mode) {
151 case 'r':
152 flags = O_RDONLY; break;
153 case 'w':
154 flags = O_WRONLY | O_TRUNC; break;
155 case 'a':
156 flags = O_WRONLY | O_APPEND; break;
159 if((*mode == 'w' || *mode == 'a') && !rb->file_exists(filename))
160 flags |= O_CREAT;
161 *pf = rb->open(filename, flags, 0666);
162 return (*pf < 0) ? pushresult(L, 0, filename) : 1;
166 static int* getiofile (lua_State *L, int findex) {
167 int *f;
168 lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
169 f = (int *)lua_touserdata(L, -1);
170 if (f == NULL || *f < 0)
171 luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
172 return f;
176 static int g_iofile (lua_State *L, int f, int flags) {
177 if (!lua_isnoneornil(L, 1)) {
178 const char *filename = lua_tostring(L, 1);
179 if (filename) {
180 int *pf = newfile(L);
181 *pf = rb->open(filename, flags);
182 if (*pf < 0)
183 fileerror(L, 1, filename);
185 else {
186 tofile(L); /* check that it's a valid file handle */
187 lua_pushvalue(L, 1);
189 lua_rawseti(L, LUA_ENVIRONINDEX, f);
191 /* return current value */
192 lua_rawgeti(L, LUA_ENVIRONINDEX, f);
193 return 1;
197 static int io_input (lua_State *L) {
198 return g_iofile(L, IO_INPUT, O_RDONLY);
202 static int io_output (lua_State *L) {
203 return g_iofile(L, IO_OUTPUT, O_WRONLY);
207 static int io_readline (lua_State *L);
210 static void aux_lines (lua_State *L, int idx, int toclose) {
211 lua_pushvalue(L, idx);
212 lua_pushboolean(L, toclose); /* close/not close file when finished */
213 lua_pushcclosure(L, io_readline, 2);
217 static int f_lines (lua_State *L) {
218 tofile(L); /* check that it's a valid file handle */
219 aux_lines(L, 1, 0);
220 return 1;
224 static int io_lines (lua_State *L) {
225 if (lua_isnoneornil(L, 1)) { /* no arguments? */
226 /* will iterate over default input */
227 lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
228 return f_lines(L);
230 else {
231 const char *filename = luaL_checkstring(L, 1);
232 int *pf = newfile(L);
233 *pf = rb->open(filename, O_RDONLY);
234 if (*pf < 0)
235 fileerror(L, 1, filename);
236 aux_lines(L, lua_gettop(L), 1);
237 return 1;
243 ** {======================================================
244 ** READ
245 ** =======================================================
248 static int read_number (lua_State *L, int *f) {
249 lua_Number d;
250 if (PREFIX(fscanf)(*f, LUA_NUMBER_SCAN, &d) == 1) {
251 lua_pushnumber(L, d);
252 return 1;
254 else return 0; /* read fails */
258 static int test_eof (lua_State *L, int *f) {
259 ssize_t s = rb->lseek(*f, 0, SEEK_CUR);
260 lua_pushlstring(L, NULL, 0);
261 return s != rb->filesize(*f);
265 /* Rockbox already defines read_line() */
266 static int _read_line (lua_State *L, int *f) {
267 luaL_Buffer b;
268 luaL_buffinit(L, &b);
269 for (;;) {
270 size_t l;
271 size_t r;
272 char *p = luaL_prepbuffer(&b);
273 r = rb->read_line(*f, p, LUAL_BUFFERSIZE);
274 l = strlen(p);
275 if (l == 0 || p[l-1] != '\n')
276 luaL_addsize(&b, l);
277 else {
278 luaL_addsize(&b, l - 1); /* do not include `eol' */
279 luaL_pushresult(&b); /* close buffer */
280 return 1; /* read at least an `eol' */
282 if (r < LUAL_BUFFERSIZE) { /* eof? */
283 luaL_pushresult(&b); /* close buffer */
284 return (lua_objlen(L, -1) > 0); /* check whether read something */
290 static int read_chars (lua_State *L, int *f, size_t n) {
291 size_t rlen; /* how much to read */
292 size_t nr; /* number of chars actually read */
293 luaL_Buffer b;
294 luaL_buffinit(L, &b);
295 rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
296 do {
297 char *p = luaL_prepbuffer(&b);
298 if (rlen > n) rlen = n; /* cannot read more than asked */
299 nr = rb->read(*f, p, rlen);
300 luaL_addsize(&b, nr);
301 n -= nr; /* still have to read `n' chars */
302 } while (n > 0 && nr == rlen); /* until end of count or eof */
303 luaL_pushresult(&b); /* close buffer */
304 return (n == 0 || lua_objlen(L, -1) > 0);
308 static int g_read (lua_State *L, int *f, int first) {
309 int nargs = lua_gettop(L) - 1;
310 int success;
311 int n;
312 if (nargs == 0) { /* no arguments? */
313 success = _read_line(L, f);
314 n = first+1; /* to return 1 result */
316 else { /* ensure stack space for all results and for auxlib's buffer */
317 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
318 success = 1;
319 for (n = first; nargs-- && success; n++) {
320 if (lua_type(L, n) == LUA_TNUMBER) {
321 size_t l = (size_t)lua_tointeger(L, n);
322 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
324 else {
325 const char *p = lua_tostring(L, n);
326 luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
327 switch (p[1]) {
328 case 'n': /* number */
329 success = read_number(L, f);
330 break;
331 case 'l': /* line */
332 success = _read_line(L, f);
333 break;
334 case 'a': /* file */
335 read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
336 success = 1; /* always success */
337 break;
338 default:
339 return luaL_argerror(L, n, "invalid format");
344 if (!success) {
345 lua_pop(L, 1); /* remove last result */
346 lua_pushnil(L); /* push nil instead */
348 return n - first;
352 static int io_read (lua_State *L) {
353 return g_read(L, getiofile(L, IO_INPUT), 1);
357 static int f_read (lua_State *L) {
358 return g_read(L, tofile(L), 2);
362 static int io_readline (lua_State *L) {
363 int *f = (int *) lua_touserdata(L, lua_upvalueindex(1));
364 int sucess;
365 if (*f < 0) /* file is already closed? */
366 luaL_error(L, "file is already closed");
367 sucess = _read_line(L, f);
368 if (sucess) return 1;
369 else { /* EOF */
370 if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
371 lua_settop(L, 0);
372 lua_pushvalue(L, lua_upvalueindex(1));
373 aux_close(L); /* close it */
375 return 0;
379 /* }====================================================== */
382 static int g_write (lua_State *L, int *f, int arg) {
383 int nargs = lua_gettop(L) - 1;
384 int status = 1;
385 for (; nargs--; arg++) {
386 if (lua_type(L, arg) == LUA_TNUMBER) {
387 /* optimization: could be done exactly as for strings */
388 status = status &&
389 rb->fdprintf(*f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
391 else {
392 size_t l;
393 const char *s = luaL_checklstring(L, arg, &l);
394 status = status && (rb->write(*f, s, l) == (ssize_t)l);
397 return pushresult(L, status, NULL);
401 static int io_write (lua_State *L) {
402 return g_write(L, getiofile(L, IO_OUTPUT), 1);
406 static int f_write (lua_State *L) {
407 return g_write(L, tofile(L), 2);
411 static int f_seek (lua_State *L) {
412 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
413 static const char *const modenames[] = {"set", "cur", "end", NULL};
414 int f = *tofile(L);
415 int op = luaL_checkoption(L, 2, "cur", modenames);
416 long offset = luaL_optlong(L, 3, 0);
417 op = rb->lseek(f, offset, mode[op]);
418 if (op)
419 return pushresult(L, 0, NULL); /* error */
420 else {
421 lua_pushinteger(L, rb->lseek(f, 0, SEEK_CUR));
422 return 1;
427 static const luaL_Reg iolib[] = {
428 {"close", io_close},
429 {"input", io_input},
430 {"lines", io_lines},
431 {"open", io_open},
432 {"output", io_output},
433 {"read", io_read},
434 {"type", io_type},
435 {"write", io_write},
436 {NULL, NULL}
440 static const luaL_Reg flib[] = {
441 {"close", io_close},
442 {"lines", f_lines},
443 {"read", f_read},
444 {"seek", f_seek},
445 {"write", f_write},
446 {"__gc", io_gc},
447 {"__tostring", io_tostring},
448 {NULL, NULL}
452 static void createmeta (lua_State *L) {
453 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
454 lua_pushvalue(L, -1); /* push metatable */
455 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
456 luaL_register(L, NULL, flib); /* file methods */
460 LUALIB_API int luaopen_io (lua_State *L) {
461 createmeta(L);
462 lua_replace(L, LUA_ENVIRONINDEX);
463 /* open library */
464 luaL_register(L, LUA_IOLIBNAME, iolib);
465 /* create (and set) default files */
466 lua_pop(L, 1); /* pop environment for default files */
467 return 1;