Skip to content

Commit 5cea569

Browse files
committed
ref-with-flag: Update for 2nd edition.
1 parent dc2350d commit 5cea569

File tree

2 files changed

+13
-9
lines changed

2 files changed

+13
-9
lines changed

ref-with-flag/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@
22
name = "ref-with-flag"
33
version = "0.1.0"
44
authors = ["You <[email protected]>"]
5+
edition = "2018"
56

67
[dependencies]

ref-with-flag/src/lib.rs

+12-9
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,44 @@ mod ref_with_flag {
1010
/// If you're the kind of programmer who's never met a pointer whose
1111
/// 2⁰-bit you didn't want to steal, well, now you can do it safely!
1212
/// ("But it's not nearly as exciting this way...")
13-
pub struct RefWithFlag<'a, T: 'a> {
13+
pub struct RefWithFlag<'a, T> {
1414
ptr_and_bit: usize,
1515
behaves_like: PhantomData<&'a T> // occupies no space
1616
}
1717

1818
impl<'a, T: 'a> RefWithFlag<'a, T> {
19-
pub fn new(ptr: &'a T, bit: bool) -> RefWithFlag<T> {
19+
pub fn new(ptr: &'a T, flag: bool) -> RefWithFlag<T> {
2020
assert!(align_of::<T>() % 2 == 0);
2121
RefWithFlag {
22-
ptr_and_bit: ptr as *const T as usize | bit as usize,
22+
ptr_and_bit: ptr as *const T as usize | flag as usize,
2323
behaves_like: PhantomData
2424
}
2525
}
2626

27-
pub fn as_ref(&self) -> &'a T {
28-
let ptr = (self.ptr_and_bit & !1) as *const T;
27+
pub fn get_ref(&self) -> &'a T {
2928
unsafe {
29+
let ptr = (self.ptr_and_bit & !1) as *const T;
3030
&*ptr
3131
}
3232
}
3333

34-
pub fn as_bool(&self) -> bool {
34+
pub fn get_flag(&self) -> bool {
3535
self.ptr_and_bit & 1 != 0
3636
}
3737
}
3838
}
3939

40+
#[cfg(test)]
4041
mod ref_with_flag_tests {
42+
use super::ref_with_flag;
43+
4144
#[test]
4245
fn use_ref_with_flag() {
4346
use ref_with_flag::RefWithFlag;
4447

4548
let vec = vec![10, 20, 30];
46-
let pab = RefWithFlag::new(&vec, true);
47-
assert_eq!(pab.as_ref()[1], 20);
48-
assert_eq!(pab.as_bool(), true);
49+
let flagged = RefWithFlag::new(&vec, true);
50+
assert_eq!(flagged.get_ref()[1], 20);
51+
assert_eq!(flagged.get_flag(), true);
4952
}
5053
}

0 commit comments

Comments
 (0)