Debian Codegraph @

os/bufio.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use bufio;
5 use errors;
6 use fs;
7 use io;
8
9 // Opens a file and allocates read and/or write buffers for buffered I/O. To
10 // open an unbuffered [[io::file]] see [[open]].
11 //
12 // [[fs::flag::CREATE]] isn't very useful with this function, since the new
13 // file's mode is set to zero. For this use-case, use [[create]] instead.
14 export fn open_buffered(
15 path: str,
16 flags: fs::flag = fs::flag::RDONLY,
17 ) (bufio::stream | fs::error | nomem) = {
18 const (rd, wr) = mkbuffers(flags)?;
19 match (open(path, flags)) {
20 case let file: io::file =>
21 return bufio::init(file, rd, wr, bufio::flag::MANAGED);
22 case let err: fs::error =>
23 free(rd);
24 free(wr);
25 return err;
26 };
27 };
28
29 // Creates a new file with the given mode if it doesn't already exist and opens
30 // it for writing, allocating read and/or write buffers for buffered I/O. To
31 // open an unbuffered [[io::file]] see [[create]].
32 //
33 // Only the permission bits of the mode are used. If other bits are set, they
34 // are discarded.
35 export fn create_buffered(
36 path: str,
37 mode: fs::mode,
38 flags: fs::flag = fs::flag::WRONLY | fs::flag::TRUNC,
39 ) (bufio::stream | fs::error | nomem) = {
40 const (rd, wr) = mkbuffers(flags)?;
41 match (create(path, mode, flags)) {
42 case let file: io::file =>
43 return bufio::init(file, rd, wr, bufio::flag::MANAGED);
44 case let err: fs::error =>
45 free(rd);
46 free(wr);
47 return err;
48 };
49 };
50
51 fn mkbuffers(flags: fs::flag) (([]u8, []u8) | nomem) = {
52 const mode = flags & 0b11;
53 const need_read = mode != fs::flag::WRONLY;
54 const need_write = mode != fs::flag::RDONLY;
55
56 let ok = false;
57 let read: []u8 = [];
58 let write: []u8 = [];
59 defer if (!ok) {
60 free(read);
61 free(write);
62 };
63
64 if (need_read) {
65 read = alloc([0...], BUFSZ)?;
66 };
67
68 if (need_write) {
69 write = alloc([0...], BUFSZ)?;
70 };
71
72 ok = true;
73 return (read, write);
74 };