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