tor_proto/tunnel/circuit/
unique_id.rs

1//! Unique identifiers for circuits.
2
3use std::fmt::{Display, Formatter};
4
5use derive_deftly::Deftly;
6use 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)]
16pub 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
23impl UniqId {
24    /// Construct a new circuit UniqId from its parts
25    pub(crate) fn new(chan: usize, circ: usize) -> Self {
26        UniqId { chan, circ }
27    }
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    pub fn display_chan_circ(&self) -> impl Display + '_ {
33        DisplayChanCirc(self)
34    }
35}
36
37impl Display for UniqId {
38    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
39        write!(f, "Circ {}", self.display_chan_circ())
40    }
41}
42
43/// A helper for displaying the process-unique identifiers of this circuit.
44struct DisplayChanCirc<'a>(&'a UniqId);
45
46impl<'a> Display for DisplayChanCirc<'a> {
47    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
48        write!(f, "{}.{}", self.0.chan, self.0.circ)
49    }
50}