Commit e726b9c0
e726b9c0be0fMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
Read n bytes from IO#read(n)
f.read(5) ignored the count and returned the whole remaining file, so
the next read saw EOF. Route the argument form to a new sp_File_read_n
helper that reads up to n bytes from the current stream position
(advancing it), returns nil at EOF, and "" for read(0). The no-arg form
still reads the rest of the file.
Fixes #1248
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- e726b9c0be0f
- Parent
- 76a58f19e983
lib/sp_runtime.hmodifiedView file
@@ -1745,6 +1745,23 @@
17451745
ungetc(c, f->fp);17461746
return FALSE;17471747
}1748+
/* IO#read(n): read up to n bytes from the current position. Returns NULL1749+
(nil) at EOF for a positive n, "" for n == 0, and the whole rest for a1750+
negative n (treated as the no-count read). A short read produces a1751+
string of the bytes actually read. */1752+
static inline const char *sp_File_read_n(sp_File *f, mrb_int n) {1753+
if (!f || !f->fp) return NULL;1754+
if (n < 0) return sp_File_read(f);1755+
if (n == 0) return sp_str_empty;1756+
char *r = sp_str_alloc((size_t)n);1757+
size_t got = fread(r, 1, (size_t)n, f->fp);1758+
if (got == 0) return NULL;1759+
if ((mrb_int)got == n) { r[got] = 0; return r; }1760+
char *s = sp_str_alloc(got);1761+
memcpy(s, r, got);1762+
s[got] = 0;1763+
return s;1764+
}17481765
static inline const char *sp_File_path(sp_File *f) { return f && f->path ? f->path : sp_str_empty; }17491766
17501767
/* Array#inspect for each typed array: `[elem1, elem2, ...]` with eachspinel_codegen.rbmodifiedView file
Loading diff…
test/file_read_count.rbaddedView file
Loading diff…
test/file_read_count.rb.expectedaddedView file
Loading diff…