]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/ptr_key.rs
Refactor mod/check (part vii)
[rust.git] / src / librustc_data_structures / ptr_key.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::{hash, ptr};
12 use std::ops::Deref;
13
14 /// A wrapper around reference that compares and hashes like a pointer.
15 /// Can be used as a key in sets/maps indexed by pointers to avoid `unsafe`.
16 #[derive(Debug)]
17 pub struct PtrKey<'a, T: 'a>(pub &'a T);
18
19 impl<'a, T> Clone for PtrKey<'a, T> {
20     fn clone(&self) -> Self { *self }
21 }
22
23 impl<'a, T> Copy for PtrKey<'a, T> {}
24
25 impl<'a, T> PartialEq for PtrKey<'a, T> {
26     fn eq(&self, rhs: &Self) -> bool {
27         ptr::eq(self.0, rhs.0)
28     }
29 }
30
31 impl<'a, T> Eq for PtrKey<'a, T> {}
32
33 impl<'a, T> hash::Hash for PtrKey<'a, T> {
34     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
35         (self.0 as *const T).hash(hasher)
36     }
37 }
38
39 impl<'a, T> Deref for PtrKey<'a, T> {
40     type Target = T;
41
42     fn deref(&self) -> &Self::Target {
43         self.0
44     }
45 }