1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! Wrapper type for by-address hashing and comparison.
//!
//! [`ByAddress`] can be used to wrap any pointer type (i.e. any type that implements the Deref
//! trait).  This includes references, raw pointers, smart pointers like `Rc<T>` and `Box<T>`, and
//! specialized pointer-like types such as `Vec<T>` and `String`.
//!
//! Comparison, ordering, and hashing of the wrapped pointer will be based on the address of its
//! contents, rather than their value.
//!
//! ```
//! use by_address::ByAddress;
//! use std::rc::Rc;
//!
//! let rc = Rc::new(5);
//! let x = ByAddress(rc.clone());
//! let y = ByAddress(rc.clone());
//!
//! // x and y are two pointers to the same address:
//! assert_eq!(x, y);
//!
//! let z = ByAddress(Rc::new(5));
//!
//! // *x and *z have the same value, but not the same address:
//! assert_ne!(x, z);
//! ```
//!
//! If `T` is a pointer to an unsized type, then comparison of `ByAddress<T>` uses the
//! entire fat pointer, not just the "thin" data address.  This means that two slice pointers
//! are consider equal only if they have the same starting address *and* length.
//!
//! ```
//! # use by_address::ByAddress;
//! #
//! let v = [1, 2, 3, 4];
//!
//! assert_eq!(ByAddress(&v[0..4]), ByAddress(&v[0..4])); // Same address and length.
//! assert_ne!(ByAddress(&v[0..4]), ByAddress(&v[0..2])); // Same address, different length.
//! ```
//!
//! You can use [`ByThinAddress`] instead if you want to compare slices by starting address only,
//! or trait objects by data pointer only.
//!
//! You can use wrapped pointers as keys in hashed or ordered collections, like BTreeMap/BTreeSet
//! or HashMap/HashSet, even if the target of the pointer doesn't implement hashing or ordering.
//! This even includes pointers to trait objects, which usually don't implement the Eq trait
//! because it is not object-safe.
//!
//! ```
//! # use by_address::ByAddress;
//! # use std::collections::HashSet;
//! #
//! /// Call each item in `callbacks`, skipping any duplicate references.
//! fn call_each_once(callbacks: &[&Fn()]) {
//!     let mut seen: HashSet<ByAddress<&Fn()>> = HashSet::new();
//!     for &f in callbacks {
//!         if seen.insert(ByAddress(f)) {
//!             f();
//!         }
//!     }
//! }
//! ```
//!
//! However, note that comparing fat pointers to trait objects can be unreliable because of
//! [Rust issue #46139](https://github.com/rust-lang/rust/issues/46139).  In some cases,
//! [`ByThinAddress`] may be more useful.
//!
//! This crate does not depend on libstd, so it can be used in [`no_std`] projects.
//!
//! [`no_std`]: https://doc.rust-lang.org/book/first-edition/using-rust-without-the-standard-library.html

// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![no_std]

use core::cmp::Ordering;
use core::convert::AsRef;
use core::fmt::{Debug, Display, Formatter};
use core::hash::{Hash, Hasher};
use core::ops::{Deref, DerefMut};

/// Wrapper for pointer types that implements by-address comparison.
///
/// See the [crate-level documentation](index.html) for details.
///
/// Note that equality tests and hashes on fat pointers (`&dyn Trait`, `&[T]`, `&str`, etc)
/// include the attribute of the fat pointer. If this is not desired, use [`ByThinAddress`].
#[derive(Copy, Clone, Default)]
pub struct ByAddress<T>(pub T)
where
    T: ?Sized + Deref;

impl<T> ByAddress<T>
where
    T: ?Sized + Deref,
{
    /// Convenience method for pointer casts.
    fn addr(&self) -> *const T::Target {
        &*self.0
    }
}

struct DebugAdapter<'a, T>(&'a T)
where
    T: ?Sized + Deref + Debug;

impl<'a, T> Debug for DebugAdapter<'a, T>
where
    T: ?Sized + Deref + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)?;
        f.write_str(" @ ")?;
        (self.0.deref() as *const T::Target).fmt(f)?;
        Ok(())
    }
}

impl<T> Debug for ByAddress<T>
where
    T: ?Sized + Deref + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("ByAddress")
            .field(&DebugAdapter(&self.0))
            .finish()
    }
}

impl<T> Display for ByAddress<T>
where
    T: ?Sized + Deref + Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)
    }
}

/// Raw pointer equality
impl<T> PartialEq for ByAddress<T>
where
    T: ?Sized + Deref,
{
    fn eq(&self, other: &Self) -> bool {
        self.addr() == other.addr()
    }
}
impl<T> Eq for ByAddress<T> where T: ?Sized + Deref {}

