ui_app

source of std::url

1// URLs as HTTP takes them (RFC 3986's subset `scheme://host:port/path?query`):2// parsing one, resolving a reference against one (a link, a redirection's3// Location), percent-encoding a query component and building a query.4//5// ```alloy6// import std::option;7// import std::string;8//9// const url = if (Url::parse(&"https://Tickets.example:8443/api/shows?q=paris#top") is ::Some |move u|) move u else {10//     expect(false);11//     return;12// };13// expect(url.scheme.view() == "https" && url.host.view() == "tickets.example" && url.port == 8443);14// expect(url.path.view() == "/api/shows" && url.query.view() == "q=paris");15// expect_equal(&url.target(), &String::from(&"/api/shows?q=paris"));16// if (url.resolve(&"../holds") is ::Some |&next|) {17//     expect_equal(&f"{next}", &String::from(&"https://tickets.example:8443/holds"));18// }19// var query = Query::empty();20// query.add(&"q", &"Saint-Étienne & co");21// query.add(&"page", &"2");22// expect_equal(&query.text, &String::from(&"?q=Saint-%C3%89tienne%20%26%20co&page=2"));23// ```2425import std::option;26import std::string;27import std::format;28import std::text;29import std::vector;3031// A URL with an authority: its scheme and host in lowercase, the port32// the scheme's default when none is written (80 for http, 443 for https,33// 0 for others), the path ("/" at least) and query as written, escapes34// kept, and no fragment.35exp type Url : Format = struct {36    exp scheme: String,37    exp host: String, // an IPv6 address without its brackets38    exp port: u16,39    exp path: String,40    exp query: String // after the '?', which is not kept; empty for none41};4243// The URL the text holds, None when it is not one of the form44// `scheme://host[:port][/path][?query][#fragment]`. User information45// (`user@`) is not taken.46exp fn Url::parse(text: &[u8]) -> Option<Url> {47    const colon = if (text.find(&"://", 0) is ::Some |at|) at else {48        return ::None;49    };50    const scheme = &text[..colon];51    if (!is_scheme(&scheme)) {52        return ::None;53    }54    // no spaces nor control characters, which a request line cannot carry55    for (text) |c| {56        if (c <= ' ' || c == 0x7F) {57            return ::None;58        }59    }60    var rest = &text[colon + 3..];61    if (rest.find_byte('#', 0) is ::Some |hash|) {62        rest = &rest[..hash];63    }64    var end = rest.length();65    for (rest, [..rest.length()]) |c, at| {66        if (c == '/' || c == '?') {67            end = at;68            break;69        }70    }71    const authority = &rest[..end];72    if (authority.find_byte('@', 0) is ::Some) {73        return ::None;74    }75    var host = &authority;76    var port_text: &[u8] = &"";77    if (authority.length() > 0 && authority[0] == '[') {78        const close = if (authority.find_byte(']', 0) is ::Some |c|) c else {79            return ::None;80        };81        host = &authority[1..close];82        if (close + 1 < authority.length()) {83            if (authority[close + 1] != ':') {84                return ::None;85            }86            port_text = &authority[close + 2..];87        }88    } else if (authority.find_byte(':', 0) is ::Some |c|) {89        host = &authority[..c];90        port_text = &authority[c + 1..];91    }92    if (host.length() == 0) {93        return ::None;94    }95    var url = Url {96        .scheme = lowercase(&scheme),97        .host = lowercase(&host),98        .port = 0,99        .path = String::from(&"/"),100        .query = String::empty()101    };102    url.port = default_port(&url.scheme.view());103    if (port_text.length() > 0) {104        if (port_text.length() > 5 || !all_digits(&port_text)) {105            return ::None;106        }107        const n = if (port_text.parse_integer() is ::Some |n|) n else 0;108        if (n > 65535) {109            return ::None;110        }111        url.port = n to u16;112    }113    const tail = &rest[end..];114    const question = if (tail.find_byte('?', 0) is ::Some |q|) q else tail.length();115    if (question > 0) {116        url.path = String::from(&tail[..question]);117    }118    if (question < tail.length()) {119        url.query = String::from(&tail[question + 1..]);120    }121    return ::Some(move url);122}123124// The URL a reference names from this one: a whole URL, `//host/path`,125// an absolute path, a relative path (`../a`, `b`), or a query alone, its126// `.` and `..` segments removed (RFC 3986, 5.2).127exp fn resolve(self base: &Url, reference: &[u8]) -> Option<Url> {128    var r = &reference;129    if (r.find_byte('#', 0) is ::Some |hash|) {130        r = &r[..hash];131    }132    for (r) |c| {133        if (c <= ' ' || c == 0x7F) {134            return ::None;135        }136    }137    if (r.find(&"://", 0) is ::Some |at| && is_scheme(&r[..at])) {138        return Url::parse(&r);139    }140    if (r.starts_with(&"//")) {141        return Url::parse(&f"{base.scheme}:{r}".view());142    }143    var url = copy base;144    if (r.length() == 0) {145        return ::Some(move url);146    }147    const question = if (r.find_byte('?', 0) is ::Some |q|) q else r.length();148    const path = &r[..question];149    url.query = String::from(if (question < r.length()) &r[question + 1..] else &"");150    if (path.length() == 0) {151        if (question == r.length()) {152            url.query = copy base.query;153        }154        return ::Some(move url);155    }156    var merged = String::empty();157    if (path[0] == '/') {158        merged.append(&path);159    } else {160        const last_slash = last_index(&base.path.view(), '/');161        merged.append(&base.path.view()[..last_slash + 1]);162        merged.append(&path);163    }164    url.path = without_dots(&merged.view());165    return ::Some(move url);166}167168// What a request names on its server: the path, with the query after a169// '?' when there is one.170exp fn target(self url: &Url) -> String {171    var out = copy url.path;172    if (url.query.length() > 0) {173        out.push('?');174        out.append(&url.query.view());175    }176    return move out;177}178179// `scheme://host`, with the port when it is not the scheme's default:180// what two URLs share when they are of one origin.181exp fn origin(self url: &Url) -> String {182    var out = f"{url.scheme}://";183    url.write_host(&var out);184    return move out;185}186187// The host as HTTP's Host header gives it: with the port when it is not188// the scheme's default, an IPv6 address in brackets.189exp fn authority(self url: &Url) -> String {190    var out = String::empty();191    url.write_host(&var out);192    return move out;193}194195fn write_host(self url: &Url, out: &var String) {196    if (url.host.view().find_byte(':', 0) is ::Some) {197        out.push('[');198        out.append(&url.host.view());199        out.push(']');200    } else {201        out.append(&url.host.view());202    }203    if (url.port != default_port(&url.scheme.view())) {204        out.push(':');205        out.write(&url.port);206    }207}208209exp fn format(self url: &Url, out: &var String) {210    out.append(&url.origin().view());211    out.append(&url.target().view());212}213214// The text percent-encoded for a query's name or value, or a path's215// segment: every byte but letters, digits and `-._~` as `%XX`.216exp fn encoded(text: &[u8]) -> String {217    var out = String::with_capacity(text.length());218    for (text) |c| {219        if (220            is_letter(c)221            || (c >= '0' && c <= '9')222            || c == '-'223            || c == '.'224            || c == '_'225            || c == '~'226        ) {227            out.push(c);228        } else {229            out.push('%');230            out.push(HEX[(c >> 4) to u64]);231            out.push(HEX[(c & 15) to u64]);232        }233    }234    return move out;235}236237// The text with its `%XX` escapes decoded, and `+` as a space when238// `plus` (a form's encoding); None when an escape is not two hex digits.239exp fn decoded(text: &[u8], plus: bool) -> Option<String> {240    var out = String::with_capacity(text.length());241    var at: u64 = 0;242    while (at < text.length()) {243        const c = text[at];244        if (c == '%') {245            if (246                at + 2 < text.length()247                && hex_digit(text[at + 1]) is ::Some |high|248                && hex_digit(text[at + 2]) is ::Some |low|249            ) {250                out.push(high << 4 | low);251                at += 3;252                continue;253            }254            return ::None;255        }256        out.push(if (plus && c == '+') ' ' else c);257        at += 1;258    }259    return ::Some(move out);260}261262// A query built a pair at a time, each name and value percent-encoded:263// `?a=1&b=two`, empty while it has none.264exp type Query = struct {265    exp text: String266};267268exp fn Query::empty() -> Query {269    return Query { .text = String::empty() };270}271272exp fn add(self query: &var Query, name: &[u8], value: &[u8]) {273    query.text.push(if (query.text.length() == 0) '?' else '&');274    query.text.append(&encoded(&name).view());275    query.text.push('=');276    query.text.append(&encoded(&value).view());277}278279const HEX: [u8 : 16] = [280    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'281];282283fn hex_digit(c: u8) -> Option<u8> {284    if (c >= '0' && c <= '9') {285        return ::Some(c - '0');286    }287    if (c >= 'a' && c <= 'f') {288        return ::Some(c - 'a' + 10);289    }290    if (c >= 'A' && c <= 'F') {291        return ::Some(c - 'A' + 10);292    }293    return ::None;294}295296// A letter, then letters, digits, '+', '-' or '.'.297fn is_scheme(text: &[u8]) -> bool {298    if (text.length() == 0 || !is_letter(text[0])) {299        return false;300    }301    for (text) |c| {302        if (!is_letter(c) && !(c >= '0' && c <= '9') && c != '+' && c != '-' && c != '.') {303            return false;304        }305    }306    return true;307}308309fn is_letter(c: u8) -> bool => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');310311fn all_digits(text: &[u8]) -> bool {312    for (text) |c| {313        if (c < '0' || c > '9') {314            return false;315        }316    }317    return true;318}319320fn lowercase(text: &[u8]) -> String {321    var out = String::with_capacity(text.length());322    for (text) |c| {323        out.push(if (c >= 'A' && c <= 'Z') c + 32 else c);324    }325    return move out;326}327328fn default_port(scheme: &[u8]) -> u16 {329    if (scheme == "http") {330        return 80;331    }332    if (scheme == "https") {333        return 443;334    }335    return 0;336}337338fn last_index(text: &[u8], byte: u8) -> u64 {339    var at = text.length();340    while (at > 0) {341        at -= 1;342        if (text[at] == byte) {343            return at;344        }345    }346    return 0;347}348349// The path with its `.` and `..` segments removed (RFC 3986, 5.2.4).350fn without_dots(path: &[u8]) -> String {351    var segments = Vector<&[u8]>::empty();352    var start: u64 = 1;353    var at: u64 = 1;354    while (at <= path.length()) {355        if (at == path.length() || path[at] == '/') {356            const segment = &path[start..at];357            const last = at == path.length();358            if (segment == "..") {359                segments.pop();360                if (last) {361                    segments.push(&"");362                }363            } else if (segment == ".") {364                if (last) {365                    segments.push(&"");366                }367            } else {368                segments.push(&segment);369            }370            start = at + 1;371        }372        at += 1;373    }374    var out = String::empty();375    for (segments.view()) |&segment| {376        out.push('/');377        out.append(&segment);378    }379    if (out.length() == 0) {380        out.push('/');381    }382    return move out;383}