Coverage Report

Created: 2026-08-11 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bytemuck-1.25.2/src/lib.rs
Line
Count
Source
1
#![no_std]
2
#![warn(missing_docs)]
3
#![allow(unused_mut)]
4
#![allow(clippy::match_like_matches_macro)]
5
#![allow(clippy::uninlined_format_args)]
6
#![allow(clippy::result_unit_err)]
7
#![allow(clippy::type_complexity)]
8
#![allow(clippy::manual_is_multiple_of)]
9
#![cfg_attr(feature = "nightly_docs", feature(doc_cfg))]
10
#![cfg_attr(feature = "nightly_portable_simd", feature(portable_simd))]
11
#![cfg_attr(feature = "nightly_float", feature(f16, f128))]
12
13
//! This crate gives small utilities for casting between plain data types.
14
//!
15
//! ## Basics
16
//!
17
//! Data comes in five basic forms in Rust, so we have five basic casting
18
//! functions:
19
//!
20
//! * `T` uses [`cast`]
21
//! * `&T` uses [`cast_ref`]
22
//! * `&mut T` uses [`cast_mut`]
23
//! * `&[T]` uses [`cast_slice`]
24
//! * `&mut [T]` uses [`cast_slice_mut`]
25
//!
26
//! Depending on the function, the [`NoUninit`] and/or [`AnyBitPattern`] traits
27
//! are used to maintain memory safety.
28
//!
29
//! **Historical Note:** When the crate first started the [`Pod`] trait was used
30
//! instead, and so you may hear people refer to that, but it has the strongest
31
//! requirements and people eventually wanted the more fine-grained system, so
32
//! here we are. All types that impl `Pod` have a blanket impl to also support
33
//! `NoUninit` and `AnyBitPattern`. The traits unfortunately do not have a
34
//! perfectly clean hierarchy for semver reasons.
35
//!
36
//! ## Failures
37
//!
38
//! Some casts will never fail, and other casts might fail.
39
//!
40
//! * `cast::<u32, f32>` always works (and [`f32::from_bits`]).
41
//! * `cast_ref::<[u8; 4], u32>` might fail if the specific array reference
42
//!   given at runtime doesn't have alignment 4.
43
//!
44
//! In addition to the "normal" forms of each function, which will panic on
45
//! invalid input, there's also `try_` versions which will return a `Result`.
46
//!
47
//! If you would like to statically ensure that a cast will work at runtime you
48
//! can use the `must_cast` crate feature and the `must_` casting functions. A
49
//! "must cast" that can't be statically known to be valid will cause a
50
//! compilation error (and sometimes a very hard to read compilation error).
51
//!
52
//! ## Using Your Own Types
53
//!
54
//! All the functions listed above are guarded by the [`Pod`] trait, which is a
55
//! sub-trait of the [`Zeroable`] trait.
56
//!
57
//! If you enable the crate's `derive` feature then these traits can be derived
58
//! on your own types. The derive macros will perform the necessary checks on
59
//! your type declaration, and trigger an error if your type does not qualify.
60
//!
61
//! The derive macros might not cover all edge cases, and sometimes they will
62
//! error when actually everything is fine. As a last resort you can impl these
63
//! traits manually. However, these traits are `unsafe`, and you should
64
//! carefully read the requirements before using a manual implementation.
65
//!
66
//! ## Cargo Features
67
//!
68
//! The crate supports Rust 1.34 when no features are enabled, and so there's
69
//! cargo features for thing that you might consider "obvious".
70
//!
71
//! The cargo features **do not** promise any particular MSRV, and they may
72
//! increase their MSRV in new versions.
73
//!
74
//! * `derive`: Provide derive macros for the various traits.
75
//! * `extern_crate_alloc`: Provide utilities for `alloc` related types such as
76
//!   Box and Vec.
77
//! * `zeroable_maybe_uninit` and `zeroable_atomics`: Provide more [`Zeroable`]
78
//!   impls.
79
//! * `pod_saturating`: Provide more [`Pod`] and [`Zeroable`] impls.
80
//! * `wasm_simd` and `aarch64_simd`: Support more SIMD types.
81
//! * `min_const_generics`: Provides appropriate impls for arrays of all lengths
82
//!   instead of just for a select list of array lengths.
83
//! * `must_cast`: Provides the `must_` functions, which will compile error if
84
//!   the requested cast can't be statically verified.
85
//! * `const_zeroed`: Provides a const version of the `zeroed` function.
86
//!
87
//! ## Related Crates
88
//!
89
//! - [`pack1`](https://docs.rs/pack1), which contains `bytemuck`-compatible
90
//!   packed little-endian, big-endian and native-endian integer and floating
91
//!   point number types.
92
93
#[cfg(all(target_arch = "aarch64", feature = "aarch64_simd"))]
94
use core::arch::aarch64;
95
#[cfg(all(target_arch = "wasm32", feature = "wasm_simd"))]
96
use core::arch::wasm32;
97
#[cfg(target_arch = "x86")]
98
use core::arch::x86;
99
#[cfg(target_arch = "x86_64")]
100
use core::arch::x86_64;
101
//
102
use core::{
103
  marker::*,
104
  mem::{align_of, size_of},
105
  num::*,
106
  ptr::*,
107
};
108
109
// Used from macros to ensure we aren't using some locally defined name and
110
// actually are referencing libcore. This also would allow pre-2018 edition
111
// crates to use our macros, but I'm not sure how important that is.
112
#[doc(hidden)]
113
pub use ::core as __core;
114
115
#[cfg(not(feature = "min_const_generics"))]
116
macro_rules! impl_unsafe_marker_for_array {
117
  ( $marker:ident , $( $n:expr ),* ) => {
118
    $(unsafe impl<T> $marker for [T; $n] where T: $marker {})*
119
  }
120
}
121
122
/// A macro to transmute between two types without requiring knowing size
123
/// statically.
124
macro_rules! transmute {
125
  ($val:expr) => {
126
    ::core::mem::transmute_copy(&::core::mem::ManuallyDrop::new($val))
127
  };
128
  // This arm is for use in const contexts, where the borrow required to use
129
  // transmute_copy poses an issue since the compiler hedges that the type
130
  // being borrowed could have interior mutability.
131
  ($srcty:ty; $dstty:ty; $val:expr) => {{
132
    #[repr(C)]
133
    union Transmute<A, B> {
134
      src: ::core::mem::ManuallyDrop<A>,
135
      dst: ::core::mem::ManuallyDrop<B>,
136
    }
137
    ::core::mem::ManuallyDrop::into_inner(
138
      Transmute::<$srcty, $dstty> { src: ::core::mem::ManuallyDrop::new($val) }
139
        .dst,
140
    )
141
  }};
142
}
143
144
/// A macro to implement marker traits for various simd types.
145
/// #[allow(unused)] because the impls are only compiled on relevant platforms
146
/// with relevant cargo features enabled.
147
#[allow(unused)]
148
macro_rules! impl_unsafe_marker_for_simd {
149
  ($(#[cfg($cfg_predicate:meta)])? unsafe impl $trait:ident for $platform:ident :: {}) => {};
150
  ($(#[cfg($cfg_predicate:meta)])? unsafe impl $trait:ident for $platform:ident :: { $first_type:ident $(, $types:ident)* $(,)? }) => {
151
    $( #[cfg($cfg_predicate)] )?
152
    $( #[cfg_attr(feature = "nightly_docs", doc(cfg($cfg_predicate)))] )?
153
    unsafe impl $trait for $platform::$first_type {}
154
    $( #[cfg($cfg_predicate)] )? // To prevent recursion errors if nothing is going to be expanded anyway.
155
    impl_unsafe_marker_for_simd!($( #[cfg($cfg_predicate)] )? unsafe impl $trait for $platform::{ $( $types ),* });
156
  };
157
}
158
159
/// A macro for conditionally const-ifying a function.
160
/// #[allow(unused)] because currently it is only used with the `must_cast` feature.
161
#[allow(unused)]
162
macro_rules! maybe_const_fn {
163
  (
164
      #[cfg($cfg_predicate:meta)]
165
      $(#[$attr:meta])*
166
      $vis:vis $(unsafe $($unsafe:lifetime)?)? fn $name:ident $($rest:tt)*
167
  ) => {
168
      #[cfg($cfg_predicate)]
169
      $(#[$attr])*
170
      $vis const $(unsafe $($unsafe)?)? fn $name $($rest)*
171
172
      #[cfg(not($cfg_predicate))]
173
      $(#[$attr])*
174
      $vis $(unsafe $($unsafe)?)? fn $name $($rest)*
175
    };
176
}
177
178
#[cfg(feature = "extern_crate_std")]
179
extern crate std;
180
181
#[cfg(feature = "extern_crate_alloc")]
182
extern crate alloc;
183
#[cfg(feature = "extern_crate_alloc")]
184
#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_alloc")))]
185
pub mod allocation;
186
#[cfg(feature = "extern_crate_alloc")]
187
pub use allocation::*;
188
189
mod anybitpattern;
190
pub use anybitpattern::*;
191
192
pub mod checked;
193
pub use checked::CheckedBitPattern;
194
195
mod internal;
196
197
mod zeroable;
198
pub use zeroable::*;
199
mod zeroable_in_option;
200
pub use zeroable_in_option::*;
201
202
mod pod;
203
pub use pod::*;
204
mod pod_in_option;
205
pub use pod_in_option::*;
206
207
#[cfg(feature = "must_cast")]
208
mod must;
209
#[cfg(feature = "must_cast")]
210
#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "must_cast")))]
211
pub use must::*;
212
213
mod no_uninit;
214
pub use no_uninit::*;
215
216
mod contiguous;
217
pub use contiguous::*;
218
219
mod offset_of;
220
// ^ no import, the module only has a macro_rules, which are cursed and don't
221
// follow normal import/export rules.
222
223
mod transparent;
224
pub use transparent::*;
225
226
// This module is just an implementation detail for the derive macros. It needs
227
// to be public to be usable from the macros, but it shouldn't be considered
228
// part of bytemuck's public API.
229
#[cfg(feature = "derive")]
230
#[doc(hidden)]
231
pub mod derive;
232
233
#[cfg(feature = "derive")]
234
#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "derive")))]
235
pub use bytemuck_derive::{
236
  AnyBitPattern, ByteEq, ByteHash, CheckedBitPattern, Contiguous, NoUninit,
237
  Pod, TransparentWrapper, Zeroable,
238
};
239
240
/// The things that can go wrong when casting between [`Pod`] data forms.
241
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242
pub enum PodCastError {
243
  /// You tried to cast a reference into a reference to a type with a higher
244
  /// alignment requirement but the input reference wasn't aligned.
245
  TargetAlignmentGreaterAndInputNotAligned,
246
  /// If the element size of a slice changes, then the output slice changes
247
  /// length accordingly. If the output slice wouldn't be a whole number of
248
  /// elements, then the conversion fails.
249
  OutputSliceWouldHaveSlop,
250
  /// When casting an individual `T`, `&T`, or `&mut T` value the
251
  /// source size and destination size must be an exact match.
252
  SizeMismatch,
253
  /// For this type of cast the alignments must be exactly the same and they
254
  /// were not so now you're sad.
255
  ///
256
  /// This error is generated **only** by operations that cast allocated types
257
  /// (such as `Box` and `Vec`), because in that case the alignment must stay
258
  /// exact.
259
  AlignmentMismatch,
260
}
261
#[cfg(not(target_arch = "spirv"))]
262
impl core::fmt::Display for PodCastError {
263
0
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
264
0
    write!(f, "{:?}", self)
265
0
  }
266
}
267
#[cfg(feature = "extern_crate_std")]
268
#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_std")))]
269
impl std::error::Error for PodCastError {}
270
271
// Rust 1.81+
272
#[cfg(all(
273
  feature = "impl_core_error",
274
  not(feature = "extern_crate_std"),
275
  not(target_arch = "spirv")
276
))]
277
impl core::error::Error for PodCastError {}
278
279
/// Re-interprets `&T` as `&[u8]`.
280
///
281
/// Any ZST becomes an empty slice, and in that case the pointer value of that
282
/// empty slice might not match the pointer value of the input reference.
283
#[inline]
284
0
pub fn bytes_of<T: NoUninit>(t: &T) -> &[u8] {
285
0
  unsafe { internal::bytes_of(t) }
286
0
}
287
288
/// Re-interprets `&mut T` as `&mut [u8]`.
289
///
290
/// Any ZST becomes an empty slice, and in that case the pointer value of that
291
/// empty slice might not match the pointer value of the input reference.
292
#[inline]
293
0
pub fn bytes_of_mut<T: NoUninit + AnyBitPattern>(t: &mut T) -> &mut [u8] {
294
0
  unsafe { internal::bytes_of_mut(t) }
295
0
}
296
297
/// Re-interprets `&[u8]` as `&T`.
298
///
299
/// ## Panics
300
///
301
/// This is like [`try_from_bytes`] but will panic on error.
302
#[inline]
303
#[cfg_attr(feature = "track_caller", track_caller)]
304
0
pub fn from_bytes<T: AnyBitPattern>(s: &[u8]) -> &T {
305
0
  unsafe { internal::from_bytes(s) }
306
0
}
307
308
/// Re-interprets `&mut [u8]` as `&mut T`.
309
///
310
/// ## Panics
311
///
312
/// This is like [`try_from_bytes_mut`] but will panic on error.
313
#[inline]
314
#[cfg_attr(feature = "track_caller", track_caller)]
315
0
pub fn from_bytes_mut<T: NoUninit + AnyBitPattern>(s: &mut [u8]) -> &mut T {
316
0
  unsafe { internal::from_bytes_mut(s) }
317
0
}
318
319
/// Reads from the bytes as if they were a `T`.
320
///
321
/// Unlike [`from_bytes`], the slice doesn't need to respect alignment of `T`,
322
/// only sizes must match.
323
///
324
/// ## Failure
325
/// * If the `bytes` length is not equal to `size_of::<T>()`.
326
#[inline]
327
0
pub fn try_pod_read_unaligned<T: AnyBitPattern>(
328
0
  bytes: &[u8],
329
0
) -> Result<T, PodCastError> {
330
0
  unsafe { internal::try_pod_read_unaligned(bytes) }
331
0
}
332
333
/// Reads the slice into a `T` value.
334
///
335
/// Unlike [`from_bytes`], the slice doesn't need to respect alignment of `T`,
336
/// only sizes must match.
337
///
338
/// ## Panics
339
/// * This is like `try_pod_read_unaligned` but will panic on failure.
340
#[inline]
341
#[cfg_attr(feature = "track_caller", track_caller)]
342
0
pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
343
0
  unsafe { internal::pod_read_unaligned(bytes) }
344
0
}
345
346
/// Re-interprets `&[u8]` as `&T`.
347
///
348
/// ## Failure
349
///
350
/// * If the slice isn't aligned for the new type
351
/// * If the slice's length isn’t exactly the size of the new type
352
#[inline]
353
0
pub fn try_from_bytes<T: AnyBitPattern>(s: &[u8]) -> Result<&T, PodCastError> {
354
0
  unsafe { internal::try_from_bytes(s) }
355
0
}
356
357
/// Re-interprets `&mut [u8]` as `&mut T`.
358
///
359
/// ## Failure
360
///
361
/// * If the slice isn't aligned for the new type
362
/// * If the slice's length isn’t exactly the size of the new type
363
#[inline]
364
0
pub fn try_from_bytes_mut<T: NoUninit + AnyBitPattern>(
365
0
  s: &mut [u8],
366
0
) -> Result<&mut T, PodCastError> {
367
0
  unsafe { internal::try_from_bytes_mut(s) }
368
0
}
369
370
/// Cast `A` into `B`
371
///
372
/// ## Panics
373
///
374
/// * This is like [`try_cast`], but will panic on a size mismatch.
375
#[inline]
376
#[cfg_attr(feature = "track_caller", track_caller)]
377
0
pub fn cast<A: NoUninit, B: AnyBitPattern>(a: A) -> B {
378
0
  unsafe { internal::cast(a) }
379
0
}
380
381
/// Cast `&mut A` into `&mut B`.
382
///
383
/// ## Panics
384
///
385
/// This is [`try_cast_mut`] but will panic on error.
386
#[inline]
387
#[cfg_attr(feature = "track_caller", track_caller)]
388
0
pub fn cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
389
0
  a: &mut A,
390
0
) -> &mut B {
391
0
  unsafe { internal::cast_mut(a) }
392
0
}
393
394
/// Cast `&A` into `&B`.
395
///
396
/// ## Panics
397
///
398
/// This is [`try_cast_ref`] but will panic on error.
399
#[inline]
400
#[cfg_attr(feature = "track_caller", track_caller)]
401
0
pub fn cast_ref<A: NoUninit, B: AnyBitPattern>(a: &A) -> &B {
402
0
  unsafe { internal::cast_ref(a) }
403
0
}
404
405
/// Cast `&[A]` into `&[B]`.
406
///
407
/// ## Panics
408
///
409
/// This is [`try_cast_slice`] but will panic on error.
410
#[inline]
411
#[cfg_attr(feature = "track_caller", track_caller)]
412
230M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
230M
  unsafe { internal::cast_slice(a) }
414
230M
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, i8>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::offset::Nullable<font_types::offset::Offset16>>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::offset::Nullable<font_types::offset::Offset32>>>
bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::tag::Tag>>
Line
Count
Source
412
12.2k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
12.2k
  unsafe { internal::cast_slice(a) }
414
12.2k
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::fixed::Fixed>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::fixed::F2Dot14>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::offset::Offset16>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::offset::Offset24>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::offset::Offset32>>
bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::uint24::Uint24>>
Line
Count
Source
412
5.31k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
5.31k
  unsafe { internal::cast_slice(a) }
414
5.31k
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::name_id::NameId>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<font_types::glyph_id::GlyphId16>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<read_fonts::tables::cpal::PaletteType>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, font_types::raw::BigEndian<i32>>
bytemuck::cast_slice::<u8, font_types::raw::BigEndian<u32>>
Line
Count
Source
412
2.06M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
2.06M
  unsafe { internal::cast_slice(a) }
414
2.06M
}
bytemuck::cast_slice::<u8, font_types::raw::BigEndian<i16>>
Line
Count
Source
412
46.0M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
46.0M
  unsafe { internal::cast_slice(a) }
414
46.0M
}
bytemuck::cast_slice::<u8, font_types::raw::BigEndian<u16>>
Line
Count
Source
412
104M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
104M
  unsafe { internal::cast_slice(a) }
414
104M
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::aat::LookupSingle<u32>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::aat::LookupSingle<u16>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::aat::LookupSegment2<u32>>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::aat::LookupSegment2<u16>>
bytemuck::cast_slice::<u8, read_fonts::TableRecord>
Line
Count
Source
412
86.4k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
86.4k
  unsafe { internal::cast_slice(a) }
414
86.4k
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::variations::RegionAxisCoordinates>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::aat::LookupSegment4>
bytemuck::cast_slice::<u8, read_fonts::tables::ift::DesignSpaceSegment>
Line
Count
Source
412
8.45k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
8.45k
  unsafe { internal::cast_slice(a) }
414
8.45k
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::svg::SVGDocumentRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::ankr::AnchorPoint>
bytemuck::cast_slice::<u8, read_fonts::tables::avar::AxisValueMap>
Line
Count
Source
412
10.2k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
10.2k
  unsafe { internal::cast_slice(a) }
414
10.2k
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::base::BaseScriptRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::base::FeatMinMaxRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::base::BaseLangSysRecord>
bytemuck::cast_slice::<u8, read_fonts::tables::cmap::UvsMapping>
Line
Count
Source
412
2.01M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
2.01M
  unsafe { internal::cast_slice(a) }
414
2.01M
}
bytemuck::cast_slice::<u8, read_fonts::tables::cmap::UnicodeRange>
Line
Count
Source
412
3.37M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
3.37M
  unsafe { internal::cast_slice(a) }
414
3.37M
}
bytemuck::cast_slice::<u8, read_fonts::tables::cmap::EncodingRecord>
Line
Count
Source
412
6.95k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
6.95k
  unsafe { internal::cast_slice(a) }
414
6.95k
}
bytemuck::cast_slice::<u8, read_fonts::tables::cmap::ConstantMapGroup>
Line
Count
Source
412
36.8M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
36.8M
  unsafe { internal::cast_slice(a) }
