encoding
let encoding = import("encoding")encoding covers reversible byte and text coding: Base64, hex, and URL percent-encoding. Hashing, HMAC, key derivation, and random bytes live in crypto.
Functions that take data accept a string or Bytes; hex_decode and base64_decode return Bytes.
Base64
Section titled “Base64”| Function | Returns | Description |
|---|---|---|
base64_encode(data: string | bytes) |
string |
Standard alphabet with padding |
base64_decode(s: string) |
bytes |
Decode; raises on invalid input |
base64url_encode(data: string | bytes) |
string |
URL-safe alphabet, no padding |
base64url_decode(s: string) |
bytes |
Decode unpadded URL-safe input |
let encoding = import("encoding")
let encoded = encoding.base64_encode("hello")print(encoded) # aGVsbG8=
let decoded = encoding.base64_decode(encoded)print(decoded.to_string()) # helloThe URL-safe variants are the ones to use for JWT segments and query parameters.
| Function | Returns | Description |
|---|---|---|
hex_encode(data: string | bytes) |
string |
Lowercase hex |
hex_decode(s: string) |
bytes |
Decode an even number of hex digits, case-insensitive |
print(encoding.hex_encode(Bytes([0, 15, 255]))) # 000fffprint(encoding.hex_decode("48656c6c6f").to_string()) # Hello| Function | Returns | Description |
|---|---|---|
url_encode(text: string) |
string |
Percent-encode; unreserved characters pass through |
url_decode(text: string) |
string |
Decode %XX; + becomes a space |
print(encoding.url_encode("a b&c=d")) # a%20b%26c%3Ddprint(encoding.url_decode("a%20b%26c%3Dd")) # a b&c=dRelated
Section titled “Related”- crypto for hashing, HMAC, and random bytes.
- Bytes & BytesBuilder for binary data.
- http for requests that carry encoded payloads.