From dd1e281c85cb047c6a4a05a4af0314e064cba088 Mon Sep 17 00:00:00 2001 From: 5225225 <5225225@mailbox.org> Date: Sun, 19 Dec 2021 20:34:52 +0000 Subject: Wrap unsafe functions to catch errors in debug Closes https://github.com/iximeow/yaxpeax-x86/issues/16 --- src/safer_unchecked.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/safer_unchecked.rs (limited to 'src/safer_unchecked.rs') diff --git a/src/safer_unchecked.rs b/src/safer_unchecked.rs new file mode 100644 index 0000000..afd0355 --- /dev/null +++ b/src/safer_unchecked.rs @@ -0,0 +1,28 @@ +use core::slice::SliceIndex; + +pub trait GetSaferUnchecked { + unsafe fn get_kinda_unchecked(&self, index: I) -> &>::Output + where + I: SliceIndex<[T]>; +} + +impl GetSaferUnchecked for [T] { + unsafe fn get_kinda_unchecked(&self, index: I) -> &>::Output + where + I: SliceIndex<[T]>, + { + if cfg!(debug_assertions) { + &self[index] + } else { + self.get_unchecked(index) + } + } +} + +pub unsafe fn unreachable_kinda_unchecked() -> ! { + if cfg!(debug_assertions) { + panic!("UB: Unreachable unchecked was executed") + } else { + core::hint::unreachable_unchecked() + } +} -- cgit v1.1