pub trait Storable: Sized + Copy {
// Required methods
fn to_word(self) -> u64;
fn from_word(word: u64) -> Self;
}
Expand description
A trait for types that can be stored in a variable-length compressed vector.
This trait provides a bidirectional, lossless conversion between a user-facing
element type (e.g., i32
, u16
) and a u64
representation. This abstraction
is essential for IntVec
to support a variety of integer types while using
a common set of compression algorithms that operate on u64
.
§Portability and usize
/isize
By default, this trait is implemented only for fixed-size integer types
(e.g., u8
, i16
, u32
, i64
). This design choice guarantees that data
compressed on one machine architecture (e.g., 64-bit) can be safely
decompressed on another (e.g., 32-bit) without data loss or corruption.
Support for the architecture-dependent types usize
and isize
can be
enabled via the arch-dependent-storable
feature flag.
§Feature Flag: arch-dependent-storable
Activating this feature provides Storable
implementations for usize
and
isize
. However, this breaks the portability guarantee. An IntVec<usize>
created on a 64-bit system with values greater than u32::MAX
will cause a
panic if it is read on a 32-bit system.
Enable this feature only if you are certain that the data will never be shared across platforms with different pointer widths.
§Zig-Zag Encoding for Signed Integers
For signed integer types, the implementation of this trait automatically applies Zig-Zag encoding. This is a reversible transformation that maps signed integers to unsigned integers, such that values close to zero (both positive and negative) are mapped to small unsigned integers. This is highly effective for variable-length codes, which use fewer bits to represent smaller numbers.
Original Signed | Zig-Zag Unsigned |
---|---|
0 | 0 |
-1 | 1 |
1 | 2 |
-2 | 3 |
2 | 4 |
… | … |
Required Methods§
Sourcefn to_word(self) -> u64
fn to_word(self) -> u64
Converts the element into its u64
storage representation.
For unsigned types, this is a direct cast. For signed types, this applies Zig-Zag encoding.
Sourcefn from_word(word: u64) -> Self
fn from_word(word: u64) -> Self
Converts a u64
storage word back into the element type.
For unsigned types, this is a direct cast. For signed types, this reverses the Zig-Zag encoding.
§Panics
This method will panic if the word
contains a value that is out of
range for the target type. This can occur if the data is corrupted or,
in the case of usize
/isize
with the arch-dependent-storable
feature,
if the data is read on an architecture with a smaller pointer width than
the one it was written on.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.