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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! Generate YYIDs
//!
//! - GitHub: <https://github.com/asaaki/yyid.rs>
//! - crates.io: <https://crates.io/crates/yyid>
//!
//! Based on following micro libraries:
//!
//! - Ruby: <https://github.com/janlelis/yyid.rb>
//!
//!   ```ruby
//!   # Code here, since it is only a require and a one-liner:
//!   require "securerandom"
//!   "%08x-%04x-%04x-%04x-%04x%08x" % SecureRandom.random_bytes(16).unpack("NnnnnN")
//!   #=> "37ab3494-7e04-ecf1-b99f-259999a44d16"
//!   ```
//!
//! - JavaScript: <https://github.com/janlelis/yyid.js>
//! - Elixir: <https://github.com/janlelis/yyid.ex>
//! - Go: <https://github.com/janlelis/yyid.go>
//!
//! TODO: Reduce/simplify code to meet the API of the other libraries (a hyphenated string only)

// NOTE: Most of this code is currently based on uuid crate
//       (<https://github.com/rust-lang-nursery/uuid>).

#![doc(html_root_url = "http://asaaki.github.io/yyid.rs/yyid/index.html")]

#![cfg_attr(test, deny(warnings))]

extern crate rand;

use std::fmt;
use std::hash;
use std::iter::repeat;
use std::mem::transmute_copy;
use rand::Rng;

pub type YYIDBytes = [u8; 16];

#[derive(Copy, Clone)]
pub struct YYID {
    bytes: YYIDBytes
}

impl hash::Hash for YYID {
    fn hash<S: hash::Hasher>(&self, state: &mut S) {
        self.bytes.hash(state)
    }
}

#[derive(Copy, Clone)]
struct YYIDSections {
    section1:  u32,
    section2:  u16,
    section3:  u16,
    section4:  u16,
    section5a: u16,
    section5b: u32,
}

impl YYID {
    /// Creates a new random YYID
    pub fn new() -> YYID {
        let ybytes = rand::thread_rng().gen_iter::<u8>().take(16).collect::<Vec<_>>();
        let mut yyid = YYID{ bytes: [0; 16] };
        copy_memory(&mut yyid.bytes, &ybytes);
        yyid
    }

    /// Return an array of 16 octets containing the YYID data
    pub fn as_bytes<'a>(&'a self) -> &'a [u8] { &self.bytes }

    /// Returns the YYID as a string of 32 hexadecimal digits
    ///
    /// Example: `2ff0b694960e88a4693a66cff98fc56c`
    pub fn to_simple_string(&self) -> String {
        let mut ystr = repeat(0u8).take(32).collect::<Vec<_>>();
        for i in 0..16 {
            let digit = format!("{:02x}", self.bytes[i] as usize);
            ystr[i*2+0] = digit.as_bytes()[0];
            ystr[i*2+1] = digit.as_bytes()[1];
        }
        String::from_utf8(ystr).unwrap()
    }

    /// Returns a string of hexadecimal digits, separated into groups with a hyphen.
    ///
    /// Example: `02e7f0f6-067e-8c92-b25c-12c9180540a9`
    pub fn to_hyphenated_string(&self) -> String {
        let mut ys: YYIDSections;
        unsafe {
            ys = transmute_copy(&self.bytes);
        }
        ys.section1  = ys.section1.to_be();
        ys.section2  = ys.section2.to_be();
        ys.section3  = ys.section3.to_be();
        ys.section4  = ys.section4.to_be();
        ys.section5a = ys.section5a.to_be();
        ys.section5b = ys.section5b.to_be();
        let ystr = format!("{:08x}-{:04x}-{:04x}-{:04x}-{:04x}{:08x}",
            ys.section1,
            ys.section2, ys.section3, ys.section4,
            ys.section5a, ys.section5b);
        ystr
    }

    /// Returns the YYID formatted as a full URN string
    ///
    /// This is the same as the hyphenated format, but with the "urn:yyid:" prefix.
    ///
    /// Example: `urn:yyid:05f7d6d3-1727-ce2d-6cf2-3b73ad48ff73`
    pub fn to_urn_string(&self) -> String {
        format!("urn:yyid:{}", self.to_hyphenated_string())
    }
}

fn copy_memory(dst: &mut [u8], src: &[u8]) {
    for (slot, val) in dst.iter_mut().zip(src.iter()) {
        *slot = *val;
    }
}

