// SPDX-License-Identifier: (BSD-2-Clause OR Apache-2.0) OR MIT
//
// Copyright 2025 The Fuchsia Authors
//
// Licensed under the 2-Clause BSD License <LICENSE-BSD or
// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
use super::*;
use crate::pointer::invariant::{Aligned, Exclusive, Invariants, Shared, Valid};
/// Types that can be split in two.
///
/// This trait generalizes Rust's existing support for splitting slices to
/// support slices and slice-based dynamically-sized types ("slice DSTs").
///
/// # Implementation
///
/// **Do not implement this trait yourself!** Instead, use
/// [`#[derive(SplitAt)]`][derive]; e.g.:
///
/// ```
/// # use zerocopy_derive::{SplitAt, KnownLayout};
/// #[derive(SplitAt, KnownLayout)]
/// #[repr(C)]
/// struct MyStruct<T: ?Sized> {
/// # /*
/// ...,
/// # */
/// // `SplitAt` types must have at least one field.
/// field: T,
/// }
/// ```
///
/// This derive performs a sophisticated, compile-time safety analysis to
/// determine whether a type is `SplitAt`.
///
/// # Safety
///
/// This trait does not convey any safety guarantees to code outside this crate.
///
/// You must not rely on the `#[doc(hidden)]` internals of `SplitAt`. Future
/// releases of zerocopy may make backwards-breaking changes to these items,
/// including changes that only affect soundness, which may cause code which
/// uses those items to silently become unsound.
///
#[cfg_attr(feature = "derive", doc = "[derive]: zerocopy_derive::SplitAt")]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.SplitAt.html"),
)]
#[cfg_attr(
not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
diagnostic::on_unimplemented(note = "Consider adding `#[derive(SplitAt)]` to `{Self}`")
)]
// # Safety
//
// The trailing slice is well-aligned for its element type. `Self` is `[T]`, or
// a `repr(C)` or `repr(transparent)` slice DST.
pub unsafe trait SplitAt: KnownLayout<PointerMetadata = usize> {
/// The element type of the trailing slice.
type Elem;
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
/// Unsafely splits `self` in two.
///
/// # Safety
///
/// The caller promises that `l_len` is not greater than the length of
/// `self`'s trailing slice.
///
#[doc = codegen_section!(
header = "h5",
bench = "split_at_unchecked",
format = "coco",
arity = 2,
[
open
@index 1
@title "Unsized"
@variant "dynamic_size"
],
[
@index 2
@title "Dynamically Padded"
@variant "dynamic_padding"
]
)]
#[inline]
#[must_use]
unsafe fn split_at_unchecked(&self, l_len: usize) -> Split<&Self> {
// SAFETY: By precondition on the caller, `l_len <= self.len()`.
unsafe { Split::<&Self>::new(self, l_len) }
}
/// Attempts to split `self` in two.
///
/// Returns `None` if `l_len` is greater than the length of `self`'s
/// trailing slice.
///
/// # Examples
///
/// ```
/// use zerocopy::{SplitAt, FromBytes};
/// # use zerocopy_derive::*;
///
/// #[derive(SplitAt, FromBytes, KnownLayout, Immutable)]
/// #[repr(C)]
/// struct Packet {
/// length: u8,
/// body: [u8],
/// }
///
/// // These bytes encode a `Packet`.
/// let bytes = &[4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
///
/// let packet = Packet::ref_from_bytes(bytes).unwrap();
///
/// assert_eq!(packet.length, 4);
/// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
///
/// // Attempt to split `packet` at `length`.
/// let split = packet.split_at(packet.length as usize).unwrap();
///
/// // Use the `Immutable` bound on `Packet` to prove that it's okay to
/// // return concurrent references to `packet` and `rest`.
/// let (packet, rest) = split.via_immutable();
///
/// assert_eq!(packet.length, 4);
/// assert_eq!(packet.body, [1, 2, 3, 4]);
/// assert_eq!(rest, [5, 6, 7, 8, 9]);
/// ```
///
#[doc = codegen_section!(
header = "h5",
bench = "split_at",
format = "coco",
arity = 2,
[
open
@index 1
@title "Unsized"
@variant "dynamic_size"
],
[
@index 2
@title "Dynamically Padded"
@variant "dynamic_padding"
]
)]
#[inline]
#[must_use = "has no side effects"]
fn split_at(&self, l_len: usize) -> Option<Split<&Self>> {
MetadataOf::new_in_bounds(self, l_len).map(
#[inline(always)]
|l_len| {
// SAFETY: We have ensured that `l_len <= self.len()` (by
// post-condition on `MetadataOf::new_in_bounds`)
unsafe { Split::new(self, l_len.get()) }
},
)
}
/// Unsafely splits `self` in two.
///
/// # Safety
///
/// The caller promises that `l_len` is not greater than the length of
/// `self`'s trailing slice.
///
#[doc = codegen_header!("h5", "split_at_mut_unchecked")]
///
/// See [`SplitAt::split_at_unchecked`](#method.split_at_unchecked.codegen).
#[inline]
#[must_use]
unsafe fn split_at_mut_unchecked(&mut self, l_len: usize) -> Split<&mut Self> {
// SAFETY: By precondition on the caller, `l_len <= self.len()`.
unsafe { Split::<&mut Self>::new(self, l_len) }
}
/// Attempts to split `self` in two.
///
/// Returns `None` if `l_len` is greater than the length of `self`'s
/// trailing slice, or if the given