From 17e33fdc7aea601d4fd67faf776289789b36d172 Mon Sep 17 00:00:00 2001 From: Scott Olsen Date: Thu, 21 Apr 2022 21:35:43 -0400 Subject: [PATCH] reader: update fread call improve byte-reader perf This change was motivated by the performance of the original byte-reader implementation, which was quite slow since it read a file one byte at a time. Using fread instead, we can net some performance gains. This currently depends on a signature change to fread in Carp's core library which isn't at HEAD yet, so that blocks this change. Assuming that change merges into upstream, we need to also update the string-reader implementation--this commit handles that as well. --- src/byte-reader.carp | 15 ++++++--------- src/string-reader.carp | 2 +- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/byte-reader.carp b/src/byte-reader.carp index fb0f798..fa1246f 100644 --- a/src/byte-reader.carp +++ b/src/byte-reader.carp @@ -9,15 +9,12 @@ (doc read-bytes "Read `n` bytes from a file.") (defn read-bytes [f n] (let-do [bytes (Array.allocate n) - i 0 - result (Result.Success [])] - (while-do (< i n) - (match (read-byte @(file f)) - (Result.Success b) (Array.aset-uninitialized! &bytes i b) - (Result.Error err) (do (set! result (Result.Error err)) (break))) - (++ i)) - (when (not (error? &result)) (set! result (Result.Success bytes))) - result)) + result (IO.Raw.fread (Array.unsafe-raw &bytes) 1 n @(file f))] + (if (IO.Raw.feof @(file f)) + (Result.Error @"EOF encountered while reading") + (if (IO.Raw.ferror @(file f)) + (Result.Error @"Error encountered while reading") + (Result.Success bytes))))) (implements read-from-file read-bytes) (doc read diff --git a/src/string-reader.carp b/src/string-reader.carp index ffe4a37..57a5b2f 100644 --- a/src/string-reader.carp +++ b/src/string-reader.carp @@ -7,7 +7,7 @@ "the file is not readable.") (defn read-string [f len] (let-do [s (String.allocate len (Char.from-int 0))] - (ignore (IO.Raw.fread &s 1 len @(file f))) + (ignore (IO.Raw.fread (String.cstr &s) 1 len @(file f))) (Result.Success s))) (implements read-from-file read-string)