Expand description
§Module :: asbytes
The asbytes crate provides a convenient trait, AsBytes, for viewing common data structures as raw byte slices (&[u8]). It focuses on types that are safe to represent as bytes (Plain Old Data, or POD), leveraging the safety guarantees of the underlying bytemuck crate.
§Why asbytes?
While bytemuck provides the core functionality for safe byte-level casting (like bytemuck::cast_slice for collections and bytemuck::bytes_of for single items), asbytes offers a unified trait-based approach for common use cases:
- Consistency: The
AsBytestrait provides a single method,.as_bytes(), that works consistently across supported types likeVec<T>, slices (&[T]), arrays ([T; N]), and single POD items wrapped in a tuple(T,). - Readability: Calling
.as_bytes()clearly signals the intent to get the raw byte representation, which is useful for tasks like serialization, hashing, or interfacing with low-level APIs (graphics, networking, etc.). - Simpler Generics: Functions can accept
T: AsBytesto work generically with the byte representation of different compatible data structures. - Convenience: The trait also provides
.byte_size()and.len()methods for easily getting the size in bytes and the number of elements, respectively.
Essentially, asbytes acts as a focused convenience layer on top of bytemuck for the specific task of viewing data as bytes via a consistent trait method.
§How asbytes Differs from bytemuck
While bytemuck offers safe transmutation via its Pod trait and functions like cast_slice, it does not expose a dedicated trait for converting data structures into byte slices. asbytes introduces the AsBytes trait, abstracting these conversions and providing additional conveniences—such as direct byte size computation—on top of bytemuck’s proven foundation.
§Example
// Make sure bytemuck is available for derives
extern crate bytemuck;
use asbytes::AsBytes; // Import the trait
// Define a POD struct
#[ repr( C ) ]
#[ derive( Clone, Copy, bytemuck::Pod, bytemuck::Zeroable ) ]
struct Point
{
x : f32,
y : f32,
}
fn main()
{
// --- Collections ---
let points_vec : Vec< Point > = vec![ Point { x : 1.0, y : 2.0 }, Point { x : 3.0, y : 4.0 } ];
let points_slice : &[ Point ] = &points_vec[ .. ];
let points_array : [ Point; 1 ] = [ Point { x : 5.0, y : 6.0 } ];
let vec_bytes = points_vec.as_bytes();
let slice_bytes = points_slice.as_bytes();
let array_bytes = points_array.as_bytes();
println!( "Vec Bytes: length={}, data={:?}", points_vec.byte_size(), vec_bytes );
println!( "Slice Bytes: length={}, data={:?}", slice_bytes.byte_size(), slice_bytes );
println!( "Array Bytes: length={}, data={:?}", points_array.byte_size(), array_bytes );
println!( "Vec Element Count: {}", points_vec.len() ); // Output: 2
println!( "Array Element Count: {}", points_array.len() ); // Output: 1
// --- Single POD Item (using tuple trick) ---
let single_point = Point { x : -1.0, y : -2.0 };
let single_point_tuple = ( single_point, ); // Wrap in a single-element tuple
let point_bytes = single_point_tuple.as_bytes();
println!( "Single Point Bytes: length={}, data={:?}", single_point_tuple.byte_size(), point_bytes );
println!( "Single Point Element Count: {}", single_point_tuple.len() ); // Output: 1
let scalar_tuple = ( 12345u32, );
let scalar_bytes = scalar_tuple.as_bytes();
println!( "Scalar Bytes: length={}, data={:?}", scalar_tuple.byte_size(), scalar_bytes );
}§To add to your project
cargo add asbytes§Try out from the repository
git clone https://github.com/Wandalen/wTools
cd wTools
cd examples/asbytes
cargo runModules§
- checked
- Checked versions of the casting functions exposed in crate root
that support
CheckedBitPatterntypes. - dependency
- Namespace with dependencies.
- exposed
- Exposed namespace of the module.
- orphan
- Orphan namespace of the module.
- own
- Own namespace of the module.
- prelude
- Prelude to use essentials:
use my_module::prelude::*.
Macros§
- offset_
of - Find the offset in bytes of the given
$fieldof$Type. Requires an already initialized$instancevalue to work with.
Enums§
- PodCast
Error - The things that can go wrong when casting between
Poddata forms.
Traits§
- AnyBit
Pattern - Marker trait for “plain old data” types that are valid for any bit pattern.
- AsBytes
- Trait for converting data to byte slices. This trait abstracts the conversion of types that implement Pod into their raw byte representation.
- Checked
BitPattern - A marker trait that allows types that have some invalid bit patterns to be
used in places that otherwise require
AnyBitPatternorPodtypes by performing a runtime check on a perticular set of bits. This is particularly useful for types like fieldless (‘C-style’) enums,char, bool, and structs containing them. - Contiguous
- A trait indicating that:
- NoUninit
- Marker trait for “plain old data” types with no uninit (or padding) bytes.
- Pod
- Marker trait for “plain old data”.
- PodIn
Option - Trait for types which are Pod when wrapped in Option.
- Transparent
Wrapper - A trait which indicates that a type is a
#[repr(transparent)]wrapper around theInnervalue. - Zeroable
- Trait for types that can be safely created with
zeroed. - Zeroable
InOption - Trait for types which are Zeroable when wrapped in Option.
Functions§
- bytes_
of - Re-interprets
&Tas&[u8]. - bytes_
of_ mut - Re-interprets
&mut Tas&mut [u8]. - cast
- Cast
AintoB - cast_
mut - Cast
&mut Ainto&mut B. - cast_
ref - Cast
&Ainto&B. - cast_
slice - Cast
&[A]into&[B]. - cast_
slice_ mut - Cast
&mut [A]into&mut [B]. - fill_
zeroes - Fill all bytes of
slicewith zeroes (seeZeroable). - from_
bytes - Re-interprets
&[u8]as&T. - from_
bytes_ mut - Re-interprets
&mut [u8]as&mut T. - pod_
align_ to - As
align_to, but safe because of thePodbound. - pod_
align_ to_ mut - As
align_to_mut, but safe because of thePodbound. - pod_
read_ unaligned - Reads the slice into a
Tvalue. - try_
cast - Try to cast
AintoB. - try_
cast_ mut - Try to convert a
&mut Ainto&mut B. - try_
cast_ ref - Try to convert a
&Ainto&B. - try_
cast_ slice - Try to convert
&[A]into&[B](possibly with a change in length). - try_
cast_ slice_ mut - Try to convert
&mut [A]into&mut [B](possibly with a change in length). - try_
from_ bytes - Re-interprets
&[u8]as&T. - try_
from_ bytes_ mut - Re-interprets
&mut [u8]as&mut T. - try_
pod_ read_ unaligned - Reads from the bytes as if they were a
T. - write_
zeroes - Fill all bytes of
targetwith zeroes (seeZeroable).
Derive Macros§
- AnyBit
Pattern - Derive the
AnyBitPatterntrait for a struct - Checked
BitPattern - Derive the
CheckedBitPatterntrait for a struct or enum. - Contiguous
- Derive the
Contiguoustrait for an enum - NoUninit
- Derive the
NoUninittrait for a struct or enum - Pod
- Derive the
Podtrait for a struct - Transparent
Wrapper - Derive the
TransparentWrappertrait for a struct - Zeroable
- Derive the
Zeroabletrait for a struct