1use core::mem;
2
3/// Copy the bytes of `val` to `ptr`, then advance pointer to just after the
4/// newly-copied bytes.
5pub unsafe fn ptr_write_unaligned_and_add<T>(ptr: &mut *mut u8, val: T) {
6 ptr.cast::<T>().write_unaligned(val);
7 *ptr = ptr.add(count:mem::size_of::<T>());
8}
9
10/// Convert from a `u32` to a `usize`. Panic if the input does fit. On typical
11/// targets `usize` is at least as big as `u32`, so this should never panic
12/// except on unusual targets.
13///
14/// Comparison to alternatives:
15/// * `val as usize` doesn't check that `val` actually fits in a `usize`.
16/// * `usize::try_from(val).unwrap()` doesn't work in a const context.
17pub const fn usize_from_u32(val: u32) -> usize {
18 // This is essentially the same as `usize::try_from(val).unwrap()`, but
19 // works in a `const` context on stable.
20 if mem::size_of::<usize>() < mem::size_of::<u32>() && val < (usize::MAX as u32) {
21 panic!("value does not fit in a usize");
22 } else {
23 val as usize
24 }
25}
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30
31 #[test]
32 fn test_usize_from_u32() {
33 assert_eq!(usize_from_u32(0), 0usize);
34 assert_eq!(usize_from_u32(u32::MAX), 4294967295usize);
35 }
36}
37