414
36.8M
}
bytemuck::cast_slice::<u8, read_fonts::tables::cmap::VariationSelector>
Line
Count
Source
412
29.2M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
29.2M
  unsafe { internal::cast_slice(a) }
414
29.2M
}
bytemuck::cast_slice::<u8, read_fonts::tables::cmap::SequentialMapGroup>
Line
Count
Source
412
6.17M
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
6.17M
  unsafe { internal::cast_slice(a) }
414
6.17M
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::colr::VarColorStop>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::colr::BaseGlyphPaint>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::colr::Clip>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::colr::Layer>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::colr::BaseGlyph>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::colr::ColorStop>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::cpal::ColorRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::dsig::SignatureRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::feat::FeatureName>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::feat::SettingName>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::fvar::VariationAxisRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::gasp::GaspRange>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::gpos::MarkRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::gpos::EntryExitRecord>
bytemuck::cast_slice::<u8, read_fonts::tables::hmtx::LongMetric>
Line
Count
Source
412
59
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
59
  unsafe { internal::cast_slice(a) }
414
59
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::kerx::Subtable0Pair>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::ltag::FTStringRange>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::meta::DataMapRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::morx::Feature>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::mvar::ValueRecord>
bytemuck::cast_slice::<u8, read_fonts::tables::name::NameRecord>
Line
Count
Source
412
460
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
460
  unsafe { internal::cast_slice(a) }
