use Cnile use Mem use Alloc allocate use Slice (Slice) use Str chars use StrView use Error or-fail, unreachable, panic use Iter next # TODO: make filename a general string # NOTE: silently allocate + 1 for a null terminator. fn try-read-contents (filename, al) file = Cnile.fopen(filename, 'r') if file Mem.is-ptr-null() return None Cnile.fseek(file, 0, Cnile.seek-end()) file-size = Cnile.ftell(file) Cnile.fseek(file, 0, Cnile.seek-set()) file-buf = al allocate(Mem.i32-size(file-size) + 1) as Slice U8 Cnile.fread(file-buf.ptr, file-size, 1, file) # not 1, file-size, cuz of some article on hn i read. file-buf Slice.set(Mem.i32-size(file-size), Char.nullchar() Char.char-u8()) Cnile.fclose(file) str = StrView { contents: file-buf Slice.subslice(0, file-buf.count - 1) } return Just(str) # alternate name: read-all fn read-contents (filename, al): try-read-contents(filename, al) or-fail('could not open file \(filename)!') fn try-write-contents (filename, contents) -> Bool file = Cnile.fopen(filename, 'w') if file Mem.is-ptr-null() return False # oh no, this is soooo bad. it = contents chars() while True case next(&it) None # ughh.... write the file char-by-char............ file Cnile.fclose() return True Just(c) chars-written = Char.fprintf-char(file, c) if chars-written < 0 return False return unreachable() fn write-contents (filename, contents) if not try-write-contents(filename, contents) panic('could not write to file \(filename)') # TODO: make filename a general string fn try-read-bytes (filename, al) file = Cnile.fopen(filename, 'rb') if file Mem.is-ptr-null() return None Cnile.fseek(file, 0, Cnile.seek-end()) file-size = Cnile.ftell(file) Cnile.fseek(file, 0, Cnile.seek-set()) file-buf = al allocate(Mem.i32-size(file-size)) as Slice U8 Cnile.fread(file-buf.ptr, 1, file-size, file) Cnile.fclose(file) return Just(file-buf) # alternate name: read-all fn read-bytes (filename, al): try-read-bytes(filename, al) or-fail('could not open file \(filename)!') fn try-write-bytes (filename, contents) file = Cnile.fopen(filename, 'wb') if file Mem.is-ptr-null() return False # oh no, this is soooo bad. it =& contents into-iter() while True case next(it) None # ughh.... write the file char-by-char............ file Cnile.fclose() return True Just(c) chars-written = Cnile.fwrite(Mem.cast-ptr(&c), 1, 1, file) if chars-written < 0 return False return unreachable() fn write-bytes (filename, contents) if not try-write-bytes(filename, contents) panic('could not write to file \(filename)')