File: buffer.ha

package info (click to toggle)
hare 0.25.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,948 kB
  • sloc: asm: 1,264; makefile: 123; sh: 114; lisp: 101
file content (77 lines) | stat: -rw-r--r-- 1,883 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

use strings;

export type buffer = struct {
	buf: [MAX]u8,
	end: size,
};

// Initializes a new path buffer.
export fn init(items: str...) (buffer | error) = {
	let buf = buffer { ... };
	push(&buf, items...)?;
	return buf;
};

// Sets the value of a path buffer to a list of components, overwriting any
// previous value. Returns the new string value of the path.
export fn set(buf: *buffer, items: str...) (str | error) = {
	buf.end = 0;
	return push(buf, items...);
};

// Returns the current path stored in this buffer.
// The return value is borrowed from the buffer. Use [[strings::dup]] to
// extend the lifetime of the string.
export fn string(buf: *buffer) str = {
	if (buf.end == 0) return ".";
	return strings::fromutf8_unsafe(buf.buf[..buf.end]);
};

// Check if a path is an absolute path.
export fn abs(path: (*buffer | str)) bool = {
	match (path) {
	case let path: str =>
		return strings::hasprefix(path, sepstr);
	case let buf: *buffer =>
		return 0 < buf.end && buf.buf[0] == SEP;
	};
};

// Check if a path is the root directory.
export fn isroot(path: (*buffer | str)) bool = {
	match (path) {
	case let path: str =>
		return path == sepstr;
	case let buf: *buffer =>
		return buf.end == 1 && buf.buf[0] == SEP;
	};
};

// Replaces all instances of '/' in a string with [[SEP]]. The result is
// statically-allocated.
export fn local(path: str) (str | too_long) = {
	static let buf: [MAX]u8 = [0...];
	match (_local(path, &buf)) {
	case let s: str =>
		return s;
	case nomem =>
		return too_long;
	};
};

fn _local(path: str, buf: *[MAX]u8) (str | nomem) = {
	let buf = buf[..0];
	const bytes = strings::toutf8(path);

	for (let byte .. bytes) {
		if (byte == '/') {
			static append(buf, SEP)?;
		} else {
			static append(buf, byte)?;
		};
	};
	return strings::fromutf8(buf)!;
};