Encoding package extracted from moonbitlang/x
// Initialize a streaming UTF-8 decoder
let decoder = @encoding.decoder(UTF8)
// Consume byte chunks
let inputs = [b"abc", b"\xf0", b"\x9f\x90\xb0"] // UTF8(🐰) == <F09F 90B0>
inspect!(decoder.consume!(inputs[0]), content="abc")
inspect!(decoder.consume!(inputs[1]), content="")
inspect!(decoder.consume!(inputs[2]), content="🐰")
// Finish decoding
assert_true!(decoder.finish!().is_empty())// Encode a string to UTF-8
let src = "你好👀"
let bytes = @encoding.encode(UTF8, src)
inspect!(
bytes,
content=
#|b"\xe4\xbd\xa0\xe5\xa5\xbd\xf0\x9f\x91\x80"
,
)inspect!(
@encoding.to_utf8_bytes('A'),
content=
#|b"\x41"
,
)type Decoderlet inputs = [b"abc", b"\xf0", b"\x9f\x90\xb0"] // UTF8(🐰) == <F09F 90B0>
let decoder = @encoding.decoder(UTF8)
inspect!(decoder.decode!(inputs[0], stream=true), content="abc")
inspect!(decoder.decode!(inputs[1], stream=true), content="")
inspect!(decoder.decode!(inputs[2], stream=false), content="🐰")fn Decoder::decode_to(self : Decoder, input : Bytes, output : StringBuilder, stream~ : Bool = ..) -> Unit!DecodingErrortest "decode_to" {
let decoder = decoder(UTF8)
let buf = StringBuilder::new()
decoder.decode_to!(b"Hello", buf)
inspect!(buf.to_string(), content="Hello")
}pub enum DecodingError {
Malformed(Bytes)
Truncated(Bytes)
}impl Show for DecodingErrorlet U_REP : Charlet src = "Hello, World!"
let encoded_bytes = encode(UTF8, src)test "encode_to" {
let buf = @buffer.new()
let text = "Hello, world"
@encoding.encode_to(text, buf, encoding=UTF16)
inspect!(buf.to_string(), content="Hello, world")
}