From 5cea569df263e29b60205b9b11dae1ecfaf1187c Mon Sep 17 00:00:00 2001 From: Jim Blandy Date: Sun, 13 Jun 2021 17:06:16 -0700 Subject: [PATCH] ref-with-flag: Update for 2nd edition. --- ref-with-flag/Cargo.toml | 1 + ref-with-flag/src/lib.rs | 21 ++++++++++++--------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/ref-with-flag/Cargo.toml b/ref-with-flag/Cargo.toml index c90ee11..be1acf6 100644 --- a/ref-with-flag/Cargo.toml +++ b/ref-with-flag/Cargo.toml @@ -2,5 +2,6 @@ name = "ref-with-flag" version = "0.1.0" authors = ["You "] +edition = "2018" [dependencies] diff --git a/ref-with-flag/src/lib.rs b/ref-with-flag/src/lib.rs index 2c435fb..0165ff7 100644 --- a/ref-with-flag/src/lib.rs +++ b/ref-with-flag/src/lib.rs @@ -10,41 +10,44 @@ mod ref_with_flag { /// If you're the kind of programmer who's never met a pointer whose /// 2⁰-bit you didn't want to steal, well, now you can do it safely! /// ("But it's not nearly as exciting this way...") - pub struct RefWithFlag<'a, T: 'a> { + pub struct RefWithFlag<'a, T> { ptr_and_bit: usize, behaves_like: PhantomData<&'a T> // occupies no space } impl<'a, T: 'a> RefWithFlag<'a, T> { - pub fn new(ptr: &'a T, bit: bool) -> RefWithFlag { + pub fn new(ptr: &'a T, flag: bool) -> RefWithFlag { assert!(align_of::() % 2 == 0); RefWithFlag { - ptr_and_bit: ptr as *const T as usize | bit as usize, + ptr_and_bit: ptr as *const T as usize | flag as usize, behaves_like: PhantomData } } - pub fn as_ref(&self) -> &'a T { - let ptr = (self.ptr_and_bit & !1) as *const T; + pub fn get_ref(&self) -> &'a T { unsafe { + let ptr = (self.ptr_and_bit & !1) as *const T; &*ptr } } - pub fn as_bool(&self) -> bool { + pub fn get_flag(&self) -> bool { self.ptr_and_bit & 1 != 0 } } } +#[cfg(test)] mod ref_with_flag_tests { + use super::ref_with_flag; + #[test] fn use_ref_with_flag() { use ref_with_flag::RefWithFlag; let vec = vec![10, 20, 30]; - let pab = RefWithFlag::new(&vec, true); - assert_eq!(pab.as_ref()[1], 20); - assert_eq!(pab.as_bool(), true); + let flagged = RefWithFlag::new(&vec, true); + assert_eq!(flagged.get_ref()[1], 20); + assert_eq!(flagged.get_flag(), true); } }