/// Raw pointer ordering
impl<T> Ord for ByAddress<T>
where
    T: ?Sized + Deref,
{
    fn cmp(&self, other: &Self) -> Ordering {
        self.addr().cmp(&other.addr())
    }
}

/// Raw pointer comparison
impl<T> PartialOrd for ByAddress<T>
where
    T: ?Sized + Deref,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.addr().cmp(&other.addr()))
    }
}

/// Raw pointer hashing
impl<T> Hash for ByAddress<T>
where
    T: ?Sized + Deref,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.addr().hash(state)
    }
}

// Generic conversion traits:

impl<T> Deref for ByAddress<T>
where
    T: ?Sized + Deref,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for ByAddress<T>
where
    T: ?Sized + Deref,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T, U> AsRef<U> for ByAddress<T>
where
    T: ?Sized + Deref + AsRef<U>,
{
    fn as_ref(&self) -> &U {
        self.0.as_ref()
    }
}

impl<T, U> AsMut<U> for ByAddress<T>
where
    T: ?Sized + Deref + AsMut<U>,
{
    fn as_mut(&mut self) -> &mut U {
        self.0.as_mut()
    }
}

impl<T> From<T> for ByAddress<T>
where
    T: Deref,
{
    fn from(t: T) -> ByAddress<T> {
        ByAddress(t)
    }
}

/// Similar to [`ByAddress`], but omits the attributes of fat pointers.
#[derive(Copy, Clone, Default)]
pub struct ByThinAddress<T>(pub T)
where
    T: ?Sized + Deref;

impl<T> ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    /// Convenience method for pointer casts.
    fn addr(&self) -> *const T::Target {
        &*self.0
    }
}

impl<T> Debug for ByThinAddress<T>
where
    T: ?Sized + Deref + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("ByThinAddress")
            .field(&DebugAdapter(&self.0))
            .finish()
    }
}

impl<T> Display for ByThinAddress<T>
where
    T: ?Sized + Deref + Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)
    }
}

/// Raw pointer equality
impl<T> PartialEq for ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    fn eq(&self, other: &Self) -> bool {
        core::ptr::eq(self.addr() as *const (), other.addr() as *const _)
    }
}
impl<T> Eq for ByThinAddress<T> where T: ?Sized + Deref {}

/// Raw pointer ordering
impl<T> Ord for ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    fn cmp(&self, other: &Self) -> Ordering {
        (self.addr() as *const ()).cmp(&(other.addr() as *const ()))
    }
}

/// Raw pointer comparison
impl<T> PartialOrd for ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some((self.addr() as *const ()).cmp(&(other.addr() as *const ())))
    }
}

/// Raw pointer hashing
impl<T> Hash for ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        (self.addr() as *const ()).hash(state)
    }
}

// Generic conversion traits:

impl<T> Deref for ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for ByThinAddress<T>
where
    T: ?Sized + Deref,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T, U> AsRef<U> for ByThinAddress<T>
where
    T: ?Sized + Deref + AsRef<U>,
{
    fn as_ref(&self) -> &U {
        self.0.as_ref()
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::format;

    use crate::{ByAddress, ByThinAddress};

    trait A: std::fmt::Debug {
        fn test(&self) {}
    }
    trait B: A {
        fn test2(&self) {}
    }

    #[derive(Debug)]
    struct Test {}
    impl A for Test {}
    impl B for Test {}

    fn force_vtable<O: B>(v: &O) -> &dyn A {
        v
    }

    #[test]
    fn test_thin_ptr_fail() {
        let t = Test {};
        let tr1: &dyn A = &t;
        let tr2: &dyn A = force_vtable(&t);

        let a = ByAddress(tr1);
        let b = ByAddress(tr2);

        assert_ne!(a, b);
    }

    #[test]
    fn test_thin_ptr_success() {
        let t = Test {};
        let tr1: &dyn A = &t;
        let tr2: &dyn A = force_vtable(&t);

        let a = ByThinAddress(tr1);
        let b = ByThinAddress(tr2);

        assert_eq!(a, b);
    }

    #[test]
    fn test_debug() {
        let x = &1;
        let b = ByAddress(x);
        let expected = format!("ByAddress(1 @ {:p})", x);
        let actual = format!("{:?}", b);
        assert_eq!(expected, actual);

        let t = ByThinAddress(x);
        let expected = format!("ByThinAddress(1 @ {:p})", x);
        let actual = format!("{:?}", t);
        assert_eq!(expected, actual);
    }
}