slice-codec is a lightweight library for encoding and decoding values using the Slice encoding.
The codec is built around two pairs of types:
Encoderwrites values into anOutputTarget, driven by theEncodeIntotrait.Decoderreads values out of anInputSource, driven by theDecodeFromtrait.
Implementations of EncodeInto / DecodeFrom are provided for common primitives and collections,
but you can implement these traits on your own types to make them usable with Slice.
use slice_codec::encoder::Encoder;
use slice_codec::decoder::Decoder;
fn main() -> slice_codec::Result<()> {
let mut buffer: Vec<u8> = Vec::new();
// Encode some values into a byte buffer.
let mut encoder = Encoder::from(&mut buffer);
encoder.encode("hello")?;
encoder.encode::<i32>(42)?;
// Decode them back out.
let mut decoder = Decoder::from(&buffer);
let greeting: String = decoder.decode()?;
let the_answer = decoder.decode::<i32>()?;
assert_eq!(greeting, "hello");
assert_eq!(the_answer, 42);
Ok(())
}Add slice-codec as a dependency to your project's Cargo.toml file:
[dependencies]
slice-codec = "0.4"The codec is no_std compatible, so it can be used in embedded or other constrained environments.
To use the codec in a no_std project, just disable default features:
[dependencies]
slice-codec = { version = "0.4", default-features = false }If you have a global allocator and need to decode owned types like String or Vec, also enable the alloc feature.
| Feature | Default | Description |
|---|---|---|
std |
✅ | Enables implementations to encode/decode standard-library types such as String, Vec, and HashMap. Implies alloc. |
alloc |
✅ | Enables implementations to decode dynamically-allocated types like String and Vec. Intended for no_std + global allocator. |
This crate is part of the slicec workspace.
Commands should be run from the repository root:
# Build with the default features.
cargo build -p slice-codec
# Run the tests with all features enabled.
cargo test -p slice-codec --all-features'slicec-codec' is licensed under the Apache License, Version 2.0.