/* * Read data from a fd. Args: * - 0: fd * - 1: nread * TODO: * - use buffers */ static duk_ret_t io_read(duk_context* ctx) { int fd; ssize_t r; size_t nread; char* buf; fd = duk_require_int(ctx, 0); nread = duk_require_int(ctx, 1); buf = malloc(nread); if (!buf) { SJS_THROW_ERRNO_ERROR2(ENOMEM); return -42; /* control never returns here */ } r = read(fd, buf, nread); if (r < 0) { SJS_THROW_ERRNO_ERROR(); return -42; /* control never returns here */ } else if (r == 0) { /* EOF */ duk_push_string(ctx, ""); } else { duk_push_lstring(ctx, buf, r); } return 1; }
static duk_ret_t time_time(duk_context* ctx) { int r; struct timeval tv; r = gettimeofday(&tv, NULL); if (r < 0) { SJS_THROW_ERRNO_ERROR(); return -42; /* control never returns here */ } else { double t; t = tv.tv_sec + 1e-6*tv.tv_usec; duk_push_number(ctx, t); return 1; } }
/* * Flush the file write buffer. Args: * - 0: FILE */ static duk_ret_t io_fflush(duk_context* ctx) { FILE* f; int r; f = duk_require_pointer(ctx, 0); r = fflush(f); if (r != 0) { SJS_THROW_ERRNO_ERROR(); return -42; /* control never returns here */ } duk_push_undefined(ctx); return 1; }
/* * Open a file given an fd. Args: * - 0: fd * - 1: mode */ static duk_ret_t io_fdopen(duk_context* ctx) { int fd; const char* mode; FILE* f; fd = duk_require_int(ctx, 0); mode = duk_require_string(ctx, 1); f = fdopen(fd, mode); if (f == NULL) { SJS_THROW_ERRNO_ERROR(); return -42; /* control never returns here */ } else { duk_push_pointer(ctx, (void*) f); return 1; } }
/* * Write data to a fd. Args: * - 0: fd * - 1: data * TODO: * - use buffers */ static duk_ret_t io_write(duk_context* ctx) { int fd; ssize_t r; size_t len; const char* buf; fd = duk_require_int(ctx, 0); buf = duk_require_lstring(ctx, 1, &len); r = write(fd, buf, len); if (r < 0) { SJS_THROW_ERRNO_ERROR(); return -42; /* control never returns here */ } else { duk_push_int(ctx, r); } return 1; }