Skip to content

Commit

Permalink
Merge pull request #130 from billhails/memstream2
Browse files Browse the repository at this point in the history
fgets on memstream only returns remaining text now
  • Loading branch information
billhails authored Nov 9, 2024
2 parents 182059b + eec41e3 commit 1d53463
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/builtin_io.c
Original file line number Diff line number Diff line change
Expand Up @@ -442,8 +442,11 @@ static Value private_fgets(FILE *fh) {
if (buf->buffer == NULL) {
cant_happen("fgets on null memstream");
}
char *b = buf->buffer;
do { pushByteArray(bytes, (Byte) *b); } while (*(b++));
if (buf->ptr == NULL) {
buf->ptr = buf->buffer;
}
do { pushByteArray(bytes, (Byte) *(buf->ptr)); } while (*(buf->ptr++));
buf->ptr--; // point back at '\0' for next time
} else {
int c;
while ((c = fgetc(fh)) != EOF) {
Expand All @@ -463,6 +466,10 @@ static Value builtin_gets() {
}

static Value private_fgetc(FILE *fh) {
HashSymbol *key = fileHandleToKey(fh);
if (getBuiltInMemBufHash(getMemBufs(), key, NULL)) {
cant_happen("getc on memory buffers not supported yet");
}
Character c = utf8Fgetc(fh);
return value_Character(c);
}
Expand Down
1 change: 1 addition & 0 deletions src/builtins.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ structs:

BuiltInMemBuf:
buffer: string=NULL
ptr: string=NULL
size: size=0

hashes:
Expand Down
13 changes: 13 additions & 0 deletions tests/fn/test_io.fn
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,16 @@ in
let data = fgetc(fh);
in assert(data == '\ua1;');
});

io.with_buffer(fn (fh) {
fputn(fh, 1234);
fputn(fh, 5678);
assert(fgets(fh) == "12345678");
});

io.with_buffer(fn (fh) {
fputn(fh, 1234);
assert(fgets(fh) == "1234");
fputn(fh, 5678);
assert(fgets(fh) == "5678");
})

0 comments on commit 1d53463

Please sign in to comment.