Commit 8d27a68f

8d27a68ff81cMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +1 added · ~2 modified

Description

Merge pull request #194 from mame/pr/file-binread

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

Details

Commit
8d27a68ff81c
Parent
3e608bc1cf76
Merge parent
fa59ba18acbe

lib/sp_runtime.hmodifiedView file

@@ -825,6 +825,28 @@
825825 return buf;
826826 }
827827
828+/* Read a file's bytes into a fresh IntArray. Distinct from
829+ `sp_str_bytes(sp_file_read(path))` because plain sp_str_bytes uses
830+ null-termination and stops at the first 0x00 byte — wrong for
831+ binary data (e.g. .nes ROM files). */
832+static sp_IntArray *sp_file_binread_bytes(const char *path) {
833+ FILE *f = fopen(path, "rb");
834+ sp_IntArray *a = sp_IntArray_new();
835+ if (!f) return a;
836+ fseek(f, 0, SEEK_END);
837+ long sz = ftell(f);
838+ fseek(f, 0, SEEK_SET);
839+ unsigned char *buf = (unsigned char *)malloc(sz > 0 ? (size_t)sz : 1);
840+ if (sz > 0) {
841+ size_t r = fread(buf, 1, sz, f);
842+ (void)r;
843+ for (long i = 0; i < sz; i++) sp_IntArray_push(a, (mrb_int)buf[i]);
844+ }
845+ free(buf);
846+ fclose(f);
847+ return a;
848+}
849+
828850 typedef struct sp_Proc { void *fn; void *cap; void (*cap_scan)(void *); } sp_Proc;
829851 static void sp_Proc_scan(void *p) { sp_Proc *pr = (sp_Proc *)p; if (pr->cap && pr->cap_scan) pr->cap_scan(pr->cap); }
830852 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; }