First 0.7 update, removing all deprecated features.

This commit is contained in:
Christoffer Lerno
2025-02-27 14:16:36 +01:00
committed by Christoffer Lerno
parent cff6697818
commit 2a895ec7be
1589 changed files with 2635 additions and 115363 deletions

406
lib/std/net/http.c3 Normal file
View File

@@ -0,0 +1,406 @@
module std::net::http;
/*
enum HttpStatus
{
PENDING,
COMPLETED,
FAILED
}
struct Http
{
HttpStatus status;
int status_code;
String reason;
String content_type;
String response_data;
}
fn Http* http_get(String url, Allocator using = allocator::temp())
{
return null;
}
fn Http* http_post(String url, Allocator using = allocator::temp())
{
return null;
}
fn void Http.destroy(Http* this)
{
}
fn HttpStatus Http.process(Http* this)
{
unreachable();
}
// Common across implementations
struct HttpInternal @private
{
inline Http http;
Allocator allocator;
int connect_pending;
int request_sent;
char[256] address;
char[256] request_header;
char* request_header_large;
String request_data;
char[1024] reason_phrase;
char[256] content_type;
usz data_size;
usz data_capacity;
void* data;
}
fn String! parse_url(String url, String* port, String* resource) @private
{
if (url[:7] != "http://") return NetError.INVALID_URL?;
url = url[7..];
usz end_index = url.index_of(":") ?? url.index_of("/") ?? url.len;
String address = url[:end_index];
String end_part = url[end_index..];
if (!end_part.len)
{
*port = "80";
*resource = {};
return address;
}
switch (end_part[0])
{
case ':':
end_index = end_part.index_of("/") ?? end_part.len;
end_part[:end_index].to_uint() ?? NetError.INVALID_URL?!;
*port = end_part[:end_index];
*resource = url[end_index..];
case '/':
*port = "80";
*resource = end_part;
default:
unreachable();
}
return address;
}
fn Socket! http_internal_connect(String address, uint port) @private
{
return tcp::connect_async(address, port)!;
}
fn HttpInternal* http_internal_create(usz request_data_size, Allocator allocator) @private
{
HttpInternal* internal = allocator.alloc(HttpInternal.sizeof + request_data_size)!!;
internal.status = PENDING;
internal.status_code = 0;
internal.response_data = {};
internal.allocator = allocator;
internal.connect_pending = 1;
internal.request_sent = 0;
// internal.reason = "";
// internal.content_type = "";
internal.data_size = 0;
internal.data_capacity = 64 * 1024;
internal.data = allocator.alloc(internal.data_capacity)!!;
internal.request_data = {};
return internal;
}
fn Http*! http_get(String url, Allocator allocator = allocator::temp())
{
$if env::WIN32:
int[1024] wsa_data;
if (_wsa_startup(1, &wsa_data) != 0) return NetError.GENERAL_ERROR?;
$endif
uint port;
String resource;
String address = parse_url(url, &port, &resource)?;
Socket socket = tcp::connect(address, port)?;
HttpInternal* internal = http_internal_create(0, allocator);
internal.socket = socket;
char* request_header;
usz request_header_len = 64 + resource.len + address.len + port.len;
if (request_header_len < sizeof(internal.request_header))
{
internal.request_header_large = null;
request_header = internal.request_header;
}
else
{
internal.request_header_large = (char*)allocator.malloc(request_header_len + 1);
request_header = internal.request_header_large;
}
int default_http_port = port == "80";
sprintf( request_header, "GET %s HTTP/1.0\r\nHost: %s%s%s\r\n\r\n", resource, address, default_http_port ? "" : ":", default_http_port ? "" : port );
return internal;
}
fn Http*! http_post(String url, Allocator allocator = allocator::temp())
{
$if env::OS_TYPE == OsType::WIN32:
int[1024] wsa_data;
if (_wsa_startup(1, &wsa_data) != 0) return NetError.GENERAL_ERROR?;
$endif
String port;
String resource;
String address = parse_url(url, &port, &resource)?;
Socket socket = http_internal_connect(address, port)?;
HttpInternal* internal = http_internal_create(0, allocator);
internal.socket = socket;
char* request_header;
uz request_header_len = 64 + resource.len + address.len + port.len;
if (request_header_len < sizeof(internal.request_header))
{
internal.request_header_large = null;
request_header = internal.request_header;
}
else
{
internal.request_header_large = (char*)allocator.malloc(request_header_len + 1);
request_header = internal.request_header_large;
}
int default_http_port = port == "80";
sprintf( request_header, "POST %s HTTP/1.0\r\nHost: %s%s%s\r\nContent-Length: %d\r\n\r\n", resource, address, default_http_port ? "" : ":", default_http_port ? "" : port,
(int) size );
internal->request_data_size = size;
internal->request_data = ( internal + 1 );
memcpy( internal->request_data, data, size );
return internal;
}
fn HttpStatus Http.process(Http* http)
{
HttpInternal* internal = (HttpInternal*)http;
if (http.status == HttpStatus.FAILED) return http.status;
if (internal.connect_pending)
{
fd_set sockets_to_check;
FD_ZERO(&sockets_to_check);
FD_SET( internal->socket, &sockets_to_check );
struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0;
// check if socket is ready for send
if( select( (int)( internal->socket + 1 ), NULL, &sockets_to_check, NULL, &timeout ) == 1 )
{
int opt = -1;
socklen_t len = sizeof( opt );
if( getsockopt( internal->socket, SOL_SOCKET, SO_ERROR, (char*)( &opt ), &len) >= 0 && opt == 0 )
{
internal->connect_pending = 0; // if it is, we're connected
}
}
}
if (internal.connect_pending) retur http.status;
if (!internal.request_sent)
{
char* request_header = internal->request_header_large ?
internal.request_header_large : internal.request_header;
if (send(internal.socket, request_header, (int) strlen( request_header ), 0) == -1)
{
return http.status = FAILED;
}
if (internal.request_data_size)
{
int res = send(internal.socket, (char const*)internal->request_data, (int) internal->request_data_size, 0 );
if (res == -1)
{
http.status = HTTP_STATUS_FAILED;
return http.status;
}
}
internal.request_sent = 1;
return http.status;
}
// check if socket is ready for recv
fd_set sockets_to_check;
FD_ZERO( &sockets_to_check );
#pragma warning( push )
#pragma warning( disable: 4548 ) // expression before comma has no effect; expected expression with side-effect
FD_SET( internal->socket, &sockets_to_check );
#pragma warning( pop )
struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0;
}
http_status_t http_process( http_t* http )
{
while( select( (int)( internal->socket + 1 ), &sockets_to_check, NULL, NULL, &timeout ) == 1 )
{
char buffer[ 4096 ];
int size = recv( internal->socket, buffer, sizeof( buffer ), 0 );
if( size == -1 )
{
http->status = HTTP_STATUS_FAILED;
return http->status;
}
else if( size > 0 )
{
size_t min_size = internal->data_size + size + 1;
if( internal->data_capacity < min_size )
{
internal->data_capacity *= 2;
if( internal->data_capacity < min_size ) internal->data_capacity = min_size;
void* new_data = HTTP_MALLOC( memctx, internal->data_capacity );
memcpy( new_data, internal->data, internal->data_size );
HTTP_FREE( memctx, internal->data );
internal->data = new_data;
}
memcpy( (void*)( ( (uintptr_t) internal->data ) + internal->data_size ), buffer, (size_t) size );
internal->data_size += size;
}
else if( size == 0 )
{
char const* status_line = (char const*) internal->data;
int header_size = 0;
char const* header_end = strstr( status_line, "\r\n\r\n" );
if( header_end )
{
header_end += 4;
header_size = (int)( header_end - status_line );
}
else
{
http->status = HTTP_STATUS_FAILED;
return http->status;
}
// skip http version
status_line = strchr( status_line, ' ' );
if( !status_line )
{
http->status = HTTP_STATUS_FAILED;
return http->status;
}
++status_line;
// extract status code
char status_code[ 16 ];
char const* status_code_end = strchr( status_line, ' ' );
if( !status_code_end )
{
http->status = HTTP_STATUS_FAILED;
return http->status;
}
memcpy( status_code, status_line, (size_t)( status_code_end - status_line ) );
status_code[ status_code_end - status_line ] = 0;
status_line = status_code_end + 1;
http->status_code = atoi( status_code );
// extract reason phrase
char const* reason_phrase_end = strstr( status_line, "\r\n" );
if( !reason_phrase_end )
{
http->status = HTTP_STATUS_FAILED;
return http->status;
}
size_t reason_phrase_len = (size_t)( reason_phrase_end - status_line );
if( reason_phrase_len >= sizeof( internal->reason_phrase ) )
reason_phrase_len = sizeof( internal->reason_phrase ) - 1;
memcpy( internal->reason_phrase, status_line, reason_phrase_len );
internal->reason_phrase[ reason_phrase_len ] = 0;
status_line = reason_phrase_end + 1;
// extract content type
char const* content_type_start = strstr( status_line, "Content-Type: " );
if( content_type_start )
{
content_type_start += strlen( "Content-Type: " );
char const* content_type_end = strstr( content_type_start, "\r\n" );
if( content_type_end )
{
size_t content_type_len = (size_t)( content_type_end - content_type_start );
if( content_type_len >= sizeof( internal->content_type ) )
content_type_len = sizeof( internal->content_type ) - 1;
memcpy( internal->content_type, content_type_start, content_type_len );
internal->content_type[ content_type_len ] = 0;
}
}
http->status = http->status_code < 300 ? HTTP_STATUS_COMPLETED : HTTP_STATUS_FAILED;
http->response_data = (void*)( ( (uintptr_t) internal->data ) + header_size );
http->response_size = internal->data_size - header_size;
// add an extra zero after the received data, but don't modify the size, so ascii results can be used as
// a zero terminated string. the size returned will be the string without this extra zero terminator.
( (char*)http->response_data )[ http->response_size ] = 0;
return http->status;
}
}
return http->status;
}
void http_release( http_t* http )
{
http_internal_t* internal = (http_internal_t*) http;
#ifdef _WIN32
closesocket( internal->socket );
#else
close( internal->socket );
#endif
if( internal->request_header_large) HTTP_FREE( memctx, internal->request_header_large );
HTTP_FREE( memctx, internal->data );
HTTP_FREE( memctx, internal );
#ifdef _WIN32
WSACleanup();
#endif
}
#endif /* HTTP_IMPLEMENTATION */
/*
revision history:
1.0 first released version
*/
/*
------------------------------------------------------------------------------
This software is available under 2 licenses - you may choose the one you like.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2016 Mattias Gustavsson
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/*/

