zerocopy/split_at.rs
1// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0 OR MIT
2//
3// Copyright 2025 The Fuchsia Authors
4//
5// Licensed under the 2-Clause BSD License <LICENSE-BSD or
6// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
7// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
8// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
9// This file may not be copied, modified, or distributed except according to
10// those terms.
11
12use super::*;
13use crate::pointer::invariant::{Aligned, Exclusive, Invariants, Safe, Shared};
14
15/// Types that can be split in two.
16///
17/// This trait generalizes Rust's existing support for splitting slices to
18/// support slices and slice-based dynamically-sized types ("slice DSTs").
19///
20/// For a `repr(C, packed)` or `repr(C, packed(N))` struct, the derive wraps
21/// the trailing field's [`Elem`](Self::Elem) in [`Unalign`]. The returned
22/// slice can therefore be accessed even when packing misaligns the original
23/// elements. Each packed struct in the trailing-field chain adds one wrapper;
24/// unpacked structs and [`ManuallyDrop`] forward their trailing type's `Elem`.
25///
26/// # Implementation
27///
28/// **Do not implement this trait yourself!** Instead, use
29/// [`#[derive(SplitAt)]`][derive]; e.g.:
30///
31/// ```
32/// # use zerocopy_derive::{SplitAt, KnownLayout};
33/// #[derive(SplitAt, KnownLayout)]
34/// #[repr(C)]
35/// struct MyStruct<T: ?Sized> {
36/// # /*
37/// ...,
38/// # */
39/// // `SplitAt` types must have at least one field.
40/// field: T,
41/// }
42/// ```
43///
44/// This derive performs a sophisticated, compile-time safety analysis to
45/// determine whether a type is `SplitAt`.
46///
47/// A packed struct exposes its trailing elements through `Unalign`:
48///
49/// ```
50/// use zerocopy::{FromBytes, SplitAt, Unalign};
51/// # use zerocopy_derive::*;
52///
53/// #[derive(FromBytes, IntoBytes, KnownLayout, SplitAt)]
54/// #[repr(C, packed)]
55/// struct Packet {
56/// tag: u8,
57/// words: [u16],
58/// }
59///
60/// let mut bytes = [0u8; 5];
61/// let packet = Packet::mut_from_bytes(&mut bytes[..]).unwrap();
62/// let (left, right): (&mut Packet, &mut [Unalign<u16>]) =
63/// packet.split_at_mut(1).unwrap().via_into_bytes();
64/// left.tag = 1;
65/// right[0] = Unalign::new(0x0202);
66/// assert_eq!(bytes, [1, 0, 0, 2, 2]);
67/// ```
68///
69/// # Safety
70///
71/// This trait does not convey any safety guarantees to code outside this crate.
72///
73/// You must not rely on the `#[doc(hidden)]` internals of `SplitAt`. Future
74/// releases of zerocopy may make backwards-breaking changes to these items,
75/// including changes that only affect soundness, which may cause code which
76/// uses those items to silently become unsound.
77///
78#[cfg_attr(feature = "derive", doc = "[derive]: zerocopy_derive::SplitAt")]
79#[cfg_attr(
80 not(feature = "derive"),
81 doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.SplitAt.html"),
82)]
83#[cfg_attr(
84 not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
85 diagnostic::on_unimplemented(note = "Consider adding `#[derive(SplitAt)]` to `{Self}`")
86)]
87// # Safety
88//
89// `Self` is a slice, a `repr(C)` (possibly packed) or `repr(transparent)` slice
90// DST, or `ManuallyDrop<T>` for some `T: SplitAt`.
91//
92// `Self::Elem` has the same size, bit validity, and `UnsafeCell` coverage as
93// the actual trailing element type. Access through either representation
94// preserves the other's validity, including writes through mutable references
95// and interior mutation through shared references. For every aligned `Self`,
96// its trailing slice's address is aligned for `Self::Elem`.
97pub unsafe trait SplitAt: KnownLayout<PointerMetadata = usize> {
98 /// The element type exposed by the split's returned slice.
99 ///
100 /// For `[T]`, this is `T`. For a struct, this is the trailing field's `Elem`,
101 /// wrapped in [`Unalign`] if the struct is packed. Nested packed structs
102 /// produce nested `Unalign` wrappers.
103 type Elem;
104
105 #[doc(hidden)]
106 fn only_derive_is_allowed_to_implement_this_trait()
107 where
108 Self: Sized;
109
110 /// Unsafely splits `self` in two.
111 ///
112 /// # Safety
113 ///
114 /// The caller promises that `l_len` is not greater than the length of
115 /// `self`'s trailing slice.
116 ///
117 #[doc = codegen_section!(
118 header = "h5",
119 bench = "split_at_unchecked",
120 format = "coco",
121 arity = 2,
122 [
123 open
124 @index 1
125 @title "Unsized"
126 @variant "dynamic_size"
127 ],
128 [
129 @index 2
130 @title "Dynamically Padded"
131 @variant "dynamic_padding"
132 ]
133 )]
134 #[inline]
135 #[must_use]
136 unsafe fn split_at_unchecked(&self, l_len: usize) -> Split<&Self> {
137 // SAFETY: By precondition on the caller, `l_len <= self.len()`.
138 unsafe { Split::<&Self>::new(self, l_len) }
139 }
140
141 /// Attempts to split `self` in two.
142 ///
143 /// Returns `None` if `l_len` is greater than the length of `self`'s
144 /// trailing slice.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use zerocopy::{SplitAt, FromBytes};
150 /// # use zerocopy_derive::*;
151 ///
152 /// #[derive(SplitAt, FromBytes, KnownLayout, Immutable)]
153 /// #[repr(C)]
154 /// struct Packet {
155 /// length: u8,
156 /// body: [u8],
157 /// }
158 ///
159 /// // These bytes encode a `Packet`.
160 /// let bytes = &[4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
161 ///
162 /// let packet = Packet::ref_from_bytes(bytes).unwrap();
163 ///
164 /// assert_eq!(packet.length, 4);
165 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
166 ///
167 /// // Attempt to split `packet` at `length`.
168 /// let split = packet.split_at(packet.length as usize).unwrap();
169 ///
170 /// // Use the `Immutable` bound on `Packet` to prove that it's okay to
171 /// // return concurrent references to `packet` and `rest`.
172 /// let (packet, rest) = split.via_immutable();
173 ///
174 /// assert_eq!(packet.length, 4);
175 /// assert_eq!(packet.body, [1, 2, 3, 4]);
176 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
177 /// ```
178 ///
179 #[doc = codegen_section!(
180 header = "h5",
181 bench = "split_at",
182 format = "coco",
183 arity = 2,
184 [
185 open
186 @index 1
187 @title "Unsized"
188 @variant "dynamic_size"
189 ],
190 [
191 @index 2
192 @title "Dynamically Padded"
193 @variant "dynamic_padding"
194 ]
195 )]
196 #[inline]
197 #[must_use = "has no side effects"]
198 fn split_at(&self, l_len: usize) -> Option<Split<&Self>> {
199 MetadataOf::new_in_bounds(self, l_len).map(
200 #[inline(always)]
201 |l_len| {
202 // SAFETY: We have ensured that `l_len <= self.len()` (by
203 // post-condition on `MetadataOf::new_in_bounds`)
204 unsafe { Split::new(self, l_len.get()) }
205 },
206 )
207 }
208
209 /// Unsafely splits `self` in two.
210 ///
211 /// # Safety
212 ///
213 /// The caller promises that `l_len` is not greater than the length of
214 /// `self`'s trailing slice.
215 ///
216 #[doc = codegen_section!(
217 header = "h5",
218 name = "split_at_mut_unchecked",
219 /// See [`SplitAt::split_at_unchecked`](#method.split_at_unchecked.codegen).
220 )]
221 #[inline]
222 #[must_use]
223 unsafe fn split_at_mut_unchecked(&mut self, l_len: usize) -> Split<&mut Self> {
224 // SAFETY: By precondition on the caller, `l_len <= self.len()`.
225 unsafe { Split::<&mut Self>::new(self, l_len) }
226 }
227
228 /// Attempts to split `self` in two.
229 ///
230 /// Returns `None` if `l_len` is greater than the length of `self`'s
231 /// trailing slice.
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// use zerocopy::{SplitAt, FromBytes};
237 /// # use zerocopy_derive::*;
238 ///
239 /// #[derive(SplitAt, FromBytes, KnownLayout, IntoBytes)]
240 /// #[repr(C)]
241 /// struct Packet<B: ?Sized> {
242 /// length: u8,
243 /// body: B,
244 /// }
245 ///
246 /// // These bytes encode a `Packet`.
247 /// let mut bytes = &mut [4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
248 ///
249 /// let packet = Packet::<[u8]>::mut_from_bytes(bytes).unwrap();
250 ///
251 /// assert_eq!(packet.length, 4);
252 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
253 ///
254 /// {
255 /// // Attempt to split `packet` at `length`.
256 /// let split = packet.split_at_mut(packet.length as usize).unwrap();
257 ///
258 /// // Use the `IntoBytes` bound on `Packet` to prove that it's okay to
259 /// // return concurrent references to `packet` and `rest`.
260 /// let (packet, rest) = split.via_into_bytes();
261 ///
262 /// assert_eq!(packet.length, 4);
263 /// assert_eq!(packet.body, [1, 2, 3, 4]);
264 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
265 ///
266 /// rest.fill(0);
267 /// }
268 ///
269 /// assert_eq!(packet.length, 4);
270 /// assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
271 /// ```
272 ///
273 #[doc = codegen_section!(
274 header = "h5",
275 name = "split_at_mut",
276 /// See [`SplitAt::split_at`](#method.split_at.codegen).
277 )]
278 #[inline]
279 fn split_at_mut(&mut self, l_len: usize) -> Option<Split<&mut Self>> {
280 MetadataOf::new_in_bounds(self, l_len).map(
281 #[inline(always)]
282 |l_len| {
283 // SAFETY: We have ensured that `l_len <= self.len()` (by
284 // post-condition on `MetadataOf::new_in_bounds`)
285 unsafe { Split::new(self, l_len.get()) }
286 },
287 )
288 }
289}
290
291// SAFETY: `[T]` exposes its own element type, preserving size, validity, and
292// `UnsafeCell` coverage. An aligned slice is aligned for its elements.
293unsafe impl<T> SplitAt for [T] {
294 type Elem = T;
295
296 #[inline]
297 #[allow(dead_code)]
298 fn only_derive_is_allowed_to_implement_this_trait()
299 where
300 Self: Sized,
301 {
302 }
303}
304
305// SAFETY: `ManuallyDrop<T>` has the same layout and bit validity as `T` [1].
306// Its `KnownLayout` implementation preserves `T`'s metadata and trailing-slice
307// layout. Forwarding `T::Elem` therefore preserves its size, validity, and
308// alignment guarantees. Its `UnsafeCell` coverage also matches `T`'s, as
309// established for `ManuallyDrop` in `impls.rs`; accesses through the forwarded
310// element representation preserve validity in both directions.
311//
312// [1] Per https://doc.rust-lang.org/1.93.0/std/mem/struct.ManuallyDrop.html:
313//
314// `ManuallyDrop<T>` is guaranteed to have the same layout and bit validity as
315// `T`
316unsafe impl<T: ?Sized + SplitAt> SplitAt for ManuallyDrop<T> {
317 type Elem = T::Elem;
318
319 #[inline]
320 #[allow(dead_code)]
321 fn only_derive_is_allowed_to_implement_this_trait()
322 where
323 Self: Sized,
324 {
325 }
326}
327
328/// A `T` that has been split into two possibly-overlapping parts.
329///
330/// For some dynamically sized types, the padding that appears after the
331/// trailing slice field [is a dynamic function of the trailing slice
332/// length](KnownLayout#slice-dst-layout). If `T` is split at a length that
333/// requires trailing padding, the trailing padding of the left part of the
334/// split `T` will overlap the right part. If `T` is a mutable reference or
335/// permits interior mutation, you must ensure that the left and right parts do
336/// not overlap. Use [`Self::via_into_bytes`] or
337/// [`Self::via_no_dynamic_padding`] to establish this without a runtime check,
338/// or [`Self::via_runtime_check`] to check a particular split. Shared references
339/// to an [`Immutable`] type may overlap; use [`Self::via_immutable`] in that
340/// case.
341#[derive(Debug)]
342pub struct Split<T> {
343 /// A pointer to the source slice DST.
344 source: T,
345 /// The length of the future left half of `source`.
346 ///
347 /// # Safety
348 ///
349 /// If `source` is a pointer to a slice DST, `l_len` is no greater than
350 /// `source`'s length.
351 l_len: usize,
352}
353
354impl<T> Split<T> {
355 /// Produces a `Split` of `source` with `l_len`.
356 ///
357 /// # Safety
358 ///
359 /// `l_len` is no greater than `source`'s length.
360 #[inline(always)]
361 unsafe fn new(source: T, l_len: usize) -> Self {
362 Self { source, l_len }
363 }
364}
365
366impl<'a, T> Split<&'a T>
367where
368 T: ?Sized + SplitAt,
369{
370 #[inline(always)]
371 fn into_ptr(self) -> Split<Ptr<'a, T, (Shared, Aligned, Safe)>> {
372 let source = Ptr::from_ref(self.source);
373 // SAFETY: `Ptr::from_ref(self.source)` points to exactly `self.source`
374 // and thus maintains the invariants of `self` with respect to `l_len`.
375 unsafe { Split::new(source, self.l_len) }
376 }
377
378 /// Produces the split parts of `self`, using [`Immutable`] to ensure that
379 /// it is sound to have concurrent references to both parts.
380 ///
381 /// # Examples
382 ///
383 /// ```
384 /// use zerocopy::{SplitAt, FromBytes};
385 /// # use zerocopy_derive::*;
386 ///
387 /// #[derive(SplitAt, FromBytes, KnownLayout, Immutable)]
388 /// #[repr(C)]
389 /// struct Packet {
390 /// length: u8,
391 /// body: [u8],
392 /// }
393 ///
394 /// // These bytes encode a `Packet`.
395 /// let bytes = &[4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
396 ///
397 /// let packet = Packet::ref_from_bytes(bytes).unwrap();
398 ///
399 /// assert_eq!(packet.length, 4);
400 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
401 ///
402 /// // Attempt to split `packet` at `length`.
403 /// let split = packet.split_at(packet.length as usize).unwrap();
404 ///
405 /// // Use the `Immutable` bound on `Packet` to prove that it's okay to
406 /// // return concurrent references to `packet` and `rest`.
407 /// let (packet, rest) = split.via_immutable();
408 ///
409 /// assert_eq!(packet.length, 4);
410 /// assert_eq!(packet.body, [1, 2, 3, 4]);
411 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
412 /// ```
413 ///
414 #[doc = codegen_section!(
415 header = "h5",
416 bench = "split_via_immutable",
417 format = "coco",
418 arity = 2,
419 [
420 open
421 @index 1
422 @title "Unsized"
423 @variant "dynamic_size"
424 ],
425 [
426 @index 2
427 @title "Dynamically Padded"
428 @variant "dynamic_padding"
429 ]
430 )]
431 #[must_use = "has no side effects"]
432 #[inline(always)]
433 pub fn via_immutable(self) -> (&'a T, &'a [T::Elem])
434 where
435 T: Immutable,
436 {
437 let (l, r) = self.into_ptr().via_immutable();
438 (l.as_ref(), r.as_ref())
439 }
440
441 /// Produces the split parts of `self`, using [`IntoBytes`] to ensure that
442 /// it is sound to have concurrent references to both parts.
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// use zerocopy::{SplitAt, FromBytes};
448 /// # use zerocopy_derive::*;
449 ///
450 /// #[derive(SplitAt, FromBytes, KnownLayout, Immutable, IntoBytes)]
451 /// #[repr(C)]
452 /// struct Packet<B: ?Sized> {
453 /// length: u8,
454 /// body: B,
455 /// }
456 ///
457 /// // These bytes encode a `Packet`.
458 /// let bytes = &[4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
459 ///
460 /// let packet = Packet::<[u8]>::ref_from_bytes(bytes).unwrap();
461 ///
462 /// assert_eq!(packet.length, 4);
463 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
464 ///
465 /// // Attempt to split `packet` at `length`.
466 /// let split = packet.split_at(packet.length as usize).unwrap();
467 ///
468 /// // Use the `IntoBytes` bound on `Packet` to prove that it's okay to
469 /// // return concurrent references to `packet` and `rest`.
470 /// let (packet, rest) = split.via_into_bytes();
471 ///
472 /// assert_eq!(packet.length, 4);
473 /// assert_eq!(packet.body, [1, 2, 3, 4]);
474 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
475 /// ```
476 ///
477 #[doc = codegen_section!(
478 header = "h5",
479 name = "split_via_into_bytes",
480 /// See [`Split::via_immutable`](#method.split_via_immutable.codegen).
481 )]
482 #[must_use = "has no side effects"]
483 #[inline(always)]
484 pub fn via_into_bytes(self) -> (&'a T, &'a [T::Elem])
485 where
486 T: IntoBytes,
487 {
488 let (l, r) = self.into_ptr().via_into_bytes();
489 (l.as_ref(), r.as_ref())
490 }
491
492 /// Produces the split parts of `self` using [`Self::via_no_dynamic_padding`].
493 #[deprecated(note = "use `Split::via_no_dynamic_padding` instead")]
494 #[doc(hidden)]
495 #[must_use = "has no side effects"]
496 #[inline(always)]
497 pub fn via_unaligned(self) -> (&'a T, &'a [T::Elem])
498 where
499 T: Unaligned,
500 {
501 self.via_no_dynamic_padding()
502 }
503
504 /// Produces the split parts of `self` using a compile-time assertion to
505 /// ensure that it is unconditionally sound to have concurrent references to
506 /// both parts.
507 ///
508 /// When possible, you should prefer using [`Self::via_into_bytes`], which
509 /// ensures this safety property through regular trait bounds.
510 ///
511 /// # Examples
512 ///
513 /// In the below example, a single byte of padding exists (on most
514 /// platforms) between `Packet<[u16]>`'s `length` and `body` fields,
515 /// precluding the use of [`Self::via_into_bytes`].
516 ///
517 /// ```
518 /// use zerocopy::SplitAt;
519 /// # use zerocopy_derive::*;
520 ///
521 /// #[derive(SplitAt, KnownLayout)]
522 /// #[repr(C)]
523 /// struct Packet<B: ?Sized> {
524 /// length: u8,
525 /// body: B,
526 /// }
527 ///
528 /// let packet: &Packet<[u16]> = &Packet { length: 4, body: [1u16, 2, 3, 4, 5, 6, 7, 8, 9] };
529 ///
530 /// assert_eq!(packet.length, 4);
531 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
532 ///
533 /// if let Some(split) = packet.split_at(packet.length as usize) {
534 /// // Every body length requires no trailing padding.
535 /// let (packet, rest) = split.via_no_dynamic_padding();
536 /// assert_eq!(packet.length, 4);
537 /// assert_eq!(packet.body, [1, 2, 3, 4]);
538 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
539 /// } else {
540 /// unreachable!("The packet's length field is within its body");
541 /// }
542 /// ```
543 ///
544 /// # Compile-Time Assertions
545 ///
546 /// This method rejects at compile-time any type that admits dynamic
547 /// trailing padding. In the below example, some `split_at` indices would
548 /// produce left parts whose trailing padding overlaps with the right part:
549 ///
550 /// ```compile_fail,E0080
551 /// use zerocopy::SplitAt;
552 /// # use zerocopy_derive::*;
553 ///
554 /// #[derive(SplitAt, KnownLayout)]
555 /// #[repr(C, align(2))]
556 /// struct Packet<B: ?Sized> {
557 /// length: u16,
558 /// body: B,
559 /// }
560 ///
561 /// let packet: &Packet<[u8]> = &Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };
562 ///
563 /// if let Some(split) = packet.split_at(packet.length as usize) {
564 /// let _ = split.via_no_dynamic_padding(); // ⚠ Compile Error!
565 /// } else {
566 /// unreachable!("The packet's length field is within its body");
567 /// }
568 /// ```
569 ///
570 /// If you need to split such types, use [`Self::via_runtime_check`].
571 ///
572 #[doc = codegen_section!(
573 header = "h5",
574 name = "split_via_no_dynamic_padding",
575 /// See [`Split::via_immutable`](#method.split_via_immutable.codegen).
576 )]
577 #[must_use = "has no side effects"]
578 #[inline(always)]
579 pub fn via_no_dynamic_padding(self) -> (&'a T, &'a [T::Elem]) {
580 let (l, r) = self.into_ptr().via_no_dynamic_padding();
581 (l.as_ref(), r.as_ref())
582 }
583
584 /// Produces the split parts of `self`, using a dynamic check to ensure that
585 /// it is sound to have concurrent references to both parts. You should
586 /// prefer using [`Self::via_immutable`], [`Self::via_into_bytes`], or
587 /// [`Self::via_no_dynamic_padding`], which perform no runtime check.
588 ///
589 /// Note that this check is overly conservative if `T` is [`Immutable`]; for
590 /// some types, this check will reject some splits which
591 /// [`Self::via_immutable`] will accept.
592 ///
593 /// # Examples
594 ///
595 /// ```
596 /// use zerocopy::SplitAt;
597 /// # use zerocopy_derive::*;
598 ///
599 /// #[derive(SplitAt, KnownLayout)]
600 /// #[repr(C, align(2))]
601 /// struct Packet<B: ?Sized> {
602 /// length: u16,
603 /// body: B,
604 /// }
605 ///
606 /// let packet: &Packet<[u8]> = &Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };
607 ///
608 /// assert_eq!(packet.length, 4);
609 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
610 ///
611 /// // The two-byte prefix and four-byte body need no trailing padding.
612 /// if let Some(split) = packet.split_at(packet.length as usize) {
613 /// if let Ok((packet, rest)) = split.via_runtime_check() {
614 /// assert_eq!(packet.length, 4);
615 /// assert_eq!(packet.body, [1, 2, 3, 4]);
616 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
617 /// } else {
618 /// unreachable!("A four-byte body requires no trailing padding");
619 /// }
620 /// } else {
621 /// unreachable!("The packet's length field is within its body");
622 /// }
623 ///
624 /// // A three-byte body needs a padding byte that would overlap `rest`.
625 /// if let Some(split) = packet.split_at((packet.length - 1) as usize) {
626 /// assert!(split.via_runtime_check().is_err());
627 /// } else {
628 /// unreachable!("One less than the packet's length is within its body");
629 /// }
630 /// ```
631 ///
632 #[doc = codegen_section!(
633 header = "h5",
634 bench = "split_via_runtime_check",
635 format = "coco",
636 arity = 2,
637 [
638 open
639 @index 1
640 @title "Unsized"
641 @variant "dynamic_size"
642 ],
643 [
644 @index 2
645 @title "Dynamically Padded"
646 @variant "dynamic_padding"
647 ]
648 )]
649 #[must_use = "has no side effects"]
650 #[inline(always)]
651 pub fn via_runtime_check(self) -> Result<(&'a T, &'a [T::Elem]), Self> {
652 match self.into_ptr().via_runtime_check() {
653 Ok((l, r)) => Ok((l.as_ref(), r.as_ref())),
654 Err(s) => Err(s.into_ref()),
655 }
656 }
657
658 /// Unsafely produces the split parts of `self`.
659 ///
660 /// # Safety
661 ///
662 /// If `T` permits interior mutation, the trailing padding bytes of the left
663 /// portion must not overlap the right portion. For some dynamically sized
664 /// types, the padding that appears after the trailing slice field [is a
665 /// dynamic function of the trailing slice
666 /// length](KnownLayout#slice-dst-layout). Thus, for some types, this
667 /// condition is dependent on the length of the left portion.
668 ///
669 #[doc = codegen_section!(
670 header = "h5",
671 bench = "split_via_unchecked",
672 format = "coco",
673 arity = 2,
674 [
675 open
676 @index 1
677 @title "Unsized"
678 @variant "dynamic_size"
679 ],
680 [
681 @index 2
682 @title "Dynamically Padded"
683 @variant "dynamic_padding"
684 ]
685 )]
686 #[must_use = "has no side effects"]
687 #[inline(always)]
688 pub unsafe fn via_unchecked(self) -> (&'a T, &'a [T::Elem]) {
689 // SAFETY: The aliasing of `self.into_ptr()` is not `Exclusive`, but the
690 // caller has promised that if `T` permits interior mutation then the
691 // left and right portions of `self` split at `l_len` do not overlap.
692 let (l, r) = unsafe { self.into_ptr().via_unchecked() };
693 (l.as_ref(), r.as_ref())
694 }
695}
696
697impl<'a, T> Split<&'a mut T>
698where
699 T: ?Sized + SplitAt,
700{
701 #[inline(always)]
702 fn into_ptr(self) -> Split<Ptr<'a, T, (Exclusive, Aligned, Safe)>> {
703 let source = Ptr::from_mut(self.source);
704 // SAFETY: `Ptr::from_mut(self.source)` points to exactly `self.source`,
705 // and thus maintains the invariants of `self` with respect to `l_len`.
706 unsafe { Split::new(source, self.l_len) }
707 }
708
709 /// Produces the split parts of `self`, using [`IntoBytes`] to ensure that
710 /// it is sound to have concurrent references to both parts.
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// use zerocopy::{SplitAt, FromBytes};
716 /// # use zerocopy_derive::*;
717 ///
718 /// #[derive(SplitAt, FromBytes, KnownLayout, IntoBytes)]
719 /// #[repr(C)]
720 /// struct Packet<B: ?Sized> {
721 /// length: u8,
722 /// body: B,
723 /// }
724 ///
725 /// // These bytes encode a `Packet`.
726 /// let mut bytes = &mut [4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
727 ///
728 /// let packet = Packet::<[u8]>::mut_from_bytes(bytes).unwrap();
729 ///
730 /// assert_eq!(packet.length, 4);
731 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
732 ///
733 /// {
734 /// // Attempt to split `packet` at `length`.
735 /// let split = packet.split_at_mut(packet.length as usize).unwrap();
736 ///
737 /// // Use the `IntoBytes` bound on `Packet` to prove that it's okay to
738 /// // return concurrent references to `packet` and `rest`.
739 /// let (packet, rest) = split.via_into_bytes();
740 ///
741 /// assert_eq!(packet.length, 4);
742 /// assert_eq!(packet.body, [1, 2, 3, 4]);
743 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
744 ///
745 /// rest.fill(0);
746 /// }
747 ///
748 /// assert_eq!(packet.length, 4);
749 /// assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
750 /// ```
751 ///
752 #[doc = codegen_section!(
753 /// # Code Generation
754 ///
755 /// See [`Split::via_immutable`](#method.split_via_immutable.codegen).
756 )]
757 #[must_use = "has no side effects"]
758 #[inline(always)]
759 pub fn via_into_bytes(self) -> (&'a mut T, &'a mut [T::Elem])
760 where
761 T: IntoBytes,
762 {
763 let (l, r) = self.into_ptr().via_into_bytes();
764 (l.as_mut(), r.as_mut())
765 }
766
767 /// Produces the split parts of `self` using [`Self::via_no_dynamic_padding`].
768 #[deprecated(note = "use `Split::via_no_dynamic_padding` instead")]
769 #[doc(hidden)]
770 #[must_use = "has no side effects"]
771 #[inline(always)]
772 pub fn via_unaligned(self) -> (&'a mut T, &'a mut [T::Elem])
773 where
774 T: Unaligned,
775 {
776 self.via_no_dynamic_padding()
777 }
778
779 /// Produces the split parts of `self` using a compile-time assertion to
780 /// ensure that it is unconditionally sound to have concurrent references to
781 /// both parts.
782 ///
783 /// When possible, you should prefer using [`Self::via_into_bytes`], which
784 /// ensures this safety property through regular trait bounds.
785 ///
786 /// # Examples
787 ///
788 /// In the below example, a single byte of padding exists (on most
789 /// platforms) between `Packet<[u16]>`'s `length` and `body` fields,
790 /// precluding the use of [`Self::via_into_bytes`].
791 ///
792 /// ```
793 /// use zerocopy::SplitAt;
794 /// # use zerocopy_derive::*;
795 ///
796 /// #[derive(SplitAt, KnownLayout)]
797 /// #[repr(C)]
798 /// struct Packet<B: ?Sized> {
799 /// length: u8,
800 /// body: B,
801 /// }
802 ///
803 /// let packet: &mut Packet<[u16]> = &mut Packet { length: 4, body: [1u16, 2, 3, 4, 5, 6, 7, 8, 9] };
804 ///
805 /// assert_eq!(packet.length, 4);
806 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
807 ///
808 /// // Every body length requires no trailing padding.
809 /// if let Some(split) = packet.split_at_mut(packet.length as usize) {
810 /// let (packet, rest) = split.via_no_dynamic_padding();
811 /// assert_eq!(packet.length, 4);
812 /// assert_eq!(packet.body, [1, 2, 3, 4]);
813 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
814 /// rest.fill(0);
815 /// } else {
816 /// unreachable!("The packet's length field is within its body");
817 /// }
818 ///
819 /// assert_eq!(packet.length, 4);
820 /// assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
821 /// ```
822 ///
823 /// # Compile-Time Assertions
824 ///
825 /// This method rejects at compile-time any type that admits dynamic
826 /// trailing padding. In the below example, some `split_at` indices would
827 /// produce left parts whose trailing padding overlaps with the right part:
828 ///
829 /// ```compile_fail,E0080
830 /// use zerocopy::SplitAt;
831 /// # use zerocopy_derive::*;
832 ///
833 /// #[derive(SplitAt, KnownLayout)]
834 /// #[repr(C, align(2))]
835 /// struct Packet<B: ?Sized> {
836 /// length: u16,
837 /// body: B,
838 /// }
839 ///
840 /// let packet: &mut Packet<[u8]> = &mut Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };
841 ///
842 /// if let Some(split) = packet.split_at_mut(packet.length as usize) {
843 /// let _ = split.via_no_dynamic_padding(); // ⚠ Compile Error!
844 /// } else {
845 /// unreachable!("The packet's length field is within its body");
846 /// }
847 /// ```
848 ///
849 /// If you need to split such types, use [`Self::via_runtime_check`].
850 ///
851 #[doc = codegen_section!(
852 /// # Code Generation
853 ///
854 /// See [`Split::via_immutable`](#method.split_via_immutable.codegen).
855 )]
856 #[must_use = "has no side effects"]
857 #[inline(always)]
858 pub fn via_no_dynamic_padding(self) -> (&'a mut T, &'a mut [T::Elem]) {
859 let (l, r) = self.into_ptr().via_no_dynamic_padding();
860 (l.as_mut(), r.as_mut())
861 }
862
863 /// Produces the split parts of `self`, using a dynamic check to ensure that
864 /// it is sound to have concurrent references to both parts. You should
865 /// prefer using [`Self::via_into_bytes`] or
866 /// [`Self::via_no_dynamic_padding`], which perform no runtime check.
867 ///
868 /// # Examples
869 ///
870 /// ```
871 /// use zerocopy::SplitAt;
872 /// # use zerocopy_derive::*;
873 ///
874 /// #[derive(SplitAt, KnownLayout)]
875 /// #[repr(C, align(2))]
876 /// struct Packet<B: ?Sized> {
877 /// length: u16,
878 /// body: B,
879 /// }
880 ///
881 /// let packet: &mut Packet<[u8]> = &mut Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };
882 ///
883 /// assert_eq!(packet.length, 4);
884 /// assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
885 ///
886 /// // The two-byte prefix and four-byte body need no trailing padding.
887 /// if let Some(split) = packet.split_at_mut(packet.length as usize) {
888 /// if let Ok((packet, rest)) = split.via_runtime_check() {
889 /// assert_eq!(packet.length, 4);
890 /// assert_eq!(packet.body, [1, 2, 3, 4]);
891 /// assert_eq!(rest, [5, 6, 7, 8, 9]);
892 /// rest.fill(0);
893 /// } else {
894 /// unreachable!("A four-byte body requires no trailing padding");
895 /// }
896 /// } else {
897 /// unreachable!("The packet's length field is within its body");
898 /// }
899 ///
900 /// assert_eq!(packet.length, 4);
901 /// assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
902 /// ```
903 ///
904 #[doc = codegen_section!(
905 /// # Code Generation
906 ///
907 /// See [`Split::via_runtime_check`](#method.split_via_runtime_check.codegen).
908 )]
909 #[must_use = "has no side effects"]
910 #[inline(always)]
911 pub fn via_runtime_check(self) -> Result<(&'a mut T, &'a mut [T::Elem]), Self> {
912 match self.into_ptr().via_runtime_check() {
913 Ok((l, r)) => Ok((l.as_mut(), r.as_mut())),
914 Err(s) => Err(s.into_mut()),
915 }
916 }
917
918 /// Unsafely produces the split parts of `self`.
919 ///
920 /// # Safety
921 ///
922 /// The trailing padding bytes of the left portion must not overlap the
923 /// right portion. For some dynamically sized types, the padding that
924 /// appears after the trailing slice field [is a dynamic function of the
925 /// trailing slice length](KnownLayout#slice-dst-layout). Thus, for some
926 /// types, this condition is dependent on the length of the left portion.
927 ///
928 #[doc = codegen_section!(
929 /// # Code Generation
930 ///
931 /// See [`Split::via_unchecked`](#method.split_via_unchecked.codegen).
932 )]
933 #[must_use = "has no side effects"]
934 #[inline(always)]
935 pub unsafe fn via_unchecked(self) -> (&'a mut T, &'a mut [T::Elem]) {
936 // SAFETY: The aliasing of `self.into_ptr()` is `Exclusive`, and the
937 // caller has promised that the left and right portions of `self` split
938 // at `l_len` do not overlap.
939 let (l, r) = unsafe { self.into_ptr().via_unchecked() };
940 (l.as_mut(), r.as_mut())
941 }
942}
943
944impl<'a, T, I> Split<Ptr<'a, T, I>>
945where
946 T: ?Sized + SplitAt,
947 I: Invariants<Alignment = Aligned, Validity = Safe>,
948{
949 fn into_ref(self) -> Split<&'a T>
950 where
951 I: Invariants<Aliasing = Shared>,
952 {
953 // SAFETY: `self.source.as_ref()` points to exactly the same referent as
954 // `self.source` and thus maintains the invariants of `self` with
955 // respect to `l_len`.
956 unsafe { Split::new(self.source.as_ref(), self.l_len) }
957 }
958
959 fn into_mut(self) -> Split<&'a mut T>
960 where
961 I: Invariants<Aliasing = Exclusive>,
962 {
963 // SAFETY: `self.source.as_mut()` points to exactly the same referent as
964 // `self.source` and thus maintains the invariants of `self` with
965 // respect to `l_len`.
966 unsafe { Split::new(self.source.unify_invariants().as_mut(), self.l_len) }
967 }
968
969 /// Produces the length of `self`'s left part.
970 #[inline(always)]
971 fn l_len(&self) -> MetadataOf<T> {
972 // SAFETY: By invariant on `Split`, `self.l_len` is not greater than the
973 // length of `self.source`.
974 unsafe { MetadataOf::<T>::new_unchecked(self.l_len) }
975 }
976
977 /// Produces the split parts of `self`, using [`Immutable`] to ensure that
978 /// it is sound to have concurrent references to both parts.
979 #[inline(always)]
980 fn via_immutable(self) -> (Ptr<'a, T, I>, Ptr<'a, [T::Elem], I>)
981 where
982 T: Immutable,
983 I: Invariants<Aliasing = Shared>,
984 {
985 // SAFETY: `Aliasing = Shared` and `T: Immutable`.
986 unsafe { self.via_unchecked() }
987 }
988
989 /// Produces the split parts of `self`, using [`IntoBytes`] to ensure that
990 /// it is sound to have concurrent references to both parts.
991 #[inline(always)]
992 fn via_into_bytes(self) -> (Ptr<'a, T, I>, Ptr<'a, [T::Elem], I>)
993 where
994 T: IntoBytes,
995 {
996 // SAFETY: By `T: IntoBytes`, `T` has no padding for any length.
997 // Consequently, `T` can be split into non-overlapping parts at any
998 // index.
999 unsafe { self.via_unchecked() }
1000 }
1001
1002 /// Produces the split parts of `self` after the conservative layout
1003 /// predicate establishes that `T` never requires dynamic trailing padding.
1004 #[inline(always)]
1005 fn via_no_dynamic_padding(self) -> (Ptr<'a, T, I>, Ptr<'a, [T::Elem], I>) {
1006 static_assert!(
1007 T: ?Sized + KnownLayout => !T::LAYOUT.requires_dynamic_padding(),
1008 "`Split::via_no_dynamic_padding` cannot be used with a type whose layout may require dynamic trailing padding; use `Split::via_runtime_check` instead"
1009 );
1010
1011 // SAFETY: The assertion establishes that `requires_dynamic_padding()`
1012 // is false. By that method's guarantee, every valid metadata—including
1013 // `self.l_len()`, which is valid by `Split`'s invariant—describes an
1014 // object with no trailing padding. By the postcondition of
1015 // `PtrInner::split_at_unchecked`, the two returned referents are then
1016 // contiguous and non-overlapping. Since the source already conforms to
1017 // `I::Aliasing`, splitting it into disjoint byte ranges preserves that
1018 // invariant: under `Exclusive`, neither result aliases or accesses the
1019 // other's bytes; under `Shared`, interior mutation through one result
1020 // cannot mutate bytes pointed to by the other. This satisfies Rust's
1021 // reference aliasing rules [1].
1022 //
1023 // [1] Per https://doc.rust-lang.org/1.93.1/std/ptr/index.html#pointer-to-reference-conversion:
1024 //
1025 // When creating a mutable reference, then while this reference
1026 // exists, the memory it points to must not get accessed (read or
1027 // written) through any other pointer or reference not derived from
1028 // this reference.
1029 //
1030 // When creating a shared reference, then while this reference
1031 // exists, the memory it points to must not get mutated (except inside
1032 // `UnsafeCell`).
1033 unsafe { self.via_unchecked() }
1034 }
1035
1036 /// Produces the split parts of `self`, using a dynamic check to ensure that
1037 /// it is sound to have concurrent references to both parts. You should
1038 /// prefer using [`Self::via_immutable`], [`Self::via_into_bytes`], or
1039 /// [`Self::via_no_dynamic_padding`], which perform no runtime check.
1040 #[inline(always)]
1041 fn via_runtime_check(self) -> Result<(Ptr<'a, T, I>, Ptr<'a, [T::Elem], I>), Self> {
1042 let l_len = self.l_len();
1043 // `l_len` witnesses an object size at most `isize::MAX`, and
1044 // `KnownLayout::LAYOUT` guarantees that it contains the trailing
1045 // slice. Thus `padding_for_elems` returns the exact trailing padding.
1046 let trailing_padding = crate::trailing_slice_layout::<T>().padding_for_elems(l_len.get());
1047 // FIXME(#1290): Once we require `KnownLayout` on all fields, add an
1048 // `IS_IMMUTABLE` associated const, and add `T::IS_IMMUTABLE ||` to the
1049 // below check.
1050 if trailing_padding == 0 {
1051 // SAFETY: As established above, `trailing_padding` is the exact
1052 // padding after the left part's trailing slice. If it is zero,
1053 // the left and right parts are strictly non-overlapping.
1054 Ok(unsafe { self.via_unchecked() })
1055 } else {
1056 Err(self)
1057 }
1058 }
1059
1060 /// Unsafely produces the split parts of `self`.
1061 ///
1062 /// # Safety
1063 ///
1064 /// The caller promises that if `I::Aliasing` is [`Exclusive`] or `T`
1065 /// permits interior mutation, then the left part has no trailing padding.
1066 #[inline(always)]
1067 unsafe fn via_unchecked(self) -> (Ptr<'a, T, I>, Ptr<'a, [T::Elem], I>) {
1068 let l_len = self.l_len();
1069 let inner = self.source.as_inner();
1070
1071 // SAFETY: By invariant on `Self::l_len`, `l_len` is not greater than
1072 // the length of `inner`'s trailing slice.
1073 let (left, right) = unsafe { inner.split_at_unchecked(l_len) };
1074
1075 // Lemma 0: `left` and `right` conform to the aliasing invariant
1076 // `I::Aliasing`. Proof: If `I::Aliasing` is `Exclusive` or `T` permits
1077 // interior mutation, the caller promises that the left part has no
1078 // trailing padding. Consequently, by the postcondition of
1079 // `PtrInner::split_at_unchecked`, `left` and `right` do not overlap.
1080 // If `I::Aliasing` is shared and `T` forbids interior mutation, then
1081 // overlap between their referents is permissible.
1082
1083 // SAFETY:
1084 // 0. `left` conforms to the aliasing invariant of `I::Aliasing`, by Lemma 0.
1085 // 1. `left` conforms to the alignment invariant of `I::Alignment, because
1086 // the referents of `left` and `Self` have the same address and type
1087 // (and, thus, alignment requirement).
1088 // 2. `left` conforms to the validity invariant of `I::Validity`, neither
1089 // the type nor bytes of `left`'s referent have been changed.
1090 let left = unsafe { Ptr::from_inner(left) };
1091
1092 // SAFETY:
1093 // 0. `right` conforms to the aliasing invariant of `I::Aliasing`, by Lemma
1094 // 0.
1095 // 1. `right` conforms to the alignment invariant of `I::Alignment`:
1096 // if the source is aligned, `T: SplitAt` guarantees that its
1097 // trailing slice's address is aligned for `T::Elem`. Advancing by
1098 // whole elements preserves that alignment.
1099 // 2. `right` conforms to the validity invariant of `I::Validity`,
1100 // because `T: SplitAt` guarantees that `T::Elem` has the size and
1101 // bit validity of the original trailing element. It also guarantees
1102 // compatible shared and mutable access, so writes through `right`
1103 // preserve the original elements' validity and interior mutation
1104 // respects the original `UnsafeCell` coverage. The left part
1105 // cannot invalidate `right`: when the references are exclusive or
1106 // permit interior mutation, the caller guarantees no trailing
1107 // padding and hence no overlap.
1108 let right = unsafe { Ptr::from_inner(right) };
1109
1110 (left, right)
1111 }
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116 use core::{cell::Cell, mem::ManuallyDrop};
1117
1118 use crate::{Immutable, KnownLayout, SplitAt, Unalign, Unaligned};
1119
1120 #[derive(KnownLayout, SplitAt, Immutable, Unaligned)]
1121 #[repr(C, packed)]
1122 struct Packed<T: ?Sized> {
1123 prefix: u8,
1124 tail: ManuallyDrop<T>,
1125 }
1126
1127 #[derive(KnownLayout, SplitAt, Immutable)]
1128 #[repr(C, packed(2))]
1129 struct Packed2<T: ?Sized> {
1130 prefix: u8,
1131 tail: ManuallyDrop<T>,
1132 }
1133
1134 #[derive(KnownLayout, SplitAt, Immutable)]
1135 #[repr(C)]
1136 struct Inner<T: ?Sized> {
1137 prefix: u32,
1138 tail: T,
1139 }
1140
1141 #[test]
1142 fn test_split_at_packed() {
1143 use crate::{FromBytes, IntoBytes};
1144
1145 #[derive(FromBytes, IntoBytes, KnownLayout, SplitAt, Immutable, Unaligned)]
1146 #[repr(C, packed)]
1147 struct Packet {
1148 prefix: u8,
1149 tail: [u16],
1150 }
1151
1152 // The tail starts at an odd address, exercising unaligned reads and
1153 // writes on targets where `u16` has alignment 2.
1154 #[repr(align(8))]
1155 struct Bytes([u8; 9]);
1156
1157 for i in 0..=4 {
1158 let mut bytes = Bytes([1; 9]);
1159 let packet = Packet::ref_from_bytes(&bytes.0).unwrap();
1160 let (left, right): (&Packet, &[Unalign<u16>]) =
1161 packet.split_at(i).unwrap().via_immutable();
1162 assert_eq!(core::mem::size_of_val(left), 1 + 2 * i);
1163 assert_eq!(right.len(), 4 - i);
1164 assert!(right.iter().all(|elem| elem.get() == 0x0101));
1165 assert!(left.split_at(i).is_some());
1166 assert!(left.split_at(i + 1).is_none());
1167 assert!(packet.split_at(5).is_none());
1168
1169 let (_, right) = packet.split_at(i).unwrap().via_into_bytes();
1170 assert_eq!(right.len(), 4 - i);
1171 let (_, right) = packet.split_at(i).unwrap().via_no_dynamic_padding();
1172 assert_eq!(right.len(), 4 - i);
1173
1174 let packet = Packet::mut_from_bytes(&mut bytes.0).unwrap();
1175 let (left, right): (&mut Packet, &mut [Unalign<u16>]) =
1176 packet.split_at_mut(i).unwrap().via_runtime_check().ok().unwrap();
1177 left.prefix = 2;
1178 for elem in right {
1179 *elem = Unalign::new(0x0202);
1180 }
1181 assert_eq!(bytes.0[0], 2);
1182 assert!(bytes.0[1..1 + 2 * i].iter().all(|&byte| byte == 1));
1183 assert!(bytes.0[1 + 2 * i..].iter().all(|&byte| byte == 2));
1184 }
1185 }
1186
1187 #[test]
1188 fn test_split_at_nested_packed() {
1189 // A packing factor greater than 1 still exposes `Unalign` elements,
1190 // including when the factor is below the original element alignment.
1191 let mut words = Packed2 { prefix: 0, tail: ManuallyDrop::new([1u32, 2, 3]) };
1192 let dst: &mut Packed2<[u32]> = &mut words;
1193 let (left, right): (&mut _, &mut [Unalign<u32>]) =
1194 dst.split_at_mut(1).unwrap().via_no_dynamic_padding();
1195 left.prefix = 4;
1196 right[0] = Unalign::new(5);
1197 let dst: &Packed2<[u32]> = &words;
1198 let (left, right) = dst.split_at(0).unwrap().via_immutable();
1199 assert_eq!(left.prefix, 4);
1200 assert_eq!(right[0].get(), 1);
1201 assert_eq!(right[1].get(), 5);
1202 assert_eq!(right[2].get(), 3);
1203
1204 let mut packet = Inner {
1205 prefix: 0,
1206 tail: Packed2 {
1207 prefix: 1,
1208 tail: ManuallyDrop::new(Packed {
1209 prefix: 2,
1210 tail: ManuallyDrop::new([3u16, 4, 5]),
1211 }),
1212 },
1213 };
1214 let dst: &Inner<Packed2<Packed<[u16]>>> = &packet;
1215 let (left, right): (&_, &[Unalign<Unalign<u16>>]) =
1216 dst.split_at(1).unwrap().via_immutable();
1217 assert_eq!(left.prefix, 0);
1218 assert_eq!(right.len(), 2);
1219 assert_eq!(right[0].get().get(), 4);
1220 assert_eq!(right[1].get().get(), 5);
1221
1222 // Split the packed field separately: the unpacked outer struct's
1223 // padding does not constrain this split.
1224 let dst: &mut Packed2<Packed<[u16]>> = &mut packet.tail;
1225 let (left, right): (&mut _, &mut [Unalign<Unalign<u16>>]) =
1226 dst.split_at_mut(1).unwrap().via_no_dynamic_padding();
1227 left.prefix = 6;
1228 right[0] = Unalign::new(Unalign::new(7));
1229 let dst: &Inner<Packed2<Packed<[u16]>>> = &packet;
1230 let (_, right) = dst.split_at(0).unwrap().via_immutable();
1231 assert_eq!(right[0].get().get(), 3);
1232 assert_eq!(right[1].get().get(), 7);
1233 assert_eq!(right[2].get().get(), 5);
1234 }
1235
1236 #[test]
1237 fn test_split_at_packed_preserves_inner_padding() {
1238 for i in 0..=4 {
1239 let mut packet = Packed {
1240 prefix: 1,
1241 tail: ManuallyDrop::new(Inner { prefix: 0, tail: [2u8, 3, 4, 5] }),
1242 };
1243 let dst: &Packed<Inner<[u8]>> = &packet;
1244 let (left, right): (&_, &[Unalign<u8>]) = dst.split_at(i).unwrap().via_immutable();
1245 assert_eq!(right.len(), 4 - i);
1246 assert_eq!(right.first().map(Unalign::get), [2, 3, 4, 5].get(i).copied());
1247
1248 // The inner `u32` prefix makes the tail start at byte 5 of the
1249 // packed wrapper. Its size may still include inner padding.
1250 let has_padding = core::mem::size_of_val(left) != 5 + i;
1251 assert_eq!(dst.split_at(i).unwrap().via_runtime_check().is_err(), has_padding);
1252
1253 let dst: &mut Packed<Inner<[u8]>> = &mut packet;
1254 let split = dst.split_at_mut(i).unwrap().via_runtime_check();
1255 assert_eq!(split.is_err(), has_padding);
1256 if let Ok((left, right)) = split {
1257 left.prefix = 6;
1258 for elem in right {
1259 *elem = Unalign::new(7);
1260 }
1261 let dst: &Packed<Inner<[u8]>> = &packet;
1262 let (left, right) = dst.split_at(i).unwrap().via_immutable();
1263 assert_eq!(left.prefix, 6);
1264 assert!(right.iter().all(|elem| elem.get() == 7));
1265 }
1266 }
1267 }
1268
1269 #[test]
1270 fn test_split_at_packed_interior_mutation_and_zsts() {
1271 let packet = Packed {
1272 prefix: 0,
1273 tail: ManuallyDrop::new([Cell::new(1u8), Cell::new(2), Cell::new(3)]),
1274 };
1275 let dst: &Packed<[Cell<u8>]> = &packet;
1276 let (left, right): (&_, &[Unalign<Cell<u8>>]) =
1277 dst.split_at(1).unwrap().via_no_dynamic_padding();
1278 left.tail[0].set(4);
1279 right[0].try_deref().unwrap().set(5);
1280 assert_eq!(dst.tail[0].get(), 4);
1281 assert_eq!(dst.tail[1].get(), 5);
1282 assert_eq!(dst.tail[2].get(), 3);
1283
1284 let mut packet = Packed { prefix: 0, tail: ManuallyDrop::new([(); 3]) };
1285 for i in 0..=3 {
1286 let dst: &mut Packed<[()]> = &mut packet;
1287 let (left, right): (&mut _, &mut [Unalign<()>]) =
1288 dst.split_at_mut(i).unwrap().via_no_dynamic_padding();
1289 assert_eq!(left.tail.len(), i);
1290 assert_eq!(right.len(), 3 - i);
1291 assert_eq!(core::mem::size_of_val(left), 1);
1292 }
1293 }
1294
1295 #[cfg(feature = "derive")]
1296 #[test]
1297 fn test_split_at() {
1298 use crate::{FromBytes, Immutable, IntoBytes, KnownLayout, SplitAt};
1299
1300 #[derive(FromBytes, KnownLayout, SplitAt, IntoBytes, Immutable, Debug)]
1301 #[repr(C)]
1302 struct SliceDst<const OFFSET: usize> {
1303 prefix: [u8; OFFSET],
1304 trailing: [u8],
1305 }
1306
1307 #[allow(clippy::as_conversions)]
1308 fn test_split_at<const OFFSET: usize, const BUFFER_SIZE: usize>() {
1309 // Test `split_at`
1310 let n: usize = BUFFER_SIZE - OFFSET;
1311 let arr = [1; BUFFER_SIZE];
1312 let dst = SliceDst::<OFFSET>::ref_from_bytes(&arr[..]).unwrap();
1313 for i in 0..=n {
1314 let (l, r) = dst.split_at(i).unwrap().via_runtime_check().unwrap();
1315 let l_sum: u8 = l.trailing.iter().sum();
1316 let r_sum: u8 = r.iter().sum();
1317 assert_eq!(l_sum, i as u8);
1318 assert_eq!(r_sum, (n - i) as u8);
1319 assert_eq!(l_sum + r_sum, n as u8);
1320 }
1321
1322 // Test `split_at_mut`
1323 let n: usize = BUFFER_SIZE - OFFSET;
1324 let mut arr = [1; BUFFER_SIZE];
1325 let dst = SliceDst::<OFFSET>::mut_from_bytes(&mut arr[..]).unwrap();
1326 for i in 0..=n {
1327 let (l, r) = dst.split_at_mut(i).unwrap().via_runtime_check().unwrap();
1328 let l_sum: u8 = l.trailing.iter().sum();
1329 let r_sum: u8 = r.iter().sum();
1330 assert_eq!(l_sum, i as u8);
1331 assert_eq!(r_sum, (n - i) as u8);
1332 assert_eq!(l_sum + r_sum, n as u8);
1333 }
1334 }
1335
1336 test_split_at::<0, 16>();
1337 test_split_at::<1, 17>();
1338 test_split_at::<2, 18>();
1339 }
1340
1341 #[cfg(feature = "derive")]
1342 #[test]
1343 #[allow(clippy::as_conversions)]
1344 fn test_split_at_overlapping() {
1345 use crate::{FromBytes, Immutable, IntoBytes, KnownLayout, SplitAt};
1346
1347 #[derive(FromBytes, KnownLayout, SplitAt, Immutable)]
1348 #[repr(C, align(2))]
1349 struct SliceDst {
1350 prefix: u8,
1351 trailing: [u8],
1352 }
1353
1354 assert!(SliceDst::LAYOUT.requires_dynamic_padding());
1355
1356 const N: usize = 16;
1357
1358 let arr = [1u16; N];
1359 let dst = SliceDst::ref_from_bytes(arr.as_bytes()).unwrap();
1360
1361 for i in 0..N {
1362 let split = dst.split_at(i).unwrap().via_runtime_check();
1363 if i % 2 == 1 {
1364 assert!(split.is_ok());
1365 } else {
1366 assert!(split.is_err());
1367 }
1368 }
1369 }
1370 #[test]
1371 fn test_split_at_unchecked() {
1372 use crate::SplitAt;
1373 let mut arr = [1, 2, 3, 4];
1374 let slice = &arr[..];
1375 // SAFETY: 2 <= arr.len() (4)
1376 let split = unsafe { SplitAt::split_at_unchecked(slice, 2) };
1377 // SAFETY: SplitAt::split_at_unchecked guarantees that the split is valid.
1378 let (l, r) = unsafe { split.via_unchecked() };
1379 assert_eq!(l, &[1, 2]);
1380 assert_eq!(r, &[3, 4]);
1381
1382 let slice_mut = &mut arr[..];
1383 // SAFETY: 2 <= arr.len() (4)
1384 let split = unsafe { SplitAt::split_at_mut_unchecked(slice_mut, 2) };
1385 // SAFETY: SplitAt::split_at_mut_unchecked guarantees that the split is valid.
1386 let (l, r) = unsafe { split.via_unchecked() };
1387 assert_eq!(l, &mut [1, 2]);
1388 assert_eq!(r, &mut [3, 4]);
1389 }
1390
1391 #[test]
1392 fn test_split_at_via_methods() {
1393 use crate::{FromBytes, Immutable, IntoBytes, KnownLayout, SplitAt};
1394 #[derive(FromBytes, KnownLayout, SplitAt, IntoBytes, Immutable, Debug)]
1395 #[repr(C)]
1396 struct Packet {
1397 length: u8,
1398 body: [u8],
1399 }
1400
1401 let arr = [1, 2, 3, 4];
1402 let packet = Packet::ref_from_bytes(&arr[..]).unwrap();
1403
1404 let split1 = packet.split_at(2).unwrap();
1405 let (l, r) = split1.via_immutable();
1406 assert_eq!(l.length, 1);
1407 assert_eq!(r, &[4]);
1408
1409 let split2 = packet.split_at(2).unwrap();
1410 let (l, r) = split2.via_into_bytes();
1411 assert_eq!(l.length, 1);
1412 assert_eq!(r, &[4]);
1413 }
1414 #[test]
1415 #[allow(deprecated)]
1416 fn test_split_at_via_unaligned() {
1417 use crate::{Immutable, KnownLayout, Split, SplitAt, Unaligned};
1418
1419 fn via_unaligned<'a, T>(split: Split<&'a T>) -> (&'a T, &'a [T::Elem])
1420 where
1421 T: ?Sized + SplitAt + Unaligned,
1422 {
1423 split.via_unaligned()
1424 }
1425
1426 fn via_unaligned_mut<'a, T>(split: Split<&'a mut T>) -> (&'a mut T, &'a mut [T::Elem])
1427 where
1428 T: ?Sized + SplitAt + Unaligned,
1429 {
1430 split.via_unaligned()
1431 }
1432
1433 #[derive(KnownLayout, SplitAt, Immutable, Unaligned)]
1434 #[repr(C)]
1435 struct Packet<B: ?Sized> {
1436 prefix: [u8; 2],
1437 body: B,
1438 }
1439
1440 // Exercise generic callers using the original `T: Unaligned` bound.
1441 assert!(!Packet::<[[u8; 2]]>::LAYOUT.requires_dynamic_padding());
1442 let packet = Packet { prefix: [0, 1], body: [[2, 3], [4, 5], [6, 7]] };
1443 let packet: &Packet<[[u8; 2]]> = &packet;
1444
1445 let split = packet.split_at(2).unwrap();
1446 let (l, r) = via_unaligned(split);
1447 assert_eq!(l.body, [[2, 3], [4, 5]]);
1448 assert_eq!(r, &[[6, 7]]);
1449
1450 let mut packet = Packet { prefix: [0, 1], body: [[2, 3], [4, 5], [6, 7]] };
1451 {
1452 let packet: &mut Packet<[[u8; 2]]> = &mut packet;
1453 let split = packet.split_at_mut(2).unwrap();
1454 let (l, r) = via_unaligned_mut(split);
1455 l.body[0] = [8, 9];
1456 r[0] = [10, 11];
1457 }
1458 assert_eq!(packet.body, [[8, 9], [4, 5], [10, 11]]);
1459 }
1460
1461 #[test]
1462 fn test_split_at_via_no_dynamic_padding() {
1463 use core::cell::Cell;
1464
1465 use crate::SplitAt;
1466
1467 // `u16` does not implement `Unaligned`, but `[u16]` never requires
1468 // dynamic trailing padding.
1469 let words = [1u16, 2, 3, 4];
1470 let split = SplitAt::split_at(&words[..], 2).unwrap();
1471 let (left, right) = split.via_no_dynamic_padding();
1472 assert_eq!(left, [1, 2]);
1473 assert_eq!(right, [3, 4]);
1474
1475 let mut words = [1u16, 2, 3, 4];
1476 let split = SplitAt::split_at_mut(&mut words[..], 2).unwrap();
1477 let (left, right) = split.via_no_dynamic_padding();
1478 left[0] = 5;
1479 right[0] = 6;
1480 assert_eq!(words, [5, 2, 6, 4]);
1481
1482 // Exercise the safety-sensitive shared route with interior mutation.
1483 let cells = [Cell::new(1u16), Cell::new(2), Cell::new(3)];
1484 let split = SplitAt::split_at(&cells[..], 2).unwrap();
1485 let (left, right) = split.via_no_dynamic_padding();
1486 left[0].set(4);
1487 right[0].set(5);
1488 assert_eq!([cells[0].get(), cells[1].get(), cells[2].get()], [4, 2, 5]);
1489 }
1490}