packed/packed_item.rs
1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Defines the `PackedItem` trait for types that can be tightly packed in memory.
6
7/// A trait for types that can be packed into a single contiguous buffer of bytes.
8pub trait PackedItem: zerocopy::IntoBytes + zerocopy::Immutable + zerocopy::Unaligned {
9 /// Reconstructs the item from a byte slice.
10 ///
11 /// # Safety
12 ///
13 /// The caller must guarantee that the slice contains data that is byte-identical
14 /// to a slice returned by `IntoBytes::as_bytes` for a valid instance of this type.
15 unsafe fn from_bytes(bytes: &[u8]) -> &Self;
16}
17
18impl PackedItem for [u8] {
19 unsafe fn from_bytes(bytes: &[u8]) -> &Self {
20 bytes
21 }
22}
23
24impl PackedItem for str {
25 unsafe fn from_bytes(bytes: &[u8]) -> &Self {
26 // SAFETY: The documented safety constraint for `from_bytes` requires
27 // the caller to guarantee these bytes are identical to the output from
28 // `<str as zerocopy::IntoBytes>::as_bytes`, which contains valid UTF-8.
29 unsafe { std::str::from_utf8_unchecked(bytes) }
30 }
31}