View File

@@ -56,19 +56,14 @@ fn usz! InetAddress.to_format(InetAddress* addr, Formatter* formatter) @dynamic
return formatter.printf("%d.%d.%d.%d", addr.ipv4.a, addr.ipv4.b, addr.ipv4.c, addr.ipv4.d)!;
}
fn String InetAddress.to_new_string(InetAddress* addr, Allocator allocator = allocator::heap()) @dynamic
fn String InetAddress.to_string(&self, Allocator allocator)
{
if (addr.is_ipv6)
{
char[8 * 5 + 1] buffer;
String res = (String)io::bprintf(&buffer, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x",
addr.ipv6.a, addr.ipv6.b, addr.ipv6.c, addr.ipv6.d,
addr.ipv6.e, addr.ipv6.f, addr.ipv6.g, addr.ipv6.h)!!;
return res.copy(allocator);
}
char[3 * 4 + 3 + 1] buffer;
String res = (String)io::bprintf(&buffer, "%d.%d.%d.%d", addr.ipv4.a, addr.ipv4.b, addr.ipv4.c, addr.ipv4.d)!!;
return res.copy(allocator);
return string::format(allocator, "%s", *self);
}
fn String InetAddress.to_tstring(&self)
{
return string::format(tmem(), "%s", *self);
}
fn InetAddress! ipv6_from_str(String s)