414
460
}
bytemuck::cast_slice::<u8, read_fonts::tables::name::LangTagRecord>
Line
Count
Source
412
14
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
14
  unsafe { internal::cast_slice(a) }
414
14
}
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::stat::AxisRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::stat::AxisValueRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::trak::TrackTableEntry>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::varc::SparseRegionAxisCoordinates>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::vorg::VertOriginYMetrics>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::bitmap::BitmapSize>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::bitmap::BdtComponent>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::bitmap::BigGlyphMetrics>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::bitmap::GlyphIdOffsetPair>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::bitmap::SmallGlyphMetrics>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::bitmap::IndexSubtableRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::RangeRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::ScriptRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::FeatureRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::LangSysRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::ClassRangeRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::SequenceLookupRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::FeatureVariationRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::tables::layout::FeatureTableSubstitutionRecord>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::ps::cff::v1::CharsetRange1>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::ps::cff::v1::CharsetRange2>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::ps::cff::v1::EncodingRange1>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::ps::cff::v1::FdSelectRange3>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::ps::cff::v1::FdSelectRange4>
Unexecuted instantiation: bytemuck::cast_slice::<u8, read_fonts::ps::cff::v1::EncodingSupplement>
bytemuck::cast_slice::<u8, u8>
Line
Count
Source
412
634k
pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413
634k
  unsafe { internal::cast_slice(a) }
