const_util/lib.rs
1#![cfg_attr(not(test), no_std)]
2#![allow(rustdoc::redundant_explicit_links)]
3#![warn(clippy::undocumented_unsafe_blocks)]
4
5//! Provides stable const implementations for some things missing from the standard library.
6//!
7//! Currently implemented are
8//! - Functions in [`result`](crate::result) to unwrap [`Result`](core::result::Result)s with generics or drop glue
9//! - Functions in the [`concat`](crate::concat) module to concat const strings and byte slices.
10//! - [`destruct_tuple`](crate::destruct_tuple) to destructure tuples with generic types or types with drop glue in them
11//! - [`nonnull_from`](crate::mem::nonnull_from) to create [`NonNull`](core::ptr::NonNull)s from mutable and regular references
12//! conveniently
13//! - [`man_drop_ref`](crate::mem::man_drop_ref)/[`man_drop_mut`](crate::mem::man_drop_mut) as a workaround for the lack of const
14//! [`Deref`](core::ops::Deref) implementations
15//! - Functions in [`slice`](crate::slice) to take subslices using ranges
16
17pub extern crate type_const;
18pub use type_const::{value_of, Const};
19
20pub mod concat;
21pub mod mem;
22pub mod result;
23pub mod slice;
24
25#[doc(hidden)]
26#[macro_export]
27macro_rules! __infer {
28 ($($_:tt)*) => {
29 _
30 };
31}
32
33/// Allows destructuring tuples in `const` contexts, regardless of items having drop glue.
34///
35/// This is mainly useful to allow generic functions to return tuples without being then stuck
36/// without a way to pull them back apart.
37///
38/// # Example
39/// ```
40/// use const_util::*;
41/// const fn pair_to_arr<T>(pair: (T, T)) -> [T; 2] {
42/// destruct_tuple! { a, b in pair }
43/// [a, b]
44/// }
45/// assert_eq!(
46/// pair_to_arr((String::from("ABC"), String::new())),
47/// ["ABC", ""],
48/// );
49/// ```
50#[macro_export]
51macro_rules! destruct_tuple {
52 ($($field:ident),* in $tup:expr) => {
53 let __tup: ($($crate::__infer!($field),)*) = $tup;
54 let __tup = $crate::__mac::core::mem::ManuallyDrop::new(__tup);
55 let ($($field),*) = $crate::mem::man_drop_ref(&__tup);
56 // SAFETY: The tuple is forgotten after this
57 $(let $field = unsafe { $crate::__mac::core::ptr::read($field) };)*
58 };
59}
60
61#[doc(hidden)]
62pub mod __mac {
63 pub use core;
64}