Created
October 18, 2022 10:54
-
-
Save baakeydow/36bee447a2aea0338c3b054418556819 to your computer and use it in GitHub Desktop.
#rust compare addresses with https://docs.rs/by_address/latest/by_address/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! src: https://github.com/mbrubeck/by_address/blob/master/src/lib.rs | |
//! Wrapper type for by-address hashing and comparison. | |
use std::ops::Deref; | |
#[derive(Copy, Clone, Debug, Default)] | |
/// Wrapper for pointer types that implements by-address comparison. | |
pub struct ByAddress<T>(pub T) | |
where | |
T: ?Sized + Deref; | |
impl<T> ByAddress<T> | |
where | |
T: ?Sized + Deref, | |
{ | |
/// Convenience method for pointer casts. | |
pub fn addr(&self) -> *const T::Target { | |
&*self.0 | |
} | |
} | |
/// Raw pointer equality | |
impl<T> PartialEq for ByAddress<T> | |
where | |
T: ?Sized + Deref, | |
{ | |
fn eq(&self, other: &Self) -> bool { | |
self.addr() == other.addr() | |
} | |
} | |
#[test] | |
fn check_by_address() { | |
use super::*; | |
use std::rc::Rc; | |
let ref_counted = Rc::new([1, 2, 3]); | |
let ref_counted1 = by_address::ByAddress(ref_counted.clone()); | |
let ref_counted2 = by_address::ByAddress(ref_counted.clone()); | |
let ref_counted3 = by_address::ByAddress(Rc::new([1, 2, 3])); | |
println!("ref_counted1: {:p}, ref_counted2: {:p}", ref_counted1.addr(), ref_counted2.addr()); | |
assert_eq!(ref_counted1.addr(), ref_counted2.addr()); | |
println!("ref_counted1: {:p}, ref_counted3: {:p}", ref_counted1.addr(), ref_counted3.addr()); | |
assert_ne!(ref_counted1.addr(), ref_counted3.addr()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment