Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172//! Gambling Pointers//!//! A crate to create pointers which occassionally dereference to a nullpointer.//!//! # Quickstart//!//! ```//! use gambling_pointers::*;//!//! let value = GamblingPointer::new("test");//!//! // has a 1 in 5 chance to cause a null reference.//! println!("{}", *value);//! ```
#![deny(missing_docs)]
use core::{ops::Deref, ptr::null};use rand::RngExt as _;
/// Generic struct holding the inner value.pub struct GamblingPointer<T> { /// Inner generic value. value: T,}
impl<T> GamblingPointer<T> { /// Produces a new `GamblingPointer` instance for the value T. #[inline] pub const fn new(val: T) -> Self { Self { value: val } }}
impl<T> Deref for GamblingPointer<T> { type Target = T;
/// Dereferences the value. Has a 1 in 5 chance to /// return a nullpointer instead of the inner value. #[inline] fn deref(&self) -> &Self::Target { let gamble = rand::rng().random_range(0_i32..11_i32); // safety: the point of this is that it's not safe, // why are you making me write a safety comment clippy unsafe { &*if gamble.gt(&8) { null::<T>() } else { &self.value } } }}
#[cfg(test)]mod tests { use super::*;
#[test] fn pointers() { let val = GamblingPointer::new("test");
let f0 = *val; let f1 = *val; let f2 = *val; let f3 = *val; let f4 = *val;
println!("{f0} {f1} {f2} {f3} {f4}"); }}