litep2p/
types.rs

1// Copyright 2023 litep2p developers
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Types used by [`Litep2p`](`crate::Litep2p`) protocols/transport.
22
23use rand::Rng;
24
25// Re-export the types used in public interfaces.
26pub mod multiaddr {
27    pub use multiaddr::{Error, Iter, Multiaddr, Onion3Addr, Protocol};
28}
29pub mod multihash {
30    pub use multihash::{Code, Error, Multihash, MultihashDigest};
31}
32
33pub mod protocol;
34
35/// Substream ID.
36#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
37pub struct SubstreamId(usize);
38
39impl Default for SubstreamId {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl SubstreamId {
46    /// Create new [`SubstreamId`].
47    pub fn new() -> Self {
48        SubstreamId(0usize)
49    }
50
51    /// Get [`SubstreamId`] from a number that can be converted into a `usize`.
52    pub fn from<T: Into<usize>>(value: T) -> Self {
53        SubstreamId(value.into())
54    }
55}
56
57/// Request ID.
58#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
59pub struct RequestId(usize);
60
61impl RequestId {
62    /// Get [`RequestId`] from a number that can be converted into a `usize`.
63    pub fn from<T: Into<usize>>(value: T) -> Self {
64        RequestId(value.into())
65    }
66}
67
68/// Connection ID.
69#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
70pub struct ConnectionId(usize);
71
72impl ConnectionId {
73    /// Create new [`ConnectionId`].
74    pub fn new() -> Self {
75        ConnectionId(0usize)
76    }
77
78    /// Generate random `ConnectionId`.
79    pub fn random() -> Self {
80        ConnectionId(rand::thread_rng().gen::<usize>())
81    }
82}
83
84impl Default for ConnectionId {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90impl From<usize> for ConnectionId {
91    fn from(value: usize) -> Self {
92        ConnectionId(value)
93    }
94}