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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use std::fmt;

use borsh::{BorshDeserialize, BorshSerialize};

/// Util to help copying arrs since we don't have the ability to use
/// `.copy_from_slice` in const contexts.
macro_rules! gen_byte_copy {
    ($dest:ident, $src:ident, $idx:literal) => {
        if $src.len() > $idx {
            $dest[$idx] = $src[$idx];
        }
    };
}

pub const TOPIC_LEN: usize = 8;

/// Inner topic 8 byte array.
pub type TopicInner = [u8; TOPIC_LEN];

/// Tag type to route messagse to the right handler.  Should be printable 0-terminated ASCII chars.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, BorshDeserialize, BorshSerialize)]
pub struct Topic(TopicInner);

impl Topic {
    /// Wraps a raw array topic.
    pub fn new(buf: TopicInner) -> Self {
        Self(buf)
    }

    /// Parses a str if valid.
    ///
    /// # Panics
    ///
    /// If the str has a length greater than `TOPIC_LEN`.
    pub fn from_str(s: &str) -> Self {
        if s.as_bytes().len() > TOPIC_LEN {
            panic!("malformed topic '{}'", s);
        }

        let mut buf = [0; TOPIC_LEN];
        buf.copy_from_slice(s.as_bytes());

        Self(buf)
    }

    pub const fn from_const_str(s: &'static str) -> Self {
        let sb = s.as_bytes();

        if sb.len() > TOPIC_LEN {
            panic!("topic str too long");
        }

        let mut buf = [0u8; TOPIC_LEN];

        // This is horrible because we don't want to require `const_for`.
        gen_byte_copy!(buf, sb, 0);
        gen_byte_copy!(buf, sb, 1);
        gen_byte_copy!(buf, sb, 2);
        gen_byte_copy!(buf, sb, 3);
        gen_byte_copy!(buf, sb, 4);
        gen_byte_copy!(buf, sb, 5);
        gen_byte_copy!(buf, sb, 6);
        gen_byte_copy!(buf, sb, 7);

        Self(buf)
    }

    pub fn inner(&self) -> &TopicInner {
        &self.0
    }

    pub fn into_inner(&self) -> TopicInner {
        self.0
    }

    /// Returns the length of the "string part".
    pub fn str_len(&self) -> usize {
        self.0.iter().position(|v| *v == 0).unwrap_or_default()
    }

    /// Returns a slice of the string bytes of the topic.
    pub fn as_str_bytes(&self) -> &[u8] {
        &self.0[..self.str_len()]
    }

    /// Returns if it's a standard topic ID.
    pub fn is_standard(&self) -> bool {
        self.as_str_bytes()
            .iter()
            .all(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'-' || *b == b'$')
    }

    /// If the topic is a standard topic, returns it as a str.
    pub fn as_str(&self) -> Option<&str> {
        if self.is_standard() {
            Some(unsafe { std::str::from_utf8_unchecked(self.as_str_bytes()) })
        } else {
            None
        }
    }
}

impl fmt::Debug for Topic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ts) = self.as_str() {
            f.write_str(ts)
        } else {
            f.write_fmt(format_args!("nonstd{:?}", self.inner()))
        }
    }
}

impl fmt::Display for Topic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <Self as fmt::Debug>::fmt(self, f)
    }
}