From ae44478b30d890fe0fb04022f44d474dcdcc3f9d Mon Sep 17 00:00:00 2001 From: Lassi Pulkkinen Date: Thu, 31 Oct 2024 03:11:21 +0200 Subject: Initial commit (import old repo) --- mcproto/encode.ha | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 mcproto/encode.ha (limited to 'mcproto/encode.ha') diff --git a/mcproto/encode.ha b/mcproto/encode.ha new file mode 100644 index 0000000..de30871 --- /dev/null +++ b/mcproto/encode.ha @@ -0,0 +1,51 @@ +use endian; +use strings; +use uuid; + +export fn encode_short(out: *[]u8, v: u16) void = { + const buf: [2]u8 = [0...]; + endian::beputu16(buf, v); + append(out, buf...); +}; +export fn encode_int(out: *[]u8, v: u32) void = { + const buf: [4]u8 = [0...]; + endian::beputu32(buf, v); + append(out, buf...); +}; +export fn encode_long(out: *[]u8, v: u64) void = { + const buf: [8]u8 = [0...]; + endian::beputu64(buf, v); + append(out, buf...); +}; + +export fn encode_bool(out: *[]u8, v: bool) void = { + append(out, if (v) 1 else 0); +}; + +export fn encode_float(out: *[]u8, v: f32) void = { + encode_int(out, *(&v: *u32)); +}; +export fn encode_double(out: *[]u8, v: f64) void = { + encode_long(out, *(&v: *u64)); +}; + +export fn encode_varint(out: *[]u8, v: i32) void = { + let v = v: u32; + + for (true) { + const continues = v & 0x7f != v; + const high_bit: u8 = if (continues) 0x80 else 0x00; + append(out, (v & 0x7f): u8 | high_bit); + v >>= 7; + if (!continues) return; + }; +}; + +export fn encode_string(out: *[]u8, string: str) void = { + encode_varint(out, len(string): i32); + append(out, strings::toutf8(string)...); +}; + +export fn encode_uuid(out: *[]u8, uuid: uuid::uuid) void = { + append(out, uuid...); +}; -- cgit v1.2.3