buffer.ha (1762B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 use strings; 5 6 export type buffer = struct { 7 buf: [MAX]u8, 8 end: size, 9 }; 10 11 // Initializes a new path buffer. 12 export fn init(items: str...) (buffer | error) = { 13 let buf = buffer { ... }; 14 push(&buf, items...)?; 15 return buf; 16 }; 17 18 // Sets the value of a path buffer to a list of components, overwriting any 19 // previous value. Returns the new string value of the path. 20 export fn set(buf: *buffer, items: str...) (str | error) = { 21 buf.end = 0; 22 return push(buf, items...); 23 }; 24 25 // Returns the current path stored in this buffer. 26 // The return value is borrowed from the buffer. Use [[strings::dup]] to 27 // extend the lifetime of the string. 28 export fn string(buf: *buffer) str = { 29 if (buf.end == 0) return "."; 30 return strings::fromutf8_unsafe(buf.buf[..buf.end]); 31 }; 32 33 // Check if a path is an absolute path. 34 export fn abs(path: (*buffer | str)) bool = match (path) { 35 case let path: str => return strings::hasprefix(path, sepstr); 36 case let buf: *buffer => return 0 < buf.end && buf.buf[0] == SEP; 37 }; 38 39 // Check if a path is the root directory. 40 export fn isroot(path: (*buffer | str)) bool = match (path) { 41 case let path: str => return path == sepstr; 42 case let buf: *buffer => return buf.end == 1 && buf.buf[0] == SEP; 43 }; 44 45 // Replaces all instances of '/' in a string with [[SEP]]. The result is 46 // statically-allocated. 47 export fn local(path: str) str = { 48 static let buf: [MAX]u8 = [0...]; 49 return _local(path, &buf); 50 }; 51 52 fn _local(path: str, buf: *[MAX]u8) str = { 53 let buf = buf[..0]; 54 const bytes = strings::toutf8(path); 55 56 for (let byte .. bytes) { 57 if (byte == '/') { 58 static append(buf, SEP)!; 59 } else { 60 static append(buf, byte)!; 61 }; 62 }; 63 return strings::fromutf8(buf)!; 64 };