Skip to main content

rustc_data_structures/
intern.rs

1use std::fmt::{self, Debug};
2use std::hash::{Hash, Hasher};
3use std::ops::Deref;
4use std::ptr;
5
6use crate::stable_hash::{StableHash, StableHashCtxt, StableHasher};
7
8mod private {
9    #[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PrivateZst {
}
#[automatically_derived]impl ::core::clone::Clone for PrivateZst {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PrivateZst { }Copy, #[automatically_derived]impl ::core::fmt::Debug for PrivateZst {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "PrivateZst")
    }
}Debug)]
10    pub struct PrivateZst;
11}
12
13/// This type is a reference with one special behaviour: the reference pointer (i.e. the address of
14/// the value referred to) is used for equality and hashing, rather than the value's contents, as
15/// would occur with a vanilla reference. There are two cases when this is useful.
16///
17/// - Types where uniqueness is guaranteed. This is most commonly achieved via interning -- hence
18///   the name `Interned` -- though it may also be possible via other means. In this case, the use
19///   of `Interned` is primarily a performance optimization, because pointer equality/hashing gives
20///   the same results as value equality/hashing, but is faster. (The use of the `Interned` type
21///   also provides documentation about the interned-ness.)
22///
23///   Note that in this case it is possible to have a `T` and a `Interned<T>` that are (or refer
24///   to) equal but different values. But if you have two different `Interned<T>`s, they both refer
25///   to the same value, at a single location in memory.
26///
27/// - Types with identity, where distinct values should always be considered unequal, even if they
28///   have equal values. These are rare in Rust, but do occur sometimes. In this case, the use of
29///   `Interned` gives different behaviour, because pointer equality/hashing gives different result
30///   to value equality/hashing, and is also faster.
31///
32/// The `PrivateZst` field means you can pattern match with `Interned(v, _)` but you can only
33/// construct a `Interned` with `new_unchecked`, and not directly. This means that all creation
34/// points can be audited easily.
35#[cfg_attr(bootstrap, rustc_pass_by_value)]
36#[cfg_attr(not(bootstrap), lint::pass_by_value)]
37pub struct Interned<'a, T>(pub &'a T, pub private::PrivateZst);
38
39impl<'a, T> Interned<'a, T> {
40    /// Create a new `Interned` value. The value referred to *must* satisfy one of the following
41    /// two conditions.
42    /// - It must be unique and it must remain unique in the future.
43    /// - It must be of a type with "identity" such that distinct values should always be
44    ///   considered unequal.
45    ///
46    /// This function has `_unchecked` in the name but is not `unsafe`, because if neither of these
47    /// conditions is met it will cause incorrect behaviour but will not affect memory safety.
48    #[inline]
49    pub const fn new_unchecked(t: &'a T) -> Self {
50        Interned(t, private::PrivateZst)
51    }
52}
53
54impl<'a, T> Clone for Interned<'a, T> {
55    fn clone(&self) -> Self {
56        *self
57    }
58}
59
60impl<'a, T> Copy for Interned<'a, T> {}
61
62impl<'a, T> Deref for Interned<'a, T> {
63    type Target = T;
64
65    #[inline]
66    fn deref(&self) -> &T {
67        self.0
68    }
69}
70
71impl<'a, T> PartialEq for Interned<'a, T> {
72    #[inline]
73    fn eq(&self, other: &Self) -> bool {
74        // Pointer equality implies equality, due to the uniqueness constraint.
75        ptr::eq(self.0, other.0)
76    }
77}
78
79impl<'a, T> Eq for Interned<'a, T> {}
80
81impl<'a, T> Hash for Interned<'a, T> {
82    #[inline]
83    fn hash<H: Hasher>(&self, s: &mut H) {
84        // Pointer hashing is sufficient.
85        ptr::hash(self.0, s)
86    }
87}
88
89impl<T> StableHash for Interned<'_, T>
90where
91    T: StableHash,
92{
93    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
94        self.0.stable_hash(hcx, hasher);
95    }
96}
97
98impl<T: Debug> Debug for Interned<'_, T> {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        self.0.fmt(f)
101    }
102}
103
104#[cfg(test)]
105mod tests;