Encoding package extracted from moonbitlang/x
test {
// 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())
}test {
// Encode a string to UTF-8
let src = "你好👀"
let bytes = @encoding.encode(src, encoding=UTF8)
inspect(
bytes,
content="b\"\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd\\xf0\\x9f\\x91\\x80\"",
)
}pub suberror DecodingError {
Malformed(Bytes)
Truncated(Bytes)
}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_lossy_to(self : Decoder, input : BytesView, output : StringBuilder, stream? : Bool) -> Unitfn Decoder::decode_to(self : Decoder, input : BytesView, output : StringBuilder, stream? : Bool) -> Unit raise DecodingErrorlet decoder = decoder(UTF8)
let buf = StringBuilder::new()
decoder.decode_to(b"Hello", buf)
inspect(buf.to_string(), content="Hello")let U_REP : Charlet inputs = [b"abc", b"\xf0", b"\x9f\x90\xb0"] // UTF8(🐰) == <F09F 90B0>
let decoder = decoder(UTF8)
inspect(decoder.consume(inputs[0]), content="abc")
inspect(decoder.consume(inputs[1]), content="")
inspect(decoder.consume(inputs[2]), content="🐰")
assert_true(decoder.finish().is_empty())let src = "Hello, World!"
@json.inspect(encode(encoding=UTF8, src).to_array(), content=
[72,101,108,108,111,44,32,87,111,114,108,100,33]
)let buf = @buffer.new()
let text = "Hello, world"
@encoding.encode_to(text, buf, encoding=UTF16LE)
inspect(buf.to_string(), content="Hello, world")Encoding package extracted from moonbitlang/x