aboutsummaryrefslogtreecommitdiff
path: root/src/safer_unchecked.rs
diff options
context:
space:
mode:
author5225225 <5225225@mailbox.org>2021-12-19 20:34:52 +0000
committeriximeow <git@iximeow.net>2022-01-02 14:40:07 -0800
commitdd1e281c85cb047c6a4a05a4af0314e064cba088 (patch)
treef902946a28927a3d26c82229782306e2efa6308d /src/safer_unchecked.rs
parent8dda53be56b3ddd17ed72de6a6d2262a2ba82625 (diff)
Wrap unsafe functions to catch errors in debug
Closes https://github.com/iximeow/yaxpeax-x86/issues/16
Diffstat (limited to 'src/safer_unchecked.rs')
-rw-r--r--src/safer_unchecked.rs28
1 files changed, 28 insertions, 0 deletions
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<T> {
+ unsafe fn get_kinda_unchecked<I>(&self, index: I) -> &<I as SliceIndex<[T]>>::Output
+ where
+ I: SliceIndex<[T]>;
+}
+
+impl<T> GetSaferUnchecked<T> for [T] {
+ unsafe fn get_kinda_unchecked<I>(&self, index: I) -> &<I as SliceIndex<[T]>>::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()
+ }
+}