Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-10 09:44:01 -06:00
commit 4aa98abfe5
1625 files changed
+43592

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
#! @file paths.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains turning a path into a `file` URI and back, `std::io`'s paths being
#! read here so that `std::io` reads nothing of URIs.
import std::io;
module std::net;
#! Makes the `file` URI of an absolute path, as
#! `file:///usr/lib/my%20notes.txt`.
#! @param at The path, which must be absolute.
#! @param alloc The optional allocator for the text the URI holds.
#! @returns The URI, with each byte of the path but its delimiters and the
#! unreserved bytes percent-encoded, or why there is none.
#! @remarks On Windows, `C:\Users` is `file:///C:/Users`, and `\\server\share\x`
#! is `file://server/share/x`.
pub def uri::from_path(at: &path, alloc: maybe<&mut allocator> = nothing{}): result<uri, failure> {
if !at.is_absolute {
return failure { message = $"`{at.span}` is relative, and only an absolute path has a `file` URI" };
}
var made := string::new(alloc);
made.append("file://");
when os == windows {
uri::windows_uri(at.span, &mut made);
return uri::split(move(made));
}
for byte in at.span {
uri::encode_byte(byte, "/", &mut made);
}
return uri::split(move(made));
}
#! Makes the path a `file` URI names.
#! @param this The URI, whose scheme must be `file`.
#! @param alloc The optional allocator for the text the path holds.
#! @returns The path, decoded from the URI's, or why there is none: the URI
#! names another scheme, or a file on another machine, or a path no
#! path here can be. A query or fragment is left out.
#! @remarks On Windows, a URI naming a machine other than `localhost` names a
#! path on its share, as `file://server/share/x` names
#! `\\server\share\x`.
pub def uri::to_path(&this, alloc: maybe<&mut allocator> = nothing{}): result<path, failure> {
if !uri::same_letters(this.scheme, "file") {
return failure { message = $"`{this.span}` is not a `file` URI" };
}
var decoded := uri::decode(this.path, alloc);
if decoded is not value(&text) {
return failure { message = $"`{this.span}` has a `%` that two hexadecimal digits do not follow" };
}
val host := this.host;
when os == windows {
return uri::windows_path(host, text.span, alloc);
}
if !host.empty && !uri::same_letters(host, "localhost") {
return failure { message = $"`{this.span}` names a file on `{host}`, which no path here can" };
}
return path::parse(text.span, alloc);
}
# The Windows path a `file` URI names, from its host and decoded path:
# `\\host\share\x` for a host other than `localhost`, and `C:\x` for `/C:/x`.
def uri::windows_path(host: strview, text: strview, alloc: maybe<&mut allocator>): result<path, failure> {
if !host.empty && !uri::same_letters(host, "localhost") {
var share := string::new(alloc);
share.append("\\\\");
share.append(host);
share.append(text);
return path::parse(share.span, alloc);
}
if text.length >= 3 && text[0] == '/' && text[1].is_alpha && text[2] == ':' {
return path::parse(text.substr(1, text.length - 1), alloc);
}
return path::parse(text, alloc);
}
# Writes what follows `file://` in the URI of an absolute Windows path: the host
# and share of `\\host\share\x` as `host/share/x`, and `C:\x` as `/C:/x`.
def uri::windows_uri(text: strview, into: &mut string): void {
var at := 2u;
if text.starts_with("\\\\") {
while at < text.length && text[at] != '\\' {
uri::encode_byte(text[at], "", into);
at++;
}
} else {
into.push('/');
into.push(text[0]);
into.push(':');
}
while at < text.length {
val byte := text[at];
at++;
if byte == '\\' {
into.push('/');
continue;
}
uri::encode_byte(byte, "", into);
}
}
+986
View File
@@ -0,0 +1,986 @@
#! @file uri.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains URIs, as RFC 3986 defines them: reading one from text, its parts,
#! resolving one against another, its normal form, and percent-encoding.
#! `std::io` turns a `file` URI into a `path` and back.
import std::containers;
module std::net;
# The bytes that separate parts within a component, which a URI holds as they are.
const uri_sub_delims: strview = "!$&'()*+,;=";
const uri_hex_digits: strview = "0123456789ABCDEF";
#! A Uniform Resource Identifier (URI): a sequence of characters naming a
#! resource, such as a web page, a service, an email address, a phone number, a
#! book, a real-world object such as a person or a place, or a concept.
#!
#! A URI is written `scheme:` then, after `//`, an authority of user
#! information, a host, and a port, then a path, a query after `?`, and a
#! fragment after `#`:
#!
#! https://user@example.com:8080/docs/index.html?lang=en#intro
#!
#! Every part but the path may be left out, and a URI without a scheme is a
#! relative reference, as `../images/logo.png`, which `resolve` turns into a
#! whole URI against a base.
#!
#! A URI holds its text as it was written, and its parts are views of it, still
#! percent-encoded, as `%20` for a space; `uri::decode` gives what they hold.
#! Two URIs are equal when their text is. `normalized` gives the form in which
#! two URIs naming the same resource by their syntax are equal.
#!
#! @sa https://www.rfc-editor.org/rfc/rfc3986
pub struct uri
: owning
, hashable
, equatable
, copyable
, moveable
{
var _text: string;
var _scheme: u64; #! Where what follows the scheme's `:` begins, or 0 where there is none.
var _host: u64; #! Where the host begins, after `//` and any user information and `@`.
var _port: u64; #! Where the host ends: the `:` before a port, or the end of the authority.
var _path: u64; #! Where the path begins, which ends the authority.
var _query: u64; #! Where the path ends: the `?` before a query, or the `#`, or the end.
var _fragment: u64; #! Where the query ends: the `#` before a fragment, or the end.
}
#! A parameter of a query written as `name=value`, as `uri::parameters` gives
#! it.
pub struct uri::parameter {
pub var name: strview; #! As written, still percent-encoded.
pub var value: strview; #! As written, still percent-encoded, and empty where there is no `=`.
}
#! The scheme a URI starts with, which says how to read the rest.
#! @param this The URI to read.
#! @returns A view of the scheme, as `https`, without its `:`, which is empty
#! for a relative reference.
pub val uri::scheme: strview {
get {
return this._scheme == 0
? strview::blank()
: this.span.substr(0, this._scheme - 1);
}
}
#! Whether a URI has a scheme, and so names a resource without a base to resolve
#! it against.
#! @param this The URI to check.
#! @returns Whether it has a scheme, rather than being a relative reference.
pub val uri::is_absolute: bool {
get => this._scheme != 0;
}
#! The authority of a URI, which follows `//`.
#! @param this The URI to read.
#! @returns A view of the user information, host, and port, as `user@host:8080`,
#! or `nothing` where the URI has no `//`.
pub val uri::authority: maybe<strview> {
get {
if !this.has_authority() {
return nothing{};
}
return this.span.substr(this._scheme + 2, this._path - this._scheme - 2);
}
}
#! The user information of a URI's authority, before its `@`.
#! @param this The URI to read.
#! @returns A view of it, as `user:password`, or `nothing` where there is no
#! `@`.
pub val uri::userinfo: maybe<strview> {
get {
if !this.has_authority() || this._host == this._scheme + 2 {
return nothing{};
}
return this.span.substr(this._scheme + 2, this._host - this._scheme - 3);
}
}
#! The user a URI's user information names.
#! @param this The URI to read.
#! @returns A view of the user information before its first `:`, which is empty
#! where there is none.
pub val uri::user: strview {
get {
if this.userinfo is not some(info) {
return strview::blank();
}
return info.substr(0, uri::colon_in(info));
}
}
#! The password a URI's user information holds, which RFC 3986 advises against
#! writing in a URI at all.
#! @param this The URI to read.
#! @returns A view of the user information after its first `:`, or `nothing`
#! where it has none.
pub val uri::password: maybe<strview> {
get {
if this.userinfo is not some(info) {
return nothing{};
}
val colon := uri::colon_in(info);
if colon == info.length {
return nothing{};
}
return info.substr(colon + 1, info.length - colon - 1);
}
}
#! The host a URI's authority names.
#! @param this The URI to read.
#! @returns A view of the host, as `example.com` or `127.0.0.1`, or an IPv6
#! address without the brackets around it, as `::1`. It is empty where
#! the URI has no authority, or names none.
pub val uri::host: strview {
get {
val host := this.span.substr(this._host, this._port - this._host);
if host.length >= 2 && host[0] == '[' && host[host.length - 1] == ']' {
return host.substr(1, host.length - 2);
}
return host;
}
}
#! The port a URI's authority names.
#! @param this The URI to read.
#! @returns The port, or `nothing` where there is none, or its `:` has no digits
#! after it, which leaves the scheme's own.
pub val uri::port: maybe<u16> {
get {
if this._port >= this._path {
return nothing{};
}
val digits := this.span.substr(this._port + 1, this._path - this._port - 1);
if digits.empty {
return nothing{};
}
var value := 0u;
for byte in digits {
value = value * 10 + byte.digit_value;
}
return value as u16;
}
}
#! The path of a URI, which every URI has, though it may be empty.
#! @param this The URI to read.
#! @returns A view of the path, as `/docs/index.html`, still percent-encoded.
pub val uri::path: strview {
get => this.span.substr(this._path, this._query - this._path);
}
#! The query of a URI, after its `?`.
#! @param this The URI to read.
#! @returns A view of the query, as `lang=en&page=2`, still percent-encoded, or
#! `nothing` where there is no `?`.
pub val uri::query: maybe<strview> {
get {
if this._query == this._fragment {
return nothing{};
}
return this.span.substr(this._query + 1, this._fragment - this._query - 1);
}
}
#! The fragment of a URI, after its `#`, which names a part of the resource.
#! @param this The URI to read.
#! @returns A view of the fragment, still percent-encoded, or `nothing` where
#! there is no `#`.
pub val uri::fragment: maybe<strview> {
get {
if this._fragment == this._text.length {
return nothing{};
}
return this.span.substr(this._fragment + 1, this._text.length - this._fragment - 1);
}
}
#! Reads text as a URI or a relative reference.
#! @param text The text to read, as `https://example.com/a?b#c`, `../d`, or
#! `#e`. Empty text is a reference to the document it is in.
#! @param alloc The optional allocator for the text the URI holds.
#! @returns The URI, or why the text is not one. Bytes a part cannot hold, such
#! as a space, must already be percent-encoded, as `uri::encode` does.
pub def uri::parse(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): result<uri, failure> {
var made := uri { _text = string::from(text, alloc) };
made.locate();
var message := made.problem();
if message.length > 0 {
return failure { message = move(message) };
}
return move(made);
}
#! Percent-encodes text, so that a URI can hold it within one of its parts.
#! @param text The text to encode.
#! @param keep The bytes to keep as they are, besides the unreserved letters,
#! digits, `-`, `.`, `_`, and `~`, as `/` to encode a path.
#! @param alloc The optional allocator for the encoded text.
#! @returns The text, with every other byte written as `%` and two upper-case
#! hexadecimal digits, as a space is `%20`.
pub def uri::encode(
text: strview,
keep: strview = "",
alloc: maybe<&mut allocator> = nothing{}
): string {
var made := string::new(alloc);
made.reserve(text.length);
for byte in text {
uri::encode_byte(byte, keep, &mut made);
}
return made;
}
#! Decodes percent-encoded text, as a part of a URI holds it.
#! @param text The text to decode, as `my%20notes`.
#! @param alloc The optional allocator for the decoded text.
#! @returns The text, with each `%` and the two hexadecimal digits after it
#! written as the byte they are, or why it cannot be decoded. A `+` is
#! left as it is, since only forms write a space as one.
pub def uri::decode(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): result<string, failure> {
var made := string::new(alloc);
if !uri::decode_into(text, &mut made, false) {
return failure { message = $"`{text}` has a `%` that two hexadecimal digits do not follow" };
}
return move(made);
}
#! Decodes percent-encoded text as `decode` does, but leniently, as editors and
#! browsers read what they are given: a `%` that two hexadecimal digits do not
#! follow is kept as it is.
#! @param text The text to decode, as `100%25 of my%20notes`.
#! @param alloc The optional allocator for the decoded text.
#! @returns The text, with each `%` and the two hexadecimal digits after it
#! written as the byte they are, and everything else as it is.
pub def uri::decode_lenient(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): string {
var made := string::new(alloc);
uri::decode_into(text, &mut made, true);
return made;
}
#! Creates a copy of the provided URI.
#! @param other The URI to copy.
#! @returns The copy, which owns its own text, with the other's allocator.
pub def uri::copy_of(other: &uri): uri {
return uri {
_text = string::copy_of(&other._text),
_scheme = other._scheme,
_host = other._host,
_port = other._port,
_path = other._path,
_query = other._query,
_fragment = other._fragment
};
}
#! Creates a new URI by moving the text of another into it.
#! @param other The URI to move from, which is empty after.
#! @returns The moved URI, which takes the text and allocator with it.
pub def uri::move_of(other: &mut uri): uri {
val made: uri = uri {
_text = string::move_of(&mut other._text),
_scheme = other._scheme,
_host = other._host,
_port = other._port,
_path = other._path,
_query = other._query,
_fragment = other._fragment
};
other.locate();
return made;
}
#! A view of the text of a URI, as it was written.
#! @param this The URI to view.
#! @returns A view of its text, which is only good until the URI closes.
pub val uri::span: strview {
get => this._text.span;
}
#! Views each segment of a URI's path, between its `/`s, in turn.
#! @param this The URI to split.
#! @returns The segments, still percent-encoded, each viewing into the URI's
#! text. A `/` the path starts with is left out, so `/a/b` holds `a`
#! and `b`, and one it ends with leaves an empty segment last. An empty
#! path has none.
pub def uri::segments(&this): splits {
var path := this.path;
if path.empty {
return splits::empty();
}
if path[0] == '/' {
path = path.substr(1, path.length - 1);
}
return path.split('/');
}
#! Views each parameter of a URI's query, as `name=value` pairs separated by
#! `&`, which is how forms and most programs write a query.
#! @param this The URI to read.
#! @param alloc The allocator for the list that will be created.
#! @returns The parameters, in order, each viewing into the URI's text. Empty
#! pairs, as in `a=1&&b=2`, are left out.
pub def uri::parameters(&this, alloc: maybe<&mut allocator> = nothing{}): vector<uri::parameter> {
var found := vector::<uri::parameter>::new(alloc);
if this.query is not some(query) {
return found;
}
var start := 0u;
while start <= query.length {
var end := start;
while end < query.length && query[end] != '&' {
end++;
}
val pair := query.substr(start, end - start);
start = end + 1;
if pair.empty {
continue;
}
var equal := 0u;
while equal < pair.length && pair[equal] != '=' {
equal++;
}
found.append(uri::parameter {
name = pair.substr(0, equal),
value = equal < pair.length
? pair.substr(equal + 1, pair.length - equal - 1)
: strview::blank()
});
}
return found;
}
#! Finds the value of the first parameter of a URI's query with a name.
#! @param this The URI to read.
#! @param name The name to look for, as it is written in the query.
#! @returns A view of the value, still percent-encoded, or `nothing` where no
#! parameter has the name.
pub def uri::query_value(&this, name: strview): maybe<strview> {
for &each in this.parameters() {
if each.name == name {
return each.value;
}
}
return nothing{};
}
#! Resolves a reference against a base, as RFC 3986 does in section 5.2: a whole
#! URI is taken as it is, and anything it leaves out is taken from the base,
#! with a relative path following on from the base's.
#! @param this The reference to resolve, as `../c?d` or `#e`.
#! @param base The URI it is relative to, which has a scheme.
#! @returns The resolved URI, whose path holds no `.` or `..` segments, as
#! `http://a/b/c?d` from `../c?d` against `http://a/b/x/y`.
pub def uri::resolve(&this, base: &uri): uri {
var made := string::new(this._text.alloc);
if this.is_absolute || this.has_authority() {
made.append(this.is_absolute ? this.scheme_part() : base.scheme_part());
made.append(this.authority_part());
uri::remove_dots(this.path, &mut made);
made.append(this.query_part());
} else {
made.append(base.scheme_part());
made.append(base.authority_part());
this.merge_onto(base, &mut made);
}
made.append(this.fragment_part());
return uri::split(move(made));
}
#! Makes the normal form of a URI, as RFC 3986 does in section 6.2.2, in which
#! two URIs that name the same resource by their syntax alone are equal.
#! @param this The URI to normalize.
#! @returns The URI with its scheme and host in lower case, each
#! percent-encoding of an unreserved byte decoded and the rest in upper
#! case, and, where it has a scheme, no `.` or `..` segments. A `:`
#! without a port is left out.
pub def uri::normalized(&this): uri {
val text := this.span;
var made := string::new(this._text.alloc);
for byte in this.scheme_part() {
made.push(byte.to_lower);
}
if this.has_authority() {
made.append("//");
if this.userinfo is some(info) {
uri::normalize_into(info, &mut made, false);
made.push('@');
}
uri::normalize_into(text.substr(this._host, this._port - this._host), &mut made, true);
if this._port + 1 < this._path {
made.append(text.substr(this._port, this._path - this._port));
}
}
if this.is_absolute {
var path := string::new(nothing{});
uri::normalize_into(this.path, &mut path, false);
uri::remove_dots(path.span, &mut made);
} else {
uri::normalize_into(this.path, &mut made, false);
}
if this.query is some(query) {
made.push('?');
uri::normalize_into(query, &mut made, false);
}
if this.fragment is some(fragment) {
made.push('#');
uri::normalize_into(fragment, &mut made, false);
}
return uri::split(move(made));
}
#! Gives back the memory holding the text of a URI.
#! @param this The URI to close.
pub def uri::close(&mut this): void {
this._text.close();
this.locate();
}
#! Compares one URI to another by equality.
#! @param this The URI to compare against.
#! @param other The URI to compare with.
#! @returns Whether both have the same text. Compare their `normalized` forms to
#! ask whether they name the same resource.
pub def uri::equals(&this, other: &uri): bool {
return this._text.equals(&other._text);
}
#! Hashes the provided URI.
#! @param this The URI to hash.
#! @returns The hash code of its text, which equal URIs share.
pub def uri::hash(&this): u64 {
return this._text.hash();
}
# Makes a URI of text that is known to be one, as what `resolve` and `normalized`
# write is, finding where its parts are.
def uri::split(text: string): uri {
var made := uri { _text = move(text) };
made.locate();
return made;
}
# Finds where each part of the text begins and ends, as RFC 3986 does in its
# appendix B, without asking whether the parts are what they should be.
def uri::locate(&mut this): void {
val text := this._text.span;
val n := text.length;
var at := 0u;
while at < n && text[at] != ':' && text[at] != '/' && text[at] != '?' && text[at] != '#' {
at++;
}
this._scheme = at < n && text[at] == ':' ? at + 1 : 0;
at = this._scheme;
this._host = at;
this._port = at;
if at + 1 < n && text[at] == '/' && text[at + 1] == '/' {
at += 2;
var end := at;
while end < n && text[end] != '/' && text[end] != '?' && text[end] != '#' {
end++;
}
# The user information ends at the last `@`, and a port follows the first `:`
# after the host, which is after the `]` of an address in brackets.
var host := at;
for k in at..end {
if text[k] == '@' {
host = k + 1;
}
}
var port := host;
if port < end && text[port] == '[' {
while port < end && text[port] != ']' {
port++;
}
}
while port < end && text[port] != ':' {
port++;
}
this._host = host;
this._port = port;
at = end;
}
this._path = at;
while at < n && text[at] != '?' && text[at] != '#' {
at++;
}
this._query = at;
if at < n && text[at] == '?' {
while at < n && text[at] != '#' {
at++;
}
}
this._fragment = at;
}
# Why the parts `locate` found are not what RFC 3986 lets them be, or nothing
# where they are.
def uri::problem(&this): string {
val text := this.span;
if this._scheme > 0 {
val scheme := text.substr(0, this._scheme - 1);
if scheme.empty {
return $"`{text}` has a `:` where a scheme should end, but no scheme before it";
}
if !scheme[0].is_alpha {
return $"`{scheme}` is not a scheme, which starts with a letter";
}
for byte in scheme {
if !byte.is_alnum && byte != '+' && byte != '-' && byte != '.' {
return $"`{scheme}` is not a scheme, which only letters, digits, `+`, `-`, and `.` make";
}
}
}
if this.has_authority() {
var why := this.authority_problem();
if why.length > 0 {
return move(why);
}
}
val path := this.path;
val bad := uri::invalid_in(path, ":@/");
if bad is some {
return uri::holds(text, path, bad.some, "path");
}
if this.query is some(query) {
val wrong := uri::invalid_in(query, ":@/?");
if wrong is some {
return uri::holds(text, query, wrong.some, "query");
}
}
if this.fragment is some(fragment) {
val wrong := uri::invalid_in(fragment, ":@/?");
if wrong is some {
return uri::holds(text, fragment, wrong.some, "fragment");
}
}
return "";
}
# Why the user information, host, or port of the authority is not what they may
# be, or nothing where they are.
def uri::authority_problem(&this): string {
val text := this.span;
if this.userinfo is some(info) {
val bad := uri::invalid_in(info, ":");
if bad is some {
return uri::holds(text, info, bad.some, "user information");
}
}
val host := text.substr(this._host, this._port - this._host);
if host.length > 0 && host[0] == '[' {
if host.length < 2 || host[host.length - 1] != ']' {
return $"`{text}` opens an address with `[` but does not close it with `]`";
}
val inside := host.substr(1, host.length - 2);
if !uri::is_ip_literal(inside) {
return $"`{inside}` is not an IPv6 address";
}
} else {
val bad := uri::invalid_in(host, "");
if bad is some {
return uri::holds(text, host, bad.some, "host");
}
}
if this._port >= this._path {
return "";
}
val digits := text.substr(this._port + 1, this._path - this._port - 1);
var value := 0u;
for byte in digits {
if !byte.is_digit {
return $"`{digits}` is not a port, which only digits make";
}
value = value * 10 + byte.digit_value;
if value > 65535 {
return $"`{digits}` is past 65535, the highest port";
}
}
return "";
}
# Says which byte of a part a URI cannot hold as it is.
def uri::holds(text: strview, part: strview, at: u64, name: strview): string {
if part[at] == '%' {
return $"`{text}` has a `%` in its {name} that two hexadecimal digits do not follow";
}
return $"`{text}` holds `{part.substr(at, 1)}` in its {name}, which a URI holds only percent-encoded";
}
# Gives the index of the first byte of a part that it cannot hold, where only
# unreserved bytes, percent-encodings, sub-delimiters, and `allowed` may be.
def uri::invalid_in(part: strview, allowed: strview): maybe<u64> {
var at := 0u;
while at < part.length {
val byte := part[at];
if byte == '%' {
if at + 2 >= part.length || !part[at + 1].is_hex || !part[at + 2].is_hex {
return at;
}
at += 3;
continue;
}
if !uri::is_unreserved(byte) && !uri::is_sub_delim(byte) && !allowed.contains(&byte) {
return at;
}
at++;
}
return nothing{};
}
def uri::is_unreserved(byte: u8): bool {
return byte.is_alnum || byte == '-' || byte == '.' || byte == '_' || byte == '~';
}
def uri::is_sub_delim(byte: u8): bool {
return uri_sub_delims.contains(&byte);
}
# Whether what is between the brackets of a host is an IPv6 address, or a future
# form of address, which starts with `v`.
def uri::is_ip_literal(text: strview): bool {
if text.length > 0 && (text[0] == 'v' || text[0] == 'V') {
return uri::is_ip_future(text);
}
return uri::is_ipv6(text);
}
# `v`, its version in hexadecimal, `.`, then unreserved bytes, sub-delimiters,
# and `:`.
def uri::is_ip_future(text: strview): bool {
var at := 1u;
while at < text.length && text[at].is_hex {
at++;
}
if at == 1 || at + 1 >= text.length || text[at] != '.' {
return false;
}
at++;
while at < text.length {
val byte := text[at];
if !uri::is_unreserved(byte) && !uri::is_sub_delim(byte) && byte != ':' {
return false;
}
at++;
}
return true;
}
# Eight groups of up to four hexadecimal digits separated by `:`, where `::` may
# stand for one or more groups of zeros once, and an IPv4 address may stand for
# the last two.
def uri::is_ipv6(text: strview): bool {
var groups := 0u;
var elided: bool = false;
var at := 0u;
if text.starts_with("::") {
elided = true;
at = 2;
if at == text.length {
return true;
}
}
while true {
val start := at;
while at < text.length && text[at].is_hex && at - start < 5 {
at++;
}
if at < text.length && text[at] == '.' {
if !uri::is_ipv4(text.substr(start, text.length - start)) {
return false;
}
groups += 2;
break;
}
val digits := at - start;
if digits == 0 || digits > 4 {
return false;
}
groups++;
if at == text.length {
break;
}
if text[at] != ':' {
return false;
}
at++;
if at < text.length && text[at] == ':' {
if elided {
return false;
}
elided = true;
at++;
if at == text.length {
break;
}
continue;
}
if at == text.length {
return false;
}
}
return elided ? groups < 8 : groups == 8;
}
# Four numbers from 0 to 255 separated by `.`, none written with a leading zero.
def uri::is_ipv4(text: strview): bool {
var parts := 0u;
var at := 0u;
while parts < 4 {
val start := at;
var value := 0u;
while at < text.length && text[at].is_digit && at - start < 4 {
value = value * 10 + text[at].digit_value;
at++;
}
val digits := at - start;
if digits == 0 || digits > 3 || value > 255 || (digits > 1 && text[start] == '0') {
return false;
}
parts++;
if parts == 4 {
break;
}
if at >= text.length || text[at] != '.' {
return false;
}
at++;
}
return at == text.length;
}
# Whether a URI has an authority, which `//` starts.
def uri::has_authority(&this): bool {
val text := this.span;
return this._path >= this._scheme + 2 && text[this._scheme] == '/' && text[this._scheme + 1] == '/';
}
# The scheme with its `:`, or nothing for a relative reference.
def uri::scheme_part(&this): strview {
return this.span.substr(0, this._scheme);
}
# The authority with the `//` before it, or nothing where there is none.
def uri::authority_part(&this): strview {
return this.span.substr(this._scheme, this._path - this._scheme);
}
# The query with the `?` before it, or nothing where there is none.
def uri::query_part(&this): strview {
return this.span.substr(this._query, this._fragment - this._query);
}
# The fragment with the `#` before it, or nothing where there is none.
def uri::fragment_part(&this): strview {
return this.span.substr(this._fragment, this._text.length - this._fragment);
}
# Writes the path and query of a reference without a scheme or authority,
# resolved against a base, as RFC 3986 does in section 5.2.2.
def uri::merge_onto(&this, base: &uri, into: &mut string): void {
val path := this.path;
if path.empty {
into.append(base.path);
into.append(this.query is some ? this.query_part() : base.query_part());
return;
}
if path[0] == '/' {
uri::remove_dots(path, into);
into.append(this.query_part());
return;
}
# A relative path follows the base's up to its last `/`, or follows `/` where the
# base has an authority and no path.
var merged := string::new(nothing{});
val held := base.path;
if base.has_authority() && held.empty {
merged.push('/');
} else {
var slash := held.length;
while slash > 0 && held[slash - 1] != '/' {
slash--;
}
merged.append(held.substr(0, slash));
}
merged.append(path);
uri::remove_dots(merged.span, into);
into.append(this.query_part());
}
# Writes a path without its `.` and `..` segments, each `..` taking the segment
# before it away, as RFC 3986 does in section 5.2.4.
def uri::remove_dots(path: strview, into: &mut string): void {
val floor := into.length;
var at := 0u;
while at < path.length {
val rest := path.substr(at, path.length - at);
if rest.starts_with("../") {
at += 3;
continue;
}
if rest.starts_with("./") || rest.starts_with("/./") {
at += 2;
continue;
}
if rest == "/." {
into.push('/');
return;
}
if rest.starts_with("/../") {
uri::drop_segment(into, floor);
at += 3;
continue;
}
if rest == "/.." {
uri::drop_segment(into, floor);
into.push('/');
return;
}
if rest == "." || rest == ".." {
return;
}
var end := path[at] == '/' ? at + 1 : at;
while end < path.length && path[end] != '/' {
end++;
}
into.append(path.substr(at, end - at));
at = end;
}
}
# Takes the last segment of the path being written away, with the `/` before it,
# never reaching back before `floor`, where the path began.
def uri::drop_segment(into: &mut string, floor: u64): void {
var at := into.length;
while at > floor && into[at - 1] != '/' {
at--;
}
if at > floor {
at--;
}
into.resize(at);
}
# Writes a part in its normal form: each percent-encoding of an unreserved byte
# decoded, the rest with upper-case digits, and, where `lower` is set, every letter
# in lower case, as a host is written.
def uri::normalize_into(part: strview, into: &mut string, lower: bool): void {
var at := 0u;
while at < part.length {
val byte := part[at];
if byte != '%' || at + 2 >= part.length {
into.push(lower ? byte.to_lower : byte);
at++;
continue;
}
val decoded := (part[at + 1].digit_value * 16 + part[at + 2].digit_value) as u8;
if !uri::is_unreserved(decoded) {
into.push('%');
into.push(part[at + 1].to_upper);
into.push(part[at + 2].to_upper);
at += 3;
continue;
}
into.push(lower ? decoded.to_lower : decoded);
at += 3;
}
}
# Writes a byte as it is where it is unreserved or kept, and percent-encoded
# otherwise.
# Decodes percent-encoded text into a string, giving whether each `%` is
# followed by two hexadecimal digits. Where one is not, a lenient decoding keeps
# the `%` as it is and goes on, and any other stops.
def uri::decode_into(text: strview, into: &mut string, lenient: bool): bool {
into.reserve(text.length);
var at := 0u;
while at < text.length {
val byte := text[at];
if byte == '%' && at + 2 < text.length && text[at + 1].is_hex && text[at + 2].is_hex {
into.push((text[at + 1].digit_value * 16 + text[at + 2].digit_value) as u8);
at += 3;
continue;
}
if byte == '%' && !lenient {
return false;
}
into.push(byte);
at++;
}
return true;
}
def uri::encode_byte(byte: u8, keep: strview, into: &mut string): void {
if uri::is_unreserved(byte) || keep.contains(&byte) {
into.push(byte);
return;
}
into.push('%');
into.push(uri_hex_digits[byte >> 4]);
into.push(uri_hex_digits[byte & 15]);
}
# Where the first `:` of user information is, or its end.
def uri::colon_in(info: strview): u64 {
var at := 0u;
while at < info.length && info[at] != ':' {
at++;
}
return at;
}
# Whether two texts hold the same letters, whatever their case.
def uri::same_letters(a: strview, b: strview): bool {
if a.length != b.length {
return false;
}
for i in 0..a.length {
if a[i].to_lower != b[i].to_lower {
return false;
}
}
return true;
}