414
634k
}
Unexecuted instantiation: bytemuck::cast_slice::<_, _>
415
416
/// Cast `&mut [A]` into `&mut [B]`.
417
///
418
/// ## Panics
419
///
420
/// This is [`try_cast_slice_mut`] but will panic on error.
421
#[inline]
422
#[cfg_attr(feature = "track_caller", track_caller)]
423
0
pub fn cast_slice_mut<
424
0
  A: NoUninit + AnyBitPattern,
425
0
  B: NoUninit + AnyBitPattern,
426
0
>(
427
0
  a: &mut [A],
428
0
) -> &mut [B] {
429
0
  unsafe { internal::cast_slice_mut(a) }
430
0
}
431
432
/// As [`align_to`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to),
433
/// but safe because of the [`Pod`] bound.
434
#[inline]
435
0
pub fn pod_align_to<T: NoUninit, U: AnyBitPattern>(
436
0
  vals: &[T],
437
0
) -> (&[T], &[U], &[T]) {
438
0
  unsafe { vals.align_to::<U>() }
439
0
}
440
441
/// As [`align_to_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to_mut),
442
/// but safe because of the [`Pod`] bound.
443
#[inline]
444
0
pub fn pod_align_to_mut<
445
0
  T: NoUninit + AnyBitPattern,
