Crates.io | solana-compact-u16 |
lib.rs | solana-compact-u16 |
version | 0.1.0 |
source | src |
created_at | 2024-09-01 10:11:20.251442 |
updated_at | 2024-09-01 10:11:20.251442 |
description | Simple compact u16 implementation with Borsh |
homepage | |
repository | |
max_upload_size | |
id | 1359463 |
size | 9,805 |
CompactU16
is a compact, variable-length encoding for 16-bit unsigned integers (u16
). It is designed to save space when serializing small integers by using fewer bytes for smaller values. The implementation is inspired by the variable-length quantity (VLQ) encoding used in formats like Protocol Buffers.
u16
integers using 1 to 3 bytes, depending on the size of the value.use-borsh
feature is enabled, CompactU16
implements the BorshSerialize
and BorshDeserialize
traits, allowing it to be used with the Borsh serialization format.u16
.CompactU16
from Bytesuse compact_u16::CompactU16;
let mut input = &[0x80, 0x01][..];
let value = CompactU16::deserialize(&mut input).unwrap();
assert_eq!(value.0, 0x0080);
CompactU16
to Bytesuse compact_u16::CompactU16;
use borsh::BorshSerialize;
let value = CompactU16(0x3fff);
let mut output = Vec::new();
value.serialize(&mut output).unwrap();
assert_eq!(output, vec![0xff, 0x7f]);
0x0000
to 0x007F
are encoded in a single byte.0x0080
to 0x3FFF
are encoded in two bytes.0x4000
to 0xFFFF
are encoded in three bytes.The CompactU16
struct supports Borsh serialization and deserialization when the use-borsh
feature is enabled. This allows easy integration with systems that use the Borsh format.
Unit tests are included to verify the correctness of the encoding and decoding. These tests cover a range of values and ensure that the encoding and decoding process is accurate.
cargo test
This project is licensed under the MIT License. See the LICENSE file for details.