#const-fn #transmute #casting

无std constmuck

bytemuck函数的const等效函数

5个版本 (2个稳定版)

1.1.0 2024年1月4日
1.0.0 2023年9月2日
0.3.0 2021年10月26日
0.2.0 2021年10月9日
0.0.0 2021年9月10日

#47无标准库

每月33次下载

Zlib 许可证

56KB
675

Rust crates-io api-docs

许多bytemuck函数的const等效函数。

constmuck使用bytemuck's traits,任何实现了这些特性的类型都可以与该crate中的相关函数一起使用。

因为*_alt函数是const fn,它们无法检查引用参数的地址。这与它们的bytemuck等效函数不同,后者使用地址来确定对齐方式。

示例

这些示例使用bytemuck的derive来展示用户不需要编写unsafe来使用此crate,并且使用konst crate来使编写const函数更容易。

连续

此示例演示了从其表示形式构建枚举。


use constmuck::Contiguous;

use konst::{array, try_opt};

fn main() {
    const COLORS: Option<[Color; 5]> = Color::from_array([3, 4, 1, 0, 2]);
    assert_eq!(
        COLORS,
        Some([Color::White, Color::Black, Color::Blue, Color::Red, Color::Green]),
    );

    const NONE_COLORS: Option<[Color; 4]> = Color::from_array([1, 2, 3, 5]);
    assert_eq!(NONE_COLORS, None);
}

#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Contiguous, Copy, Clone)]
pub enum Color {
    Red = 0,
    Blue,
    Green,
    White,
    Black,
}

impl Color {
    pub const fn from_int(n: u8) -> Option<Self> {
        constmuck::contiguous::from_integer(n)
    }
    pub const fn from_array<const N: usize>(input: [u8; N]) -> Option<[Self; N]> {
        // `try_opt` returns from `from_array` on `None`,
        // because `konst::array::map` allows the passed-in expression
        // to return from the surrounding named function.
        Some(array::map!(input, |n| try_opt!(Self::from_int(n))))
    }
}


包装器

此示例演示了一个包装类型[T]的类型,该类型通过引用构建。


use constmuck::TransparentWrapper;

fn main() {
    const SLICE: &[u32] = &[3, 5, 8, 13, 21];
    const WRAPPER: &SliceWrapper<u32> = SliceWrapper::new(SLICE);

    const SUM: u64 = WRAPPER.sum();
    assert_eq!(SUM, 50);

    const FIRST_EVEN: Option<(usize, u32)> = WRAPPER.find_first_even();
    assert_eq!(FIRST_EVEN, Some((2, 8)));
}

#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, TransparentWrapper)]
pub struct SliceWrapper<T>(pub [T]);

impl<T> SliceWrapper<T> {
    // Using `constmuck` allows safely defining this function as a `const fn`
    pub const fn new(reff: &[T]) -> &Self {
        constmuck::wrapper::wrap_ref!(reff)
    }
}

impl SliceWrapper<u32> {
    pub const fn sum(&self) -> u64 {
        konst::iter::eval!(&self.0,copied(),fold(0, |l, r| l + r as u64))
    }
    pub const fn find_first_even(&self) -> Option<(usize, u32)> {
        konst::iter::eval!(&self.0,copied(),enumerate(),find(|(i, n)| *n % 2 == 0))
    }
}


额外检查

默认禁用的"debug_checks" crate功能(在constmuck函数中启用额外断言)可以在某些情况下使bytemuck traits的未定义行为(Undefined Behavior)引发panic。

特性

这些是此crate的特性

  • "derive"(默认禁用):启用bytemuck"derive"特性并重新导出其derive。

  • "debug_checks"(默认禁用):启用额外的安全检查以检测一些未定义行为。

  • "rust_1_75" (默认禁用): 允许 constmuck::zeroed 构造任何大小的类型。

  • "rust_latest_stable" (默认禁用): 启用所有 "rust_1_*" 功能。

无标准支持

constmuck#![no_std],它可以在Rust可以使用的任何地方使用。

最低支持的Rust版本

constmuck 需要 Rust 1.65.0。

您可以使用 "rust_latest_stable" 包功能来获取所有需要稳定Rust版本(1.65.0之后)的项目和功能。

依赖关系

~750KB
~12K SLoC