aligned_bytes/
lib.rs

1#![deny(missing_debug_implementations)]
2#![deny(missing_docs)]
3#![deny(clippy::all)]
4#![cfg_attr(not(feature = "std"), no_std)]
5#![cfg_attr(feature = "unstable", feature(unsize, coerce_unsized))]
6
7//! A continuous fixed-length byte array with a specified alignment.
8//!
9//! # Example
10//! ```
11//! use aligned_bytes::AlignedBytes;
12//! let mut bytes = AlignedBytes::new_zeroed(1024, 8);
13//! let buf: &mut [u8] = &mut *bytes;
14//! ```
15
16extern crate alloc;
17
18mod boxed;
19mod bytes;
20pub mod stack;
21
22pub use self::boxed::AlignedBox;
23pub use self::bytes::AlignedBytes;
24
25use alloc::alloc::{handle_alloc_error, Layout};
26
27unsafe fn aligned_alloc(alloc: unsafe fn(Layout) -> *mut u8, size: usize, align: usize) -> *mut u8 {
28    let layout = match Layout::from_size_align(size, align) {
29        Ok(layout) => layout,
30        Err(_) => panic!("Invalid layout: size = {}, align = {}", size, align),
31    };
32
33    let ptr = alloc(layout);
34    if ptr.is_null() {
35        handle_alloc_error(layout);
36    }
37    debug_assert!(
38        (ptr as usize) % align == 0,
39        "pointer = {:p} is not a multiple of alignment = {}",
40        ptr,
41        align
42    );
43    ptr
44}