1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use rand::{thread_rng, RngCore};
use std::borrow::Cow;
use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;
use std::ops::Deref;
use std::str::Utf8Error;

/// Wrapper of bytes represent a `Topic`
///
/// ## Example:
/// ```
/// use comet_eventbus::TopicKey;
///
/// // create topic from str literal
/// TopicKey::from("my awsome topic");
///
/// // crate topic from bytes literal
/// TopicKey::from(b"deafbeef");
///
/// // create topic from Vec<u8>
/// TopicKey::from(vec![0xde, 0xaf, 0xbe, 0xef]);
/// ```
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct TopicKey(Cow<'static, [u8]>);

impl TopicKey {
    /// try parse topic key as an utf-8 str
    pub fn try_as_str(&self) -> Result<&str, Utf8Error> {
        std::str::from_utf8(self.as_ref())
    }

    /// Generate a random topic
    pub fn random(len: usize) -> Self {
        let mut buf = Vec::new();
        buf.resize(len, 0);
        thread_rng().fill_bytes(&mut buf);
        Self::from(buf)
    }
}

impl AsRef<[u8]> for TopicKey {
    fn as_ref(&self) -> &[u8] {
        self.0.deref()
    }
}

impl Deref for TopicKey {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        self.0.deref()
    }
}

impl From<Vec<u8>> for TopicKey {
    fn from(value: Vec<u8>) -> Self {
        Self(Cow::from(value))
    }
}

impl From<&'static Vec<u8>> for TopicKey {
    fn from(value: &'static Vec<u8>) -> Self {
        Self(Cow::from(value))
    }
}

impl From<&'static [u8]> for TopicKey {
    fn from(value: &'static [u8]) -> Self {
        Self(Cow::from(value))
    }
}

impl From<&'static str> for TopicKey {
    fn from(value: &'static str) -> Self {
        Self(Cow::from(value.as_bytes()))
    }
}

impl Display for TopicKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            &self.try_as_str().unwrap_or(&hex::encode(self.as_ref()))
        )
    }
}

impl Debug for TopicKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("TopicKey")
            .field(&self.try_as_str().unwrap_or(&hex::encode(self.as_ref())))
            .finish()
    }
}