446
0
  U: NoUninit + AnyBitPattern,
447
0
>(
448
0
  vals: &mut [T],
449
0
) -> (&mut [T], &mut [U], &mut [T]) {
450
0
  unsafe { vals.align_to_mut::<U>() }
451
0
}
452
453
/// Try to cast `A` into `B`.
454
///
455
/// Note that for this particular type of cast, alignment isn't a factor. The
456
/// input value is semantically copied into the function and then returned to a
457
/// new memory location which will have whatever the required alignment of the
458
/// output type is.
459
///
460
/// ## Failure
461
///
462
/// * If the types don't have the same size this fails.
463
#[inline]
464
0
pub fn try_cast<A: NoUninit, B: AnyBitPattern>(
465
0
  a: A,
466
0
) -> Result<B, PodCastError> {
467
0
  unsafe { internal::try_cast(a) }
468
0
}
469
470
/// Try to convert a `&A` into `&B`.
471
///
472
/// ## Failure
473
///
474
/// * If the reference isn't aligned in the new type
475
/// * If the source type and target type aren't the same size.
476
#[inline]
477
0
pub fn try_cast_ref<A: NoUninit, B: AnyBitPattern>(
478
0
  a: &A,
479
0
) -> Result<&B, PodCastError> {
480
0
  unsafe { internal::try_cast_ref(a) }
481
0
}
482
483
/// Try to convert a `&mut A` into `&mut B`.
484
///
485
/// As [`try_cast_ref`], but `mut`.
486
#[inline]
487
0
pub fn try_cast_mut<
488
0
  A: NoUninit + AnyBitPattern,