View File

@@ -58,14 +58,9 @@ fn uint! ipv4toint(String s)
return out;
}
fn String! int_to_new_ipv4(uint val, Allocator allocator = allocator::heap())
fn String! int_to_ipv4(uint val, Allocator allocator)
{
char[3 * 4 + 3 + 1] buffer;
String res = (String)io::bprintf(&buffer, "%d.%d.%d.%d", val >> 24, (val >> 16) & 0xFF, (val >> 8) & 0xFF, val & 0xFF)!;
return res.copy(allocator);
}
fn String! int_to_temp_ipv4(uint val)
{
return int_to_new_ipv4(val, allocator::temp());
}

View File

@@ -49,7 +49,7 @@ struct Url(Printable)
@require url_string.len > 0 "the url_string must be len 1 or more"
@return "the parsed Url"
*>
fn Url! temp_parse(String url_string) => new_parse(url_string, allocator::temp());
fn Url! tparse(String url_string) => parse(tmem(), url_string);
<*
Parse a URL string into a Url struct.
@@ -58,7 +58,7 @@ fn Url! temp_parse(String url_string) => new_parse(url_string, allocator::temp()
@require url_string.len > 0 "the url_string must be len 1 or more"
@return "the parsed Url"
*>
fn Url! new_parse(String url_string, Allocator allocator = allocator::heap())
fn Url! parse(Allocator allocator, String url_string)
{
url_string = url_string.trim();
if (!url_string) return UrlParsingResult.EMPTY?;
@@ -76,7 +76,7 @@ fn Url! new_parse(String url_string, Allocator allocator = allocator::heap())
// Handle schemes without authority like 'mailto:'
if (!pos) return UrlParsingResult.INVALID_SCHEME?;
url.scheme = url_string[:pos].copy(allocator);
url.path = decode(url_string[pos + 1 ..], PATH, allocator) ?? UrlParsingResult.INVALID_PATH?!;
url.path = decode(allocator, url_string[pos + 1 ..], PATH) ?? UrlParsingResult.INVALID_PATH?!;
return url;
}
@@ -98,8 +98,8 @@ fn Url! new_parse(String url_string, Allocator allocator = allocator::heap())
if (!username.len) return UrlParsingResult.INVALID_USER?;
url.host =
url.username = decode(username, HOST, allocator) ?? UrlParsingResult.INVALID_USER?!;
if (userpass.len) url.password = decode(userpass[1], USERPASS, allocator) ?? UrlParsingResult.INVALID_PASSWORD?!;
url.username = decode(allocator, username, HOST) ?? UrlParsingResult.INVALID_USER?!;
if (userpass.len) url.password = decode(allocator, userpass[1], USERPASS) ?? UrlParsingResult.INVALID_PASSWORD?!;
};
authority = authority[userinfo.len + 1 ..];
}
@@ -131,7 +131,7 @@ fn Url! new_parse(String url_string, Allocator allocator = allocator::heap())
}
};
}
url.host = decode(host, HOST, allocator) ?? UrlParsingResult.INVALID_HOST?!;
url.host = decode(allocator, host, HOST) ?? UrlParsingResult.INVALID_HOST?!;
url_string = url_string[authority_end ..];
}
@@ -142,12 +142,12 @@ fn Url! new_parse(String url_string, Allocator allocator = allocator::heap())
if (@ok(query_index) || @ok(fragment_index))
{
usz path_end = min(query_index ?? url_string.len, fragment_index ?? url_string.len);
url.path = decode(url_string[:path_end], PATH, allocator) ?? UrlParsingResult.INVALID_PATH?!;
url.path = decode(allocator, url_string[:path_end], PATH) ?? UrlParsingResult.INVALID_PATH?!;
url_string = url_string[path_end ..];
}
else
{
url.path = decode(url_string, PATH, allocator) ?? UrlParsingResult.INVALID_PATH?!;
url.path = decode(allocator, url_string, PATH) ?? UrlParsingResult.INVALID_PATH?!;
url_string = "";
}
@@ -165,86 +165,86 @@ fn Url! new_parse(String url_string, Allocator allocator = allocator::heap())
// Parse fragment
if (url_string.starts_with("#"))
{
url.fragment = decode(url_string[1..], FRAGMENT, allocator) ?? UrlParsingResult.INVALID_FRAGMENT?!;
url.fragment = decode(allocator, url_string[1..], FRAGMENT) ?? UrlParsingResult.INVALID_FRAGMENT?!;
}
return url;
}
<*
Stringify a Url struct.
@param [in] self
@param [inout] allocator
@return "Url as a string"
*>
fn String Url.to_string(&self, Allocator allocator = allocator::heap()) @dynamic => @pool(allocator)
fn usz! Url.to_format(&self, Formatter* f) @dynamic
{
DString builder = dstring::temp_new();
usz len;
// Add scheme if it exists
if (self.scheme != "")
{
builder.append_chars(self.scheme);
builder.append_char(':');
if (self.host.len > 0) builder.append_chars("//");
len += f.print(self.scheme)!;
len += f.print(":")!;
if (self.host.len > 0) len += f.print("//")!;
}
// Add username and password if they exist
if (self.username != "")
if (self.username)
{
String username = temp_encode(self.username, USERPASS);
builder.append_chars(username);
if (self.password != "")
@stack_mem(64; Allocator smem)
{
builder.append_char(':');
String password = temp_encode(self.password, USERPASS);
builder.append_chars(password);
len += f.print(encode(smem, self.username, USERPASS))!;
};
if (self.password)
{
len += f.print(":")!;
@stack_mem(64; Allocator smem)
{
len += f.print(encode(smem, self.password, USERPASS))!;
};
}
builder.append_char('@');
len += f.print("@")!;
}
// Add host
String host = temp_encode(self.host, HOST);
builder.append_chars(host);
@stack_mem(128; Allocator smem)
{
len += f.print(encode(smem, self.host, HOST))!;
};
// Add port
if (self.port != 0)
{
builder.append_char(':');
builder.appendf("%d", self.port);
}
if (self.port) len += f.printf(":%d", self.port)!;
// Add path
String path = temp_encode(self.path, PATH);
builder.append_chars(path);
@stack_mem(256; Allocator smem)
{
len += f.print(encode(smem, self.path, PATH))!;
};
// Add query if it exists (note that `query` is expected to
// be already properly encoded).
if (self.query != "")
if (self.query)
{
builder.append_char('?');
builder.append_chars(self.query);
len += f.print("?")!;
len += f.print(self.query)!;
}
// Add fragment if it exists
if (self.fragment != "")
if (self.fragment)
{
builder.append_char('#');
String fragment = temp_encode(self.fragment, FRAGMENT);
builder.append_chars(fragment);
@stack_mem(256; Allocator smem)
{
len += f.print("#")!;
len += f.print(encode(smem, self.fragment, FRAGMENT))!;
};
}
return builder.copy_str(allocator);
return len;
}
def UrlQueryValueList = List(<String>);
fn String Url.to_string(&self, Allocator allocator)
{
return string::format(allocator, "%s", *self);
}
def UrlQueryValueList = List{String};
struct UrlQueryValues
{
inline HashMap(<String, UrlQueryValueList>) map;
inline HashMap{String, UrlQueryValueList} map;
UrlQueryValueList key_order;
}
@@ -254,15 +254,7 @@ struct UrlQueryValues
@param [in] query
@return "a UrlQueryValues HashMap"
*>
fn UrlQueryValues temp_parse_query(String query) => parse_query(query, allocator::temp());
<*
Parse the query parameters of the Url into a UrlQueryValues map.
@param [in] query
@return "a UrlQueryValues HashMap"
*>
fn UrlQueryValues new_parse_query(String query) => parse_query(query, allocator::heap());
fn UrlQueryValues parse_query_to_temp(String query) => parse_query(tmem(), query);
<*
Parse the query parameters of the Url into a UrlQueryValues map.
@@ -271,7 +263,7 @@ fn UrlQueryValues new_parse_query(String query) => parse_query(query, allocator:
@param [inout] allocator
@return "a UrlQueryValues HashMap"
*>
fn UrlQueryValues parse_query(String query, Allocator allocator)
fn UrlQueryValues parse_query(Allocator allocator, String query)
{
UrlQueryValues vals;
vals.map.init(allocator);
@@ -283,8 +275,8 @@ fn UrlQueryValues parse_query(String query, Allocator allocator)
@pool(allocator)
{
String[] parts = rv.tsplit("=", 2);
String key = temp_decode(parts[0], QUERY) ?? parts[0];
vals.add(key, parts.len == 1 ? key : (temp_decode(parts[1], QUERY) ?? parts[1]));
String key = tdecode(parts[0], QUERY) ?? parts[0];
vals.add(key, parts.len == 1 ? key : (tdecode(parts[1], QUERY) ?? parts[1]));
};
}
return vals;
@@ -317,41 +309,35 @@ fn UrlQueryValues* UrlQueryValues.add(&self, String key, String value)
}
<*
Stringify UrlQueryValues into an encoded query string.
@param [in] self
@param [inout] allocator
@return "a percent-encoded query string"
*>
fn String UrlQueryValues.to_string(&self, Allocator allocator = allocator::heap()) @dynamic => @pool(allocator)
fn usz! UrlQueryValues.to_format(&self, Formatter* f) @dynamic
{
DString builder = dstring::temp_new();
usz len;
usz i;
foreach (key: self.key_order)
{
String encoded_key = temp_encode(key, QUERY);
UrlQueryValueList! values = self.map.get(key);
if (catch values) continue;
foreach (value: values)
@stack_mem(128; Allocator mem)
{
if (i > 0) builder.append_char('&');
builder.append_chars(encoded_key);
builder.append_char('=');
String encoded_value = temp_encode(value, QUERY);
builder.append_chars(encoded_value);
i++;
}
};
return builder.copy_str(allocator);
String encoded_key = encode(mem, key, QUERY);
UrlQueryValueList! values = self.map.get(key);
if (catch values) continue;
foreach (value : values)
{
if (i > 0) len += f.print("&")!;
len += f.print(encoded_key)!;
len += f.print("=")!;
@stack_mem(256; Allocator smem)
{
len += f.print(encode(smem, value, QUERY))!;
};
i++;
}
};
}
return len;
}
fn void UrlQueryValues.free(&self)
{
self.map.@each(;String key, UrlQueryValueList values)

View File

@@ -67,7 +67,7 @@ fn usz encode_len(String s, UrlEncodingMode mode) @inline
@param [inout] allocator
@return "Percent-encoded String"
*>
fn String encode(String s, UrlEncodingMode mode, Allocator allocator) => @pool(allocator)
fn String encode(Allocator allocator, String s, UrlEncodingMode mode) => @pool(allocator)
{
usz n = encode_len(s, mode);
DString builder = dstring::temp_with_capacity(n);
@@ -83,8 +83,8 @@ fn String encode(String s, UrlEncodingMode mode, Allocator allocator) => @pool(a
// add encoded char
case should_encode(c, mode):
builder.append_char('%');
String hex = hex::encode_temp(s[i:1]);
builder.append(hex.temp_ascii_to_upper());
String hex = hex::tencode(s[i:1]);
builder.append(hex.to_upper_tcopy());
// use char, no encoding needed
default:
@@ -95,15 +95,6 @@ fn String encode(String s, UrlEncodingMode mode, Allocator allocator) => @pool(a
return builder.copy_str(allocator);
}
<*
Encode the string s for a given encoding mode.
Returned string must be freed.
@param s "String to encode"
@param mode "Url encoding mode"
@return "Percent-encoded String"
*>
fn String new_encode(String s, UrlEncodingMode mode) => encode(s, mode, allocator::heap());
<*
Encode string s for a given encoding mode, stored on the temp allocator.
@@ -112,7 +103,7 @@ fn String new_encode(String s, UrlEncodingMode mode) => encode(s, mode, allocato
@param mode "Url encoding mode"
@return "Percent-encoded String"
*>
fn String temp_encode(String s, UrlEncodingMode mode) => encode(s, mode, allocator::temp());
fn String tencode(String s, UrlEncodingMode mode) => encode(tmem(), s, mode);
<*
Calculate the length of the percent-decoded string.
@@ -143,7 +134,7 @@ fn usz! decode_len(String s, UrlEncodingMode mode) @inline
@param [inout] allocator
@return "Percent-decoded String"
*>
fn String! decode(String s, UrlEncodingMode mode, Allocator allocator) => @pool(allocator)
fn String! decode(Allocator allocator, String s, UrlEncodingMode mode) => @pool(allocator)
{
usz n = decode_len(s, mode)!;
DString builder = dstring::temp_with_capacity(n);
@@ -154,7 +145,7 @@ fn String! decode(String s, UrlEncodingMode mode, Allocator allocator) => @pool
{
// decode encoded char
case '%':
char[] hex = hex::decode_temp(s[i+1:2])!;
char[] hex = hex::tdecode(s[i+1:2])!;
builder.append(hex);
i += 2;
@@ -171,15 +162,6 @@ fn String! decode(String s, UrlEncodingMode mode, Allocator allocator) => @pool
return builder.copy_str(allocator);
}
<*
Decode string s for a given encoding mode.
Returned string must be freed.
@param s "String to decode"
@param mode "Url encoding mode"
@return "Percent-decoded String"
*>
fn String! new_decode(String s, UrlEncodingMode mode) => decode(s, mode, allocator::heap());
<*
Decode string s for a given encoding mode, stored on the temp allocator.
@@ -188,4 +170,4 @@ fn String! new_decode(String s, UrlEncodingMode mode) => decode(s, mode, alloca
@param mode "Url encoding mode"
@return "Percent-decoded String"
*>
fn String! temp_decode(String s, UrlEncodingMode mode) => decode(s, mode, allocator::temp());
fn String! tdecode(String s, UrlEncodingMode mode) => decode(tmem(), s, mode);