pub trait ZeroCopySerializable:
Sized
+ Clone
+ Copy
+ 'static
+ Send
+ Sync {
// Required methods
unsafe fn from_bytes(bytes: &[u8]) -> CoreResult<Self>;
unsafe fn as_bytes(&self) -> &[u8] ⓘ;
// Provided methods
fn validate_bytes(bytes: &[u8]) -> bool { ... }
fn byte_size() -> usize { ... }
fn type_identifier() -> &'static str { ... }
}Expand description
Trait for zero-copy serializable types.
This trait enables types to be directly mapped between memory and disk without intermediate copies. It’s primarily designed for numeric types and other types with stable memory representations.
Implementations of this trait provide:
- Direct memory layout access through raw byte slices
- Safe conversion between bytes and typed values
- Validation of serialized data for type safety
- Size information for memory allocation and validation
This trait is optimized for performance-critical code where avoiding memory copies is essential, especially with large datasets.
§Safety Considerations
Zero-copy serialization relies on the binary representation of types, which depends on:
- Memory layout (which can differ across platforms)
- Endianness (byte order)
- Alignment requirements
For custom types, ensure:
- The type has a well-defined memory layout (e.g., #[repr(C)] or #[repr(transparent)])
- The type doesn’t contain references, pointers, or other indirection
- All fields are themselves zero-copy serializable
- The type doesn’t have any padding bytes with undefined values
Required Methods§
Sourceunsafe fn from_bytes(bytes: &[u8]) -> CoreResult<Self>
unsafe fn from_bytes(bytes: &[u8]) -> CoreResult<Self>
Convert a byte slice to an instance of this type.
§Safety
This function is unsafe because it reads raw bytes and interprets them as a value
of type Self. The caller must ensure that the byte slice is valid for the type.
Provided Methods§
Sourcefn validate_bytes(bytes: &[u8]) -> bool
fn validate_bytes(bytes: &[u8]) -> bool
Check if the byte slice is valid for this type.
Sourcefn type_identifier() -> &'static str
fn type_identifier() -> &'static str
Get a type identifier for validation during deserialization.
This method provides a way to identify the type during deserialization. By default, it returns the type name, but custom implementations may override this for more specific type checking.
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.