Trait dungeon_cell::CanStore
source · pub trait CanStore<T>: ValidLayout {
// Provided method
fn assert_can_store() { ... }
}
Expand description
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
types can store.
Provided Methods§
sourcefn assert_can_store()
fn assert_can_store()
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
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
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:
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