slotmap/
util.rs

1use core::fmt::Debug;
2use core::hint::unreachable_unchecked;
3
4/// Internal stable replacement for !.
5#[derive(Debug)]
6pub enum Never {}
7
8/// Returns if a is an older version than b, taking into account wrapping of
9/// versions.
10pub fn is_older_version(a: u32, b: u32) -> bool {
11    let diff = a.wrapping_sub(b);
12    diff >= (1 << 31)
13}
14
15/// An unwrapper that checks on debug, doesn't check on release.
16/// UB if unwrapped on release mode when unwrap would panic.
17pub trait UnwrapUnchecked<T> {
18    // Extra underscore because unwrap_unchecked is planned to be added to the stdlib.
19    unsafe fn unwrap_unchecked_(self) -> T;
20}
21
22impl<T> UnwrapUnchecked<T> for Option<T> {
23    unsafe fn unwrap_unchecked_(self) -> T {
24        if cfg!(debug_assertions) {
25            self.unwrap()
26        } else {
27            match self {
28                Some(x) => x,
29                None => unreachable_unchecked(),
30            }
31        }
32    }
33}
34
35impl<T, E: Debug> UnwrapUnchecked<T> for Result<T, E> {
36    unsafe fn unwrap_unchecked_(self) -> T {
37        if cfg!(debug_assertions) {
38            self.unwrap()
39        } else {
40            match self {
41                Ok(x) => x,
42                Err(_) => unreachable_unchecked(),
43            }
44        }
45    }
46}