Add all and line option to file-read

This commit is contained in:
Calvin Rose
2018-02-04 00:54:38 -05:00
parent f3b2c29580
commit 4b89789f69
3 changed files with 42 additions and 127 deletions
+29 -3
View File
@@ -169,11 +169,37 @@ static int dst_io_fread(DstArgs args) {
size_t ntoread, nread;
IOFile *iof = checkfile(args, 0);
if (!iof) return 1;
if (!dst_checktype(args.v[1], DST_INTEGER)) return dst_throw(args, "expected positive integer");
len = dst_unwrap_integer(args.v[1]);
if (len < 0) return dst_throw(args, "expected positive integer");
b = checkbuffer(args, 2, 1);
if (!b) return 1;
if (dst_checktype(args.v[1], DST_SYMBOL)) {
const uint8_t *sym = dst_unwrap_symbol(args.v[1]);
if (!dst_cstrcmp(sym, ":all")) {
/* Read whole file */
long fsize;
fseek(iof->file, 0, SEEK_END);
fsize = ftell(iof->file);
fseek(iof->file, 0, SEEK_SET);
if (fsize > INT32_MAX) return dst_throw(args, "buffer overflow");
len = fsize;
/* Fall through to normal code */
} else if (!dst_cstrcmp(sym, ":line")) {
for (;;) {
int x = fgetc(iof->file);
if (x == EOF || x == '\n') {
break;
}
if (dst_buffer_push_u8(b, (uint8_t)x)) return dst_throw(args, "buffer overflow");
}
return dst_return(args, dst_wrap_buffer(b));
} else {
return dst_throw(args, "expected one of :all, :line");
}
} else if (!dst_checktype(args.v[1], DST_INTEGER)) {
return dst_throw(args, "expected positive integer");
} else {
len = dst_unwrap_integer(args.v[1]);
if (len < 0) return dst_throw(args, "expected positive integer");
}
if (!(iof->flags & (IO_READ | IO_UPDATE))) return dst_throw(args, "file is not readable");
/* Ensure buffer size */
if (dst_buffer_extra(b, len)) return dst_throw(args, "buffer overflow");
+13 -8
View File
@@ -307,10 +307,13 @@ const uint8_t *dst_short_description(Dst x) {
return dst_unwrap_string(x);
case DST_STRING:
return dst_escape_string(dst_unwrap_string(x));
case DST_ABSTRACT:
return string_description(
dst_abstract_type(dst_unwrap_abstract(x))->name,
dst_unwrap_abstract(x));
case DST_ABSTRACT:
{
const char *n = dst_abstract_type(dst_unwrap_abstract(x))->name;
return string_description(
n[0] == ':' ? n + 1 : n,
dst_unwrap_abstract(x));
}
default:
return string_description(dst_type_names[dst_type(x)] + 1, dst_unwrap_pointer(x));
}
@@ -345,10 +348,12 @@ void dst_short_description_b(DstBuffer *buffer, Dst x) {
dst_escape_buffer_b(buffer, dst_unwrap_buffer(x));
return;
case DST_ABSTRACT:
string_description_b(buffer,
dst_abstract_type(dst_unwrap_abstract(x))->name,
dst_unwrap_abstract(x));
return;
{
const char *n = dst_abstract_type(dst_unwrap_abstract(x))->name;
return string_description_b(buffer,
n[0] == ':' ? n + 1 : n,
dst_unwrap_abstract(x));
}
default:
string_description_b(buffer, dst_type_names[dst_type(x)] + 1, dst_unwrap_pointer(x));
break;