hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

buffer.ha (1771B)


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