Commit fa59ba18

fa59ba18acbeMerged

Yusuke Endoh <[email protected]> · 6 months ago · 3 files · +1 added · ~2 modified

Description

feat(codegen+runtime): File.binread + binread(path).bytes

File.binread(path) is just an alias for File.read — both lower to sp_file_read. Wired up in infer_method_name_type (returns "string") and the codegen dispatcher.

File.binread(path).bytes is pattern-matched in the bytes codegen path and lowered to a new sp_file_binread_bytes helper. Plain sp_str_bytes(sp_file_read(path)) uses null-termination and stops at the first 0x00 byte, which is wrong for binary data (e.g. .nes ROM files where 0x00 appears mid-file). The new helper reads with the file's actual byte count via fseek + fread.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
fa59ba18acbe
Parent
d920667f4cc7

lib/sp_runtime.hmodifiedView file

@@ -783,6 +783,28 @@
783783 static const char *sp_backtick(const char *cmd) { FILE *p = popen(cmd, "r"); if (!p) return sp_str_empty; char *buf = sp_str_alloc_raw(4096); size_t n = fread(buf, 1, 4095, p); buf[n] = 0; pclose(p); return buf; }
784784 static const char *sp_file_basename(const char *path) { const char *s = strrchr(path, '/'); if (s) return s + 1; return path; }
785785
786+/* Read a file's bytes into a fresh IntArray. Distinct from
787+ `sp_str_bytes(sp_file_read(path))` because plain sp_str_bytes uses
788+ null-termination and stops at the first 0x00 byte — wrong for
789+ binary data (e.g. .nes ROM files). */
790+static sp_IntArray *sp_file_binread_bytes(const char *path) {
791+ FILE *f = fopen(path, "rb");
792+ sp_IntArray *a = sp_IntArray_new();
793+ if (!f) return a;
794+ fseek(f, 0, SEEK_END);
795+ long sz = ftell(f);
796+ fseek(f, 0, SEEK_SET);
797+ unsigned char *buf = (unsigned char *)malloc(sz > 0 ? (size_t)sz : 1);
798+ if (sz > 0) {
799+ size_t r = fread(buf, 1, sz, f);
800+ (void)r;
801+ for (long i = 0; i < sz; i++) sp_IntArray_push(a, (mrb_int)buf[i]);
802+ }
803+ free(buf);
804+ fclose(f);
805+ return a;
806+}
807+
786808 typedef struct sp_Proc { void *fn; void *cap; void (*cap_scan)(void *); } sp_Proc;
787809 static void sp_Proc_scan(void *p) { sp_Proc *pr = (sp_Proc *)p; if (pr->cap && pr->cap_scan) pr->cap_scan(pr->cap); }
788810 static sp_Proc *sp_proc_new(void *fn, void *cap, void (*cap_scan)(void *)) { sp_Proc *p = (sp_Proc *)sp_gc_alloc(sizeof(sp_Proc), NULL, sp_Proc_scan); p->fn = fn; p->cap = cap; p->cap_scan = cap_scan; return p; }