Files
nandi 274bb319ab
check / check (macos-latest) (push) Failing after 2m16s
check / check (ubuntu-latest) (push) Failing after 2m14s
check / check (windows-latest) (push) Failing after 14m21s
refactor: switch StringBuilder capacity to size_hint
- Replace the StringBuilder(capacity=...) argument with size_hint=... in base32, base64, hex, SAM quoting/parsing.
- Drop trailing commas after the last field in I2NP, NTCP2 and tunnel fragment enum variants (formatter cleanup).
- No behavior change; encoded output and parsed fields are unchanged.
2026-11-27 16:57:28 -08:00

326 lines
8.4 KiB
MoonBit

///|
/// Errors raised during I2P binary, Base64, Base32, or Hex encoding/decoding.
#derive(Eq, Debug)
pub suberror EncodingError {
UnexpectedEof(String)
InvalidCharacter(String)
InvalidLength(String)
ValueOutOfRange(String)
}
///|
/// Big-endian binary reader over an immutable `Bytes` buffer.
pub struct Reader {
data : Bytes
mut pos : Int32
}
///|
pub fn Reader::new(data : Bytes) -> Reader {
{ data, pos: 0, }
}
///|
pub fn Reader::position(self : Reader) -> Int32 {
self.pos
}
///|
pub fn Reader::remaining(self : Reader) -> Int32 {
self.data.length() - self.pos
}
///|
pub fn Reader::is_eof(self : Reader) -> Bool {
self.pos >= self.data.length()
}
///|
pub fn Reader::skip(self : Reader, n : Int32) -> Unit raise EncodingError {
if n < 0 || self.remaining() < n {
raise UnexpectedEof("skip: need \{n} bytes, have \{self.remaining()}")
}
self.pos += n
}
///|
pub fn Reader::read_u8(self : Reader) -> Byte raise EncodingError {
if self.remaining() < 1 {
raise UnexpectedEof("read_u8: unexpected EOF at \{self.pos}")
}
let b = self.data[self.pos]
self.pos += 1
b
}
///|
pub fn Reader::read_u16_be(self : Reader) -> UInt32 raise EncodingError {
if self.remaining() < 2 {
raise UnexpectedEof("read_u16_be: unexpected EOF at \{self.pos}")
}
let b0 = self.data[self.pos].to_uint()
let b1 = self.data[self.pos + 1].to_uint()
self.pos += 2
(b0 << 8) | b1
}
///|
pub fn Reader::read_u32_be(self : Reader) -> UInt32 raise EncodingError {
if self.remaining() < 4 {
raise UnexpectedEof("read_u32_be: unexpected EOF at \{self.pos}")
}
let b0 = self.data[self.pos].to_uint()
let b1 = self.data[self.pos + 1].to_uint()
let b2 = self.data[self.pos + 2].to_uint()
let b3 = self.data[self.pos + 3].to_uint()
self.pos += 4
(b0 << 24) | (b1 << 16) | (b2 << 8) | b3
}
///|
pub fn Reader::read_u64_be(self : Reader) -> UInt64 raise EncodingError {
if self.remaining() < 8 {
raise UnexpectedEof("read_u64_be: unexpected EOF at \{self.pos}")
}
let mut acc : UInt64 = 0UL
for i = 0; i < 8; i = i + 1 {
acc = (acc << 8) | self.data[self.pos + i].to_uint64()
}
self.pos += 8
acc
}
///|
pub fn Reader::read_bytes(
self : Reader,
len : Int32,
) -> Bytes raise EncodingError {
if len < 0 || self.remaining() < len {
raise UnexpectedEof(
"read_bytes: need \{len} bytes, have \{self.remaining()}",
)
}
let out = FixedArray::make(len, b'\x00')
for i = 0; i < len; i = i + 1 {
out[i] = self.data[self.pos + i]
}
self.pos += len
Bytes::from_array(out)
}
///|
pub fn Reader::read_remaining(self : Reader) -> Bytes {
let len = self.remaining()
let out = FixedArray::make(len, b'\x00')
for i = 0; i < len; i = i + 1 {
out[i] = self.data[self.pos + i]
}
self.pos = self.data.length()
Bytes::from_array(out)
}
///|
/// Reads an I2P String: 1-byte unsigned length prefix (0..255) followed by UTF-8 bytes.
pub fn Reader::read_i2p_string(self : Reader) -> String raise EncodingError {
let len = self.read_u8().to_int()
let raw = self.read_bytes(len)
utf8_bytes_to_string(raw)
}
///|
/// Big-endian binary writer backed by a growable byte buffer.
pub struct Writer {
buf : Array[Byte]
}
///|
pub fn Writer::new(capacity~ : Int32 = 64) -> Writer {
{ buf: Array(capacity~), }
}
///|
pub fn Writer::length(self : Writer) -> Int32 {
self.buf.length()
}
///|
pub fn Writer::write_u8(self : Writer, v : Byte) -> Unit {
self.buf.push(v)
}
///|
pub fn Writer::write_u16_be(self : Writer, v : UInt32) -> Unit {
self.buf.push(((v >> 8) & 0xFFU).to_byte())
self.buf.push((v & 0xFFU).to_byte())
}
///|
pub fn Writer::write_u32_be(self : Writer, v : UInt32) -> Unit {
self.buf.push(((v >> 24) & 0xFFU).to_byte())
self.buf.push(((v >> 16) & 0xFFU).to_byte())
self.buf.push(((v >> 8) & 0xFFU).to_byte())
self.buf.push((v & 0xFFU).to_byte())
}
///|
pub fn Writer::write_u64_be(self : Writer, v : UInt64) -> Unit {
self.buf.push(((v >> 56) & 0xFFUL).to_byte())
self.buf.push(((v >> 48) & 0xFFUL).to_byte())
self.buf.push(((v >> 40) & 0xFFUL).to_byte())
self.buf.push(((v >> 32) & 0xFFUL).to_byte())
self.buf.push(((v >> 24) & 0xFFUL).to_byte())
self.buf.push(((v >> 16) & 0xFFUL).to_byte())
self.buf.push(((v >> 8) & 0xFFUL).to_byte())
self.buf.push((v & 0xFFUL).to_byte())
}
///|
pub fn Writer::write_bytes(self : Writer, data : Bytes) -> Unit {
for i = 0; i < data.length(); i = i + 1 {
self.buf.push(data[i])
}
}
///|
/// Writes an I2P String (1-byte length + UTF-8 bytes, max 255 bytes).
pub fn Writer::write_i2p_string(
self : Writer,
s : String,
) -> Unit raise EncodingError {
let raw = string_to_utf8_bytes(s)
if raw.length() > 255 {
raise ValueOutOfRange("I2P string exceeds 255 UTF-8 bytes: \{raw.length()}")
}
self.write_u8(raw.length().to_byte())
self.write_bytes(raw)
}
///|
pub fn Writer::to_bytes(self : Writer) -> Bytes {
Bytes::from_array(self.buf)
}
///|
/// Encodes a MoonBit `String` to UTF-8 `Bytes`.
pub fn string_to_utf8_bytes(s : String) -> Bytes {
let out : Array[Byte] = []
for ch in s {
let cp = ch.to_int()
if cp < 0x80 {
out.push(cp.to_byte())
} else if cp < 0x800 {
out.push((0xC0 | (cp >> 6)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
} else if cp < 0x10000 {
out.push((0xE0 | (cp >> 12)).to_byte())
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
} else {
out.push((0xF0 | (cp >> 18)).to_byte())
out.push((0x80 | ((cp >> 12) & 0x3F)).to_byte())
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
}
}
Bytes::from_array(out)
}
///|
/// Decodes UTF-8 `Bytes` to a MoonBit `String`.
pub fn utf8_bytes_to_string(data : Bytes) -> String raise EncodingError {
let buf = StringBuilder()
let len = data.length()
let mut i = 0
while i < len {
let b0 = data[i].to_int()
if b0 < 0x80 {
buf.write_char(b0.unsafe_to_char())
i += 1
} else if (b0 & 0xE0) == 0xC0 {
if i + 1 >= len {
raise InvalidCharacter("truncated 2-byte UTF-8 sequence")
}
let b1 = data[i + 1].to_int()
let cp = ((b0 & 0x1F) << 6) | (b1 & 0x3F)
buf.write_char(cp.unsafe_to_char())
i += 2
} else if (b0 & 0xF0) == 0xE0 {
if i + 2 >= len {
raise InvalidCharacter("truncated 3-byte UTF-8 sequence")
}
let b1 = data[i + 1].to_int()
let b2 = data[i + 2].to_int()
let cp = ((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)
buf.write_char(cp.unsafe_to_char())
i += 3
} else if (b0 & 0xF8) == 0xF0 {
if i + 3 >= len {
raise InvalidCharacter("truncated 4-byte UTF-8 sequence")
}
let b1 = data[i + 1].to_int()
let b2 = data[i + 2].to_int()
let b3 = data[i + 3].to_int()
let cp = ((b0 & 0x07) << 18) |
((b1 & 0x3F) << 12) |
((b2 & 0x3F) << 6) |
(b3 & 0x3F)
buf.write_char(cp.unsafe_to_char())
i += 4
} else {
raise InvalidCharacter("invalid UTF-8 lead byte: \{b0}")
}
}
buf.to_string()
}
///|
let hex_digits : Bytes = b"0123456789abcdef"
///|
/// Encodes `Bytes` as lowercase hexadecimal.
pub fn hex_encode(data : Bytes) -> String {
let buf = StringBuilder(size_hint=data.length() * 2)
for i = 0; i < data.length(); i = i + 1 {
let b = data[i].to_int()
buf.write_char(hex_digits[b >> 4].to_int().unsafe_to_char())
buf.write_char(hex_digits[b & 0x0F].to_int().unsafe_to_char())
}
buf.to_string()
}
///|
fn hex_nibble(c : Int32) -> Int32 raise EncodingError {
if c >= 48 && c <= 57 {
c - 48
} else if c >= 97 && c <= 102 {
c - 87
} else if c >= 65 && c <= 70 {
c - 55
} else {
raise InvalidCharacter("invalid hex character code: \{c}")
}
}
///|
/// Decodes a hexadecimal string (case-insensitive, ignoring ASCII whitespace) into `Bytes`.
pub fn hex_decode(s : String) -> Bytes raise EncodingError {
let chars : Array[Int32] = []
for ch in s {
let c = ch.to_int()
if c == 32 || c == 9 || c == 10 || c == 13 {
continue
}
chars.push(c)
}
if chars.length() % 2 != 0 {
raise InvalidLength("hex string has odd length: \{chars.length()}")
}
let out = FixedArray::make(chars.length() / 2, b'\x00')
for i = 0; i < out.length(); i = i + 1 {
let hi = hex_nibble(chars[i * 2])
let lo = hex_nibble(chars[i * 2 + 1])
out[i] = ((hi << 4) | lo).to_byte()
}
Bytes::from_array(out)
}