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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//! MessageId
use std::sync::atomic::{AtomicU16, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{fmt, result, error};
use std::str::FromStr;

use once_cell::sync::Lazy;

use rand::{self, thread_rng, Rng};

use hex::{ToHex, FromHex, FromHexError};

static COUNTER: Lazy<AtomicU16> = Lazy::new(|| AtomicU16::new(thread_rng().gen()));

#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct MessageId {
    bytes: [u8; 12]
}

pub type Result<T> = result::Result<T, Error>;

// Unique incrementing MessageId.
//
//   +---+---+---+---+---+---+---+---+---+---+---+---+
//   |       timestamp       | count |    random     |
//   +---+---+---+---+---+---+---+---+---+---+---+---+
//     0   1   2   3   4   5   6   7   8   9   10  11
impl MessageId {
    /// Generate a new MessageId
    ///
    /// # Examples
    ///
    /// ```
    /// use nson::message_id::MessageId;
    ///
    /// let id = MessageId::new();
    ///
    /// println!("{:?}", id);
    /// ```
    pub fn new() -> MessageId {
        let timestamp = timestamp();
        let counter = gen_count();
        let random_bytes = random_bytes();

        let mut bytes: [u8; 12] = [0; 12];

        bytes[..6].copy_from_slice(&timestamp[2..]);
        bytes[6..8].copy_from_slice(&counter);
        bytes[8..].copy_from_slice(&random_bytes);

        MessageId { bytes }
    }

    /// Generate an MessageId with bytes
    ///
    /// # Examples
    ///
    /// ```
    /// use nson::message_id::MessageId;
    ///
    /// let id = MessageId::with_bytes([1, 111, 157, 189, 157, 247, 247, 220, 156, 134, 213, 115]);
    ///
    /// assert_eq!(format!("{}", id), "016f9dbd9df7f7dc9c86d573")
    /// ```
    pub fn with_bytes(bytes: [u8; 12]) -> Self {
        MessageId { bytes }
    }

    /// Generate an MessageId with string.
    /// Provided string must be a 12-byte hexadecimal string
    ///
    /// # Examples
    ///
    /// ```
    /// use nson::message_id::MessageId;
    ///
    /// let id = MessageId::with_string("016f9dbd9df7f7dc9c86d573").unwrap();
    ///
    /// assert_eq!(format!("{}", id), "016f9dbd9df7f7dc9c86d573")
    /// ```
    pub fn with_string(str: &str) -> Result<MessageId> {
        let bytes: Vec<u8> = FromHex::from_hex(str)?;
        if bytes.len() != 12 {
            return Err(Error::ArgumentError("Provided string must be a 12-byte hexadecimal string.".to_string()))
        }

        let mut buf = [0u8; 12];
        buf[..].copy_from_slice(&bytes);

        Ok(MessageId {
            bytes: buf
        })
    }

    /// 12-byte binary representation of this MessageId.
    pub fn bytes(&self) -> [u8; 12] {
        self.bytes
    }

    /// Timstamp of this MessageId
    pub fn timestamp(&self) -> u64 {
        let mut buf = [0u8; 8];
        buf[2..8].copy_from_slice(&self.bytes[..6]);
        u64::from_be_bytes(buf)
    }

    /// Convert this MessageId to a 16-byte hexadecimal string.
    pub fn to_hex(&self) -> String {
        self.bytes.encode_hex()
    }

    pub fn zero() -> MessageId {
        MessageId { bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
    }

    pub fn is_zero(&self) -> bool {
        self == &MessageId::zero()
    }
}

impl Default for MessageId {
    fn default() -> Self {
        MessageId::new()
    }
}

impl fmt::Display for MessageId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl fmt::Debug for MessageId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&format!("MessageId({})", self.to_hex()))
    }
}

impl From<[u8; 12]> for MessageId {
    fn from(bytes: [u8; 12]) -> Self {
        MessageId { bytes }
    }
}

impl FromStr for MessageId {
    type Err = Error;

    fn from_str(s: &str) -> Result<MessageId> {
        Self::with_string(s)
    }
}

#[inline]
fn timestamp() -> [u8; 8] {
    let time = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("SystemTime before UNIX EPOCH!")
        .as_millis() as u64;

    time.to_be_bytes()
}

#[inline]
fn random_bytes() -> [u8; 4] {
    let rand_num: u32 = thread_rng().gen();

    rand_num.to_be_bytes()
}

#[inline]
fn gen_count() -> [u8; 2] {
    let count = COUNTER.fetch_add(1, Ordering::SeqCst);

    count.to_be_bytes()
}

#[derive(Debug)]
pub enum Error {
    ArgumentError(String),
    FromHexError(FromHexError)
}

impl From<FromHexError> for Error {
    fn from(err: FromHexError) -> Error {
        Error::FromHexError(err)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::ArgumentError(ref err) => err.fmt(fmt),
            Error::FromHexError(ref err) => err.fmt(fmt)
        }
    }
}

impl error::Error for Error {
    fn cause(&self) -> Option<&dyn error::Error> {
        match *self {
            Error::ArgumentError(_) => None,
            Error::FromHexError(ref err) => Some(err)
        }
    }
}