A fast and compliant Bencode encoder and decoder for MoonBit.
moon add 2515050243qyf/moon_bencodeimport {
"2515050243qyf/moon_bencode" = "0.1.2"
}{
"deps": {
"2515050243qyf/moon_bencode/src/bencode": ""
}
}///|
pub fn main raise {
// Decode a Bencode string
let val = @bencode.decode(b"d3:bar4:spam3:fooi42ee")
println("Decoded: \{val}")
// Output: BDict([(b"bar", BStr(b"spam")), (b"foo", BInt(42))])
// Encode it back to Bytes
let bytes = @bencode.encode(val)
println("Encoded: \{bytes}")
// Output: b"d3:bar4:spam3:fooi42ee"
}///|
pub fn example_json(val : @bencode.BValue) raise {
// Convert to Json
let json_obj = val.to_json()
println(json_obj.stringify())
// Parse back to BValue
let b_val = @bencode.BValue::from_json(json_obj)
}///|
pub fn example_path(torrent : @bencode.BValue) {
// Retrieve the nested 'name' field inside 'info'
match torrent.get_path(["info", "name"]) {
Some(BStr(name)) => println("Name: \{name}")
_ => println("Not found")
}
}///|
pub fn example_hash(torrent : @bencode.BValue) {
match torrent.info_hash() {
Some(hash_bytes) => println("Info Hash: \{hash_bytes}")
None => println("Invalid torrent")
}
}A fast and compliant Bencode encoder and decoder for MoonBit.