1
//! Unique identifiers for circuits.
2

            
3
use std::fmt::{Display, Formatter};
4

            
5
use derive_deftly::Deftly;
6
use tor_memquota::derive_deftly_template_HasMemoryCost;
7

            
8
/// Process-unique identifier for a circuit.
9
///
10
/// We could use channel_id.circid here, but the circid can be reused
11
/// over time.  This won't ever repeat on a 64-bit architecture, and
12
/// is super-unlikely to repeat on a 32-bit architecture.  (If
13
/// we're about to return a repeat value, we assert instead.)
14
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Deftly)]
15
#[derive_deftly(HasMemoryCost)]
16
pub struct UniqId {
17
    /// Channel that this circuit is on.
18
    chan: usize,
19
    /// ID for the circuit on the channel
20
    circ: usize,
21
}
22

            
23
impl UniqId {
24
    /// Construct a new circuit UniqId from its parts
25
382
    pub(crate) fn new(chan: usize, circ: usize) -> Self {
26
382
        UniqId { chan, circ }
27
382
    }
28

            
29
    /// A helper for displaying the process-unique identifiers of this circuit.
30
    ///
31
    /// Unlike the [`Display`] implementation, this does not display a `Circ` prefix.
32
5800
    pub fn display_chan_circ(&self) -> impl Display + '_ {
33
5800
        DisplayChanCirc(self)
34
5800
    }
35
}
36

            
37
impl Display for UniqId {
38
76
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
39
76
        write!(f, "Circ {}", self.display_chan_circ())
40
76
    }
41
}
42

            
43
/// A helper for displaying the process-unique identifiers of this circuit.
44
struct DisplayChanCirc<'a>(&'a UniqId);
45

            
46
impl<'a> Display for DisplayChanCirc<'a> {
47
5800
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
48
5800
        write!(f, "{}.{}", self.0.chan, self.0.circ)
49
5800
    }
50
}