489
0
  B: NoUninit + AnyBitPattern,
490
0
>(
491
0
  a: &mut A,
492
0
) -> Result<&mut B, PodCastError> {
493
0
  unsafe { internal::try_cast_mut(a) }
494
0
}
495
496
/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
497
///
498
/// * `input.as_ptr() as usize == output.as_ptr() as usize`
499
/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
500
///
501
/// ## Failure
502
///
503
/// * If the target type has a greater alignment requirement and the input slice
504
///   isn't aligned. **Note:** This rule applies even if the slice is empty!
505
/// * If the target element type is a different size from the current element
506
///   type, and the output slice wouldn't be a whole number of elements when
507
///   accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
508
///   that's a failure).
509
/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
510
///   and a non-ZST.
511
#[inline]
512
0
pub fn try_cast_slice<A: NoUninit, B: AnyBitPattern>(
513
0
  a: &[A],
514
0
) -> Result<&[B], PodCastError> {
515
0
  unsafe { internal::try_cast_slice(a) }
516
0
}
517
518
/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
519
/// length).
520
///
521
/// As [`try_cast_slice`], but `&mut`.
522
#[inline]
523
0
pub fn try_cast_slice_mut<
524
0
  A: NoUninit + AnyBitPattern,
525
0
  B: NoUninit + AnyBitPattern,
526
0
>(
527
0
  a: &mut [A],
528
0
) -> Result<&mut [B], PodCastError> {
529
0
  unsafe { internal::try_cast_slice_mut(a) }
530
0
}
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, font_types::point::Point<font_types::fixed::Fixed>>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, font_types::point::Point<font_types::fixed::F26Dot6>>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, font_types::point::Point<f32>>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, font_types::point::Point<i32>>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, read_fonts::tables::glyf::PointFlags>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, i32>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<u8, u16>
Unexecuted instantiation: bytemuck::try_cast_slice_mut::<_, _>
531
532
/// Fill all bytes of `target` with zeroes (see [`Zeroable`]).
533
///
534
/// This is similar to `*target = Zeroable::zeroed()`, but guarantees that any
535
/// padding bytes in `target` are zeroed as well.
536
///
537
/// See also [`fill_zeroes`], if you have a slice rather than a single value.
538
#[inline]
539
0
pub fn write_zeroes<T: Zeroable>(target: &mut T) {
540
  struct EnsureZeroWrite<T>(*mut T);
541
  impl<T> Drop for EnsureZeroWrite<T> {
542
    #[inline(always)]
543
0
    fn drop(&mut self) {
544
0
      unsafe {
545
0
        core::ptr::write_bytes(self.0, 0u8, 1);
546
0
      }
547
0
    }
548
  }
549
0
  unsafe {
550
0
    let guard = EnsureZeroWrite(target);
551
0
    core::ptr::drop_in_place(guard.0);
552
0
    drop(guard);
553
0
  }
554
0
}
555
556
/// Fill all bytes of `slice` with zeroes (see [`Zeroable`]).
557
///
558
/// This is similar to `slice.fill(Zeroable::zeroed())`, but guarantees that any
559
/// padding bytes in `slice` are zeroed as well.
560
///
561
/// See also [`write_zeroes`], which zeroes all bytes of a single value rather
562
/// than a slice.
563
#[inline]
564
0
pub fn fill_zeroes<T: Zeroable>(slice: &mut [T]) {
565
0
  if core::mem::needs_drop::<T>() {
566
0
    // If `T` needs to be dropped then we have to do this one item at a time, in
567
0
    // case one of the intermediate drops does a panic.
568
0
    slice.iter_mut().for_each(write_zeroes);
569
0
  } else {
570
    // Otherwise we can be really fast and just fill everything with zeros.
571
0
    let len = slice.len();
572
0
    unsafe { core::ptr::write_bytes(slice.as_mut_ptr(), 0u8, len) }
573
  }
574
0
}
575
576
/// Same as [`Zeroable::zeroed`], but as a `const fn` const.
577
#[cfg(feature = "const_zeroed")]
578
#[inline]
579
#[must_use]
580
pub const fn zeroed<T: Zeroable>() -> T {
581
  unsafe { core::mem::zeroed() }
582
}