/// Convert the YYID to a hexadecimal-based string representation wrapped in `YYID()`
impl fmt::Debug for YYID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "YYID(\"{}\")", self.to_hyphenated_string())
    }
}

/// Convert the YYID to a hexadecimal-based string representation
impl fmt::Display for YYID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.to_hyphenated_string())
    }
}

/// Test two YYIDs for equality
///
/// YYIDs are equal only when they are byte-for-byte identical
impl PartialEq for YYID {
    fn eq(&self, other: &YYID) -> bool {
        self.bytes == other.bytes
    }
}

impl Eq for YYID {}

/// Generates a random instance of YYID (V4 conformant)
impl rand::Rand for YYID {
    #[inline]
    fn rand<R: rand::Rng>(rng: &mut R) -> YYID {
        let ybytes = rng.gen_iter::<u8>().take(16).collect::<Vec<_>>();
        let mut yyid = YYID{ bytes: [0; 16] };
        copy_memory(&mut yyid.bytes, &ybytes);
        yyid
    }
}

#[cfg(test)]
mod tests {
    use super::YYID;
    use rand;

    #[test]
    fn test_new() {
        let yyid = YYID::new();
        let ystr = yyid.to_simple_string();

        assert!(ystr.len() == 32);
    }

    #[test]
    fn test_to_simple_string() {
        let yyid = YYID::new();
        let ystr = yyid.to_simple_string();

        assert!(ystr.len() == 32);
        assert!(ystr.chars().all(|c| c.is_digit(16)));
    }

    #[test]
    fn test_to_string() {
        let yyid = YYID::new();
        let ystr = yyid.to_string();

        assert!(ystr.len() == 36);
        assert!(ystr.chars().all(|c| c.is_digit(16) || c == '-'));
    }

    #[test]
    fn test_to_hyphenated_string() {
        let yyid = YYID::new();
        let ystr = yyid.to_hyphenated_string();

        assert!(ystr.len() == 36);
        assert!(ystr.chars().all(|c| c.is_digit(16) || c == '-'));
    }

    #[test]
    fn test_to_urn_string() {
        let yyid = YYID::new();
        let yurn = yyid.to_urn_string();
        let ystr = &yurn[9..];

        assert!(yurn.starts_with("urn:yyid:"));
        assert!(ystr.len() == 36);
        assert!(ystr.chars().all(|c| c.is_digit(16) || c == '-'));
    }

    #[test]
    fn test_to_simple_string_matching() {
        let yyid = YYID::new();

        let yhyphen = yyid.to_hyphenated_string();
        let ysimple = yyid.to_simple_string();

        let ysimplified = yhyphen.chars().filter(|&c| c != '-').collect::<String>();

        assert!(ysimplified == ysimple);
    }

    #[test]
    fn test_compare() {
        let yyid1 = YYID::new();
        let yyid2 = YYID::new();

        assert!(yyid1 == yyid1);
        assert!(yyid2 == yyid2);
        assert!(yyid1 != yyid2);
        assert!(yyid2 != yyid1);
    }

    #[test]
    fn test_as_bytes() {
        let yyid = YYID::new();
        let ybytes = yyid.as_bytes();

        assert!(ybytes.len() == 16);
        assert!(! ybytes.iter().all(|&b| b == 0));
    }

    #[test]
    fn test_operator_eq() {
        let yyid1 = YYID::new();
        let yyid2 = yyid1.clone();
        let yyid3 = YYID::new();

        assert!(yyid1 == yyid1);
        assert!(yyid1 == yyid2);
        assert!(yyid2 == yyid1);

        assert!(yyid1 != yyid3);
        assert!(yyid3 != yyid1);
        assert!(yyid2 != yyid3);
        assert!(yyid3 != yyid2);
    }

    #[test]
    fn test_rand_rand() {
        let mut rng = rand::thread_rng();
        let yyid: YYID = rand::Rand::rand(&mut rng);
        let ybytes = yyid.as_bytes();

        assert!(ybytes.len() == 16);
        assert!(! ybytes.iter().all(|&b| b == 0));
    }

    #[test]
    fn test_iterbytes_impl_for_uuid() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        let yyid1 = YYID::new();
        let yyid2 = YYID::new();
        set.insert(yyid1.clone());
        assert!(set.contains(&yyid1));
        assert!(!set.contains(&yyid2));
    }
}