1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
use core::{marker::PhantomData, mem};
use const_panic::concat_panic;
use crate::{
valid_generic_markers::{ValidAlignment, ValidLayout, ValidSize},
Aligned,
};
/// Size in bytes.
///
/// This is the type to use where [`ValidSize`] is required.
///
/// [`Size`] also has an associated [`Buffer`][ValidSize::Buffer] with a length
/// equal to the const generic. The buffer is of type `[MaybeUninit<u8>; N]`.
///
/// # Examples
/// ```
/// use std::mem::size_of;
/// use dungeon_cell::{Size, valid_generic_markers::ValidSize};
///
/// struct Test<S: ValidSize> {
/// buffer: S::Buffer,
/// }
///
/// assert_eq!(size_of::<Test::<Size<6>>>(), 6);
/// assert_eq!(size_of::<Test::<Size<14>>>(), 14);
/// ```
pub struct Size<const N: usize> {
_private: (),
}
/// Combination of size and alignment.
///
/// This is the type to use where [`ValidLayout`] is required.
///
/// Unlike the [`std::alloc::Layout`], this type is for layouts known at compile time.
///
/// The layout given to a dungeon type determines the types it can store. When
/// choosing a layout its important to make the size and alignment as small
/// as possible because dungeon types always take up the amount of memory their
/// [`Layout`] describes, not the amount of memory their actively stored type needs.
/// To find the smallest layout for a given set of types the
/// [`layout_for!()`][crate::layout_for] macro can be used.
///
/// # Examples
///
/// ```
/// use dungeon_cell::{Layout, Size, Alignment};
///
/// type Test = Layout<Size<4>, Alignment<2>>;
///
/// assert_eq!(Test::size(), 4);
/// assert_eq!(Test::alignment(), 2);
/// ```
pub struct Layout<S: ValidSize, A: ValidAlignment> {
_phantom: PhantomData<(S, A)>,
}
/// Marker for if a [`Layout`] can store a given `T`.
///
/// This trait is always implemented and is a no-op on stable.
/// The [`Self::assert_can_store()`] method must be called to actually
/// assert if the [`Layout`] can store the type.
///
/// On nightly, bounding with this trait will cause the compiler error created by
/// [`Self::assert_can_store()`] even when using `cargo check`.
/// This requires the use of const generic expressions
/// and therefore may cause issues on some nightly rustc versions.
/// The use of const generic expressions can be disabled by having a
/// `DUNGEON_CELL_NO_GENERIC_CONST_EXPRS` environment variable while building.
///
/// In the future, this trait may actually provide a type level bound of what
/// [`dungeon_cell`][crate] types can store.
pub trait CanStore<T>: ValidLayout {
/// Assert that type `T` can be stored in this layout.
///
/// A `T` can be stored if it's size is equal to or smaller than the layout size,
/// and the alignment is equal to or smaller than the layout alignment.
///
/// Unsafe code can use the above fact if this function returns.
///
/// By default, this function will cause a compiler error if the assert fails.
/// The assertion is only triggered during an actual build. Therefore, `cargo check`
/// won't show them.
/// The resulting compiler error doesn't have any information on where the
/// failing assert is located. Because of this limitation, the environment variable
/// `DUNGEON_CELL_RUNTIME_CHECKS` can be enabled (it can have any value) while
/// building [`dungeon_cell`][crate] to have this function generate runtime
/// panics with a backtrace instead.
///
/// # Examples
///
/// ## Passing Assertions
/// ```
/// use dungeon_cell::{Layout, layout_for, CanStore};
///
/// type LayoutI32 = layout_for!(i32);
///
/// <LayoutI32 as CanStore<u8>>::assert_can_store();
/// <LayoutI32 as CanStore<u16>>::assert_can_store();
/// <LayoutI32 as CanStore<i32>>::assert_can_store();
/// ```
///
/// ## Failing Assertion
/// ```compile_fail
/// use dungeon_cell::{Layout, layout_for, CanStore};
///
/// <layout_for!(i32) as CanStore<String>>::assert_can_store();
/// ```
///
/// Example of generated compile error for the above example:
/// ```txt
/// error[E0080]: evaluation of `dungeon_cell::can_store::CanStore::<std::string::String, dungeon_cell::Layout<dungeon_cell::Size<4>, dungeon_cell::Alignment<4>>>::ASSERT` failed
/// --> dungeon-cell/src/can_store.rs:372:9
/// |
/// 372 | do_assert::<T, L>(type_name, true);
/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
///
/// std::string::String with a size of 24 bytes, does not fit in a 4 byte buffer.
///
/// This error happens after monomorphization so the location of the code that
/// caused this to happen is not known. Add the `DUNGEON_CELL_RUNTIME_CHECKS`
/// environment variable when compiling to enable runtime panics with a backtrace.
///
/// ', dungeon-cell/src/can_store.rs:372:9
/// ```
#[inline]
#[track_caller]
fn assert_can_store() {
#[cfg(not(use_runtime_checks))]
{
// Force rustc to resolve the constant after monomorphization.
//
// This bypasses the restriction of const generics being used
// in const expressions, but results in rustc not knowing what
// code caused the error.
#[allow(clippy::let_unit_value)]
let _ = CanStoreCheck::<T, Self>::ASSERT;
}
#[cfg(use_runtime_checks)]
{
// Do the check `CanStore::ASSERT` does but with better panic messages.
//
// These checks should get optimized out by llvm because they are known
// at compile time.
let type_name = core::any::type_name::<T>();
do_assert::<T, Self>(type_name, false);
}
}
}
/// Opaque type with layout given by a [`Layout`].
pub type OpaqueType<L> = Aligned<
<<L as ValidLayout>::Size as ValidSize>::Buffer,
<L as ValidLayout>::Alignment,
>;
#[cfg(not(has_feature_generic_const_exprs))]
impl<T, S: ValidSize, A: ValidAlignment> CanStore<T> for Layout<S, A> {}
#[cfg(has_feature_generic_const_exprs)]
mod gce_check {
// Use generic const expressions to cause post monomorphization error
// earlier. In the future may be used to actually bound using generic
// const expressions if they ever get the ability to.
use super::*;
use crate::valid_generic_markers::LayoutFrom;
struct Check<const N: u8>;
const fn do_check<T, L: ValidLayout>() -> u8 {
// Disable when the user asks for runtime checks.
#[cfg(not(use_runtime_checks))]
LayoutFrom::<L>::const_assert_can_store::<T>();
0
}
impl<T, S: ValidSize, A: ValidAlignment> CanStore<T> for Layout<S, A> where
Check<{ do_check::<T, Self>() }>: Sized
{
}
}
impl<S: ValidSize, A: ValidAlignment> Layout<S, A> {
/// Check if this layout perfectly matches the layout for `T`.
///
/// # Examples
/// ```
/// use dungeon_cell::{Layout, Size, Alignment};
///
/// type Test = Layout<Size<4>, Alignment<4>>;
///
/// assert!(Test::is_layout_of::<i32>());
/// assert!(!Test::is_layout_of::<i16>());
/// ```
pub const fn is_layout_of<T>() -> bool {
(mem::size_of::<T>() == S::VALUE) && (mem::align_of::<T>() == A::VALUE)
}
/// Return the size of the layout.
///
/// # Examples
/// ```
/// use dungeon_cell::layout_for;
///
/// assert_eq!(<layout_for!(String)>::size(), 24);
/// ```
pub const fn size() -> usize {
S::VALUE
}
/// Return the alignment requirement of the layout.
///
/// # Examples
/// ```
/// use dungeon_cell::layout_for;
///
/// assert_eq!(<layout_for!(String)>::alignment(), 8);
/// ```
pub const fn alignment() -> usize {
A::VALUE
}
/// Create a [`std::alloc::Layout`] with the size and alignment of this layout.
///
/// # Examples
/// ```
/// use dungeon_cell::layout_for;
///
/// let l: std::alloc::Layout =
/// <layout_for!(String)>::to_std_layout().unwrap();
///
/// assert_eq!(l.size(), 24);
/// assert_eq!(l.align(), 8);
/// ```
#[cfg(feature = "alloc")]
pub const fn to_std_layout(
) -> Result<crate::alloc::Layout, crate::alloc::LayoutError> {
crate::alloc::Layout::from_size_align(S::VALUE, A::VALUE)
}
/// Check if this layout would allow a `T` to be stored.
///
/// # Examples
/// ```
/// use dungeon_cell::layout_for;
///
/// type LayoutI32 = layout_for!(i32);
///
/// assert!(LayoutI32::can_store::<u8>());
/// assert!(LayoutI32::can_store::<u16>());
/// assert!(LayoutI32::can_store::<i32>());
/// assert!(!LayoutI32::can_store::<String>());
/// ```
pub const fn can_store<T>() -> bool {
(mem::size_of::<T>() <= S::VALUE) && (mem::align_of::<T>() <= A::VALUE)
}
/// Const form of [`CanStore::assert_can_store()`].
///
/// Use [`CanStore::assert_can_store()`] if possible because it can provide better
/// diagnostic messages.
#[inline]
#[track_caller]
pub const fn const_assert_can_store<T>() {
#[cfg(not(use_runtime_checks))]
{
// Force rustc to resolve the constant after monomorphization.
//
// This bypasses the restriction of const generics being used
// in const expressions, but results in rustc not knowing what
// code caused the error.
#[allow(clippy::let_unit_value)]
let _ = CanStoreCheck::<T, Self>::ASSERT;
}
#[cfg(use_runtime_checks)]
{
// Do the check `CanStore::ASSERT` does but with better panic messages.
//
// These checks should get optimized out by llvm because they are known
// at compile time.
#[cfg(any(has_const_type_name, has_feature_const_type_name))]
let type_name = core::any::type_name::<T>();
#[cfg(not(any(has_const_type_name, has_feature_const_type_name)))]
let type_name = "T (rebuild with nightly rustc to print type name)";
do_assert::<T, Self>(type_name, false);
}
}
}
/// Calculate the [`Layout`] needed to store a set of types.
///
/// This macro expects input of the form `layout_for!(Type1, Type2, Type3)`.
/// The created [`Layout`] type will have a size equal to the maximum size
/// of the given types, and will have an alignment equal to the maximum alignment
/// of the given types. If you want the layout for the combination of types `Type1`,
/// `Type2`, `Type3` as one value then use `layout_for!((Type1, Type2, Type3))`.
///
/// # Examples
/// ```
/// use dungeon_cell::layout_for;
///
/// // sizes
///
/// assert_eq!(<layout_for!()>::size(), 0);
/// assert_eq!(<layout_for!(())>::size(), 0);
///
/// assert_eq!(<layout_for!(u8)>::size(), 1);
/// assert_eq!(<layout_for!(u8, i8)>::size(), 1);
///
/// assert_eq!(<layout_for!(u32)>::size(), 4);
/// assert_eq!(<layout_for!(u32, i32, u8, i16, ())>::size(), 4);
///
/// assert_eq!(<layout_for!(u32, u8, String, &'static str, ())>::size(), 24);
///
/// assert_eq!(<layout_for!([u8; 100], [i32; 5], String)>::size(), 100);
///
///
/// // alignments
///
/// assert_eq!(<layout_for!()>::alignment(), 1);
/// assert_eq!(<layout_for!(u8)>::alignment(), 1);
///
/// assert_eq!(<layout_for!(i32)>::alignment(), 4);
///
/// assert_eq!(<layout_for!([u8; 100], [i32; 5], String)>::alignment(), 8);
/// ```
///
/// # Example Expansion
/// ```
/// # use dungeon_cell::layout_for;
/// # type __ =
/// layout_for!(i32, u8)
/// # ;
/// ```
/// expands to
/// ```
/// # use dungeon_cell::{Layout, Size, Alignment};
/// # type __ =
/// ::dungeon_cell::Layout<
/// ::dungeon_cell::Size<
/// {
/// let mut max = 0;
///
/// let size = ::core::mem::size_of::<i32>();
/// if size > max {
/// max = size;
/// }
///
/// let size = ::core::mem::size_of::<u8>();
/// if size > max {
/// max = size;
/// }
///
/// max
/// },
/// >,
/// ::dungeon_cell::Alignment<
/// {
/// let mut max = 1;
///
/// let align = ::core::mem::align_of::<i32>();
/// if align > max {
/// max = align;
/// }
///
/// let align = ::core::mem::align_of::<u8>();
/// if align > max {
/// max = align;
/// }
///
/// max
/// },
/// >,
/// >
/// # ;
/// ```
#[macro_export]
macro_rules! layout_for {
($($type:ty),* $(,)?) => {
$crate::Layout::<$crate::Size<{
let mut max = 0;
$(
let size = ::core::mem::size_of::<$type>();
if size > max {
max = size;
}
)*
max
}>, $crate::Alignment<{
let mut max = 1;
$(
let align = ::core::mem::align_of::<$type>();
if align > max {
max = align;
}
)*
max
}>>
};
($($t:tt)*) => {
compile_error!("Expected input of the form `layout_for!(Type1, Type2, Type3)`")
}
}
/// Generate a compile time size check panic.
#[track_caller]
#[inline]
const fn size_panic(
name: &str,
size: usize,
buffer_size: usize,
show_extra: bool,
) {
if show_extra {
concat_panic!(
"\n\n",
display: name,
" with a size of ",
size,
" bytes, does not fit in a ",
buffer_size,
" byte buffer.\n\nThis error happens after monomorphization so \
the location of the code that caused this to happen is not known. \
Add the `DUNGEON_CELL_RUNTIME_CHECKS` environment variable \
when compiling to enable runtime panics with a backtrace.\n\n"
);
} else {
concat_panic!(
display: name,
" with a size of ",
size,
" bytes, does not fit in a ",
buffer_size,
" byte buffer."
);
}
}
/// Generate a compile time alignment check panic.
#[track_caller]
#[inline]
const fn align_panic(
name: &str,
align: usize,
buffer_align: usize,
show_extra: bool,
) {
if show_extra {
concat_panic!(
"\n\n",
display: name,
" with a alignment of ",
align,
" bytes, has a larger alignment than a ",
buffer_align,
" byte aligned buffer can store.\n\nThis error happens after \
monomorphization so \
the location of the code that caused this to happen is not known. \
Add the `DUNGEON_CELL_RUNTIME_CHECKS` environment variable \
when compiling to enable runtime panics with a backtrace.\n\n"
);
} else {
concat_panic!(
display: name,
" with a alignment of ",
align,
" bytes, has a larger alignment than a ",
buffer_align,
" byte aligned buffer can store."
);
}
}
/// Work around to do compile time assert on const generics.
struct CanStoreCheck<T, L>(PhantomData<(T, L)>);
impl<T, L: ValidLayout> CanStoreCheck<T, L> {
/// If type 'T` can't be stored in a buffer of length `S` and
/// alignment `A` then this const will fail to resolve.
///
/// This happens after monomorphization so the error message rustc
/// gives is very unhelpful in telling where in the user code the
/// issue is.
const ASSERT: () = {
#[cfg(any(has_const_type_name, has_feature_const_type_name))]
let type_name = core::any::type_name::<T>();
#[cfg(not(any(has_const_type_name, has_feature_const_type_name)))]
let type_name = "T (rebuild with nightly rustc to print type name)";
do_assert::<T, L>(type_name, true);
};
}
/// Perform the can store assert checks.
///
/// Will panic if the assert fails.
#[track_caller]
#[inline]
const fn do_assert<T, L: ValidLayout>(type_name: &str, is_compile_time: bool) {
let buffer_size = L::Size::VALUE;
let type_size = core::mem::size_of::<T>();
if type_size > buffer_size {
size_panic(type_name, type_size, buffer_size, is_compile_time);
}
let type_alignment = core::mem::align_of::<T>();
let alignment = L::Alignment::VALUE;
if type_alignment > alignment {
align_panic(type_name, type_alignment, alignment, is_compile_time);
}
}