| 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 = { |
| 35 |
match (path) { |
| 36 |
case let path: str => |
| 37 |
return strings::hasprefix(path, sepstr); |
| 38 |
case let buf: *buffer => |
| 39 |
return 0 < buf.end && buf.buf[0] == SEP; |
| 40 |
}; |
| 41 |
}; |
| 42 |
|
| 43 |
// Check if a path is the root directory. |
| 44 |
export fn isroot(path: (*buffer | str)) bool = { |
| 45 |
match (path) { |
| 46 |
case let path: str => |
| 47 |
return path == sepstr; |
| 48 |
case let buf: *buffer => |
| 49 |
return buf.end == 1 && buf.buf[0] == SEP; |
| 50 |
}; |
| 51 |
}; |
| 52 |
|
| 53 |
// Replaces all instances of '/' in a string with [[SEP]]. The result is |
| 54 |
// statically-allocated. |
| 55 |
export fn local(path: str) (str | too_long) = { |
| 56 |
static let buf: [MAX]u8 = [0...]; |
| 57 |
match (_local(path, &buf)) { |
| 58 |
case let s: str => |
| 59 |
return s; |
| 60 |
case nomem => |
| 61 |
return too_long; |
| 62 |
}; |
| 63 |
}; |
| 64 |
|
| 65 |
fn _local(path: str, buf: *[MAX]u8) (str | nomem) = { |
| 66 |
let buf = buf[..0]; |
| 67 |
const bytes = strings::toutf8(path); |
| 68 |
|
| 69 |
for (let byte .. bytes) { |
| 70 |
if (byte == '/') { |
| 71 |
static append(buf, SEP)?; |
| 72 |
} else { |
| 73 |
static append(buf, byte)?; |
| 74 |
}; |
| 75 |
}; |
| 76 |
return strings::fromutf8(buf)!; |
| 77 |
}; |