Skip to main content

ostd_pod/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2
3#![doc = include_str!("../README.md")]
4#![no_std]
5#![deny(unsafe_code)]
6
7pub use array_factory::{ArrayFactory, ArrayManufacture, U8Array, U16Array, U32Array, U64Array};
8pub use zerocopy::{FromBytes, FromZeros, Immutable, IntoBytes, KnownLayout};
9
10mod array_factory;
11
12/// A trait for plain old data (POD).
13///
14/// A POD type `T: Pod` can be safely converted to and from an arbitrary byte
15/// sequence of length [`size_of::<T>()`].
16/// For example, primitive types such as `u8` and `i16` are POD types.
17///
18/// See the crate-level documentation for design notes and usage guidance.
19///
20/// [`size_of::<T>()`]: size_of
21pub trait Pod: FromBytes + IntoBytes + KnownLayout + Immutable + Copy {
22    /// Creates a new instance from the given bytes.
23    ///
24    /// # Panics
25    ///
26    /// Panics if `bytes.len() != size_of::<Self>()`.
27    #[track_caller]
28    fn from_bytes(bytes: &[u8]) -> Self {
29        <Self as FromBytes>::read_from_bytes(bytes).unwrap()
30    }
31
32    /// Creates a new instance by copying the first `size_of::<Self>()` bytes from `bytes`.
33    ///
34    /// This is useful when `bytes` contains a larger buffer (e.g., a header followed by
35    /// payload) and you only want to interpret the prefix as `Self`.
36    ///
37    /// # Panics
38    ///
39    /// Panics if `bytes.len() < size_of::<Self>()`.
40    #[track_caller]
41    fn from_first_bytes(bytes: &[u8]) -> Self {
42        <Self as FromBytes>::read_from_prefix(bytes).unwrap().0
43    }
44}
45
46impl<T: FromBytes + IntoBytes + KnownLayout + Immutable + Copy> Pod for T {}
47
48#[cfg(feature = "macros")]
49pub use ostd_pod_macros::{derive, pod_union};
50#[cfg(feature = "macros")]
51pub use padding_struct::padding_struct;