ockam_core/flow_control/
flow_control_id.rs

1use crate::compat::rand::distributions::{Distribution, Standard};
2use crate::compat::rand::Rng;
3use crate::compat::string::{String, ToString};
4use core::fmt;
5use core::fmt::Formatter;
6use minicbor::{CborLen, Decode, Encode};
7use serde::{Deserialize, Serialize};
8
9/// Unique random identifier of a Flow Control
10#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Encode, Decode, CborLen)]
11#[rustfmt::skip]
12#[cbor(map)]
13pub struct FlowControlId {
14    #[n(1)] id: String
15}
16
17impl FlowControlId {
18    /// Constructor
19    fn new(str: &str) -> Self {
20        Self {
21            id: str.to_string(),
22        }
23    }
24}
25
26impl Serialize for FlowControlId {
27    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
28    where
29        S: serde::Serializer,
30    {
31        self.id.serialize(serializer)
32    }
33}
34
35impl<'de> Deserialize<'de> for FlowControlId {
36    fn deserialize<D>(deserializer: D) -> Result<FlowControlId, D::Error>
37    where
38        D: serde::Deserializer<'de>,
39    {
40        let id = String::deserialize(deserializer)?;
41        Ok(FlowControlId { id })
42    }
43}
44
45impl fmt::Debug for FlowControlId {
46    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
47        fmt::Display::fmt(self, f)
48    }
49}
50
51impl fmt::Display for FlowControlId {
52    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
53        f.write_str(&self.id)
54    }
55}
56
57impl Distribution<FlowControlId> for Standard {
58    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> FlowControlId {
59        let data: [u8; 16] = rng.gen();
60        FlowControlId::new(&hex::encode(data))
61    }
62}
63
64impl From<String> for FlowControlId {
65    fn from(value: String) -> Self {
66        Self { id: value }
67    }
68}