/development/std/path/utf8_path.nct
utf8_path.nct
//! UTF-8 path representation, validation, and joining.
include ./index.nct
use std/string.{String, bytes}
struct Utf8Path {
text: String
}
construct Utf8Path {
default func new(value: &str): Self! {
validate(value)?
return Utf8Path { text: String.copy(value) }
}
}
instance Utf8Path {
/// Exposes the validated UTF-8 path text without transferring ownership.
coerce &self as &str {
return &self.text as &str
}
method &self.is_absolute(): bool { return is_absolute(self) }
method &self.join(child: &str): Utf8Path! { return join(self, child)? }
}
func is_absolute(path: &Utf8Path): bool {
let value: &str = &path.text as &str
let raw: &[u8] = bytes(value)
return value.len() != 0 && raw[0] == 47
}
func join(path: &Utf8Path, child: &str): Utf8Path! {
validate(child)?
let child_bytes: &[u8] = bytes(child)
if child.len() != 0 && child_bytes[0] == 47 {
return Utf8Path.new(child)?
}
var result = String.copy(&path.text as &str)
if result.len() != 0 && !result.ends_with("/") {
result.push_str("/")
}
result.push_str(child)
return Utf8Path { text: move result }
}
func validate(value: &str): void! {
let raw = bytes(value)
var offset: usize = 0
while offset < raw.len() {
if raw[offset] == 0 { return invalid_path() }
offset = offset + 1
}
return
}
func invalid_path(): error {
return error.new("std.path.invalid_path", "UTF-8 path contains a NUL byte")
}