Commit dfdea4bd

dfdea4bd91a5Merged

Sam Ruby <[email protected]> · 5 months ago · 5 files · +2 added · ~3 modified

Description

Add File.size class method

File.size(path) returns the byte size (via stat), or raises Errno::ENOENT on a missing path — matching MRI and the existing stat/open-based File class methods (File.mtime / File.read). The runtime already had no size-by-path helper; this adds sp_file_size plus the analyzer (→ Integer) and codegen dispatch, mirroring mtime.

Because it stats rather than reading, it's binary-safe by construction (counts embedded NUL bytes) and avoids slurping the whole file just to measure it — the workaround callers reach for today (File.read(p).length).

Test: test/file_size.rb (byte count incl. embedded NULs + the missing-path raise). make test: 951 pass / 0 fail / 0 error.

Details

Commit
dfdea4bd91a5
Parent
74498298f707

lib/sp_runtime.hmodifiedView file

@@ -5109,6 +5109,21 @@
51095109 return (sp_Time){(int64_t)st.st_mtim.tv_sec, (int32_t)st.st_mtim.tv_nsec, 0};
51105110 #endif
51115111 }
5112+/* File.size(path) -> byte size. Raises Errno::ENOENT on a missing path,
5113+ matching MRI (and sp_file_read / sp_file_mtime, which stat/open the
5114+ same way). */
5115+static mrb_int sp_file_size(const char *path) {
5116+ if (!path) {
5117+ sp_raise_cls("TypeError", "no implicit conversion of nil into String");
5118+ return 0;
5119+ }
5120+ struct stat st;
5121+ if (stat(path, &st) == -1) {
5122+ sp_raise_cls(errno == ENOENT ? "Errno::ENOENT" : "RuntimeError", sp_sprintf("%s @ File.size - %s", strerror(errno), path));
5123+ return 0;
5124+ }
5125+ return (mrb_int)st.st_size;
5126+}
51125127 static const char *sp_backtick(const char *cmd) {
51135128 FILE *p = popen(cmd, "r");
51145129 if (!p) { sp_last_status = -1; return sp_str_empty; }