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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
#![no_std]
#![warn(missing_docs)]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::style))]
#[cfg(feature = "std")]
extern crate std;
use core::{fmt, time, mem};
#[cfg(feature = "serde")]
mod serde;
type StrBuf = str_buf::StrBuf<36>;
#[repr(transparent)]
pub struct TextRepr(str_buf::StrBuf<36>);
impl TextRepr {
#[inline(always)]
pub const fn as_bytes(&self) -> &[u8] {
self.0.as_slice()
}
#[inline(always)]
pub const fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl core::ops::Deref for TextRepr {
type Target = str;
#[inline(always)]
fn deref(&self) -> &str {
self.0.as_str()
}
}
impl PartialEq<TextRepr> for &str {
#[inline(always)]
fn eq(&self, other: &TextRepr) -> bool {
*self == other.as_str()
}
}
impl PartialEq<TextRepr> for str {
#[inline(always)]
fn eq(&self, other: &TextRepr) -> bool {
self == other.as_str()
}
}
impl PartialEq<str> for TextRepr {
#[inline(always)]
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for TextRepr {
#[inline(always)]
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl fmt::Debug for TextRepr {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), fmt)
}
}
const SEP: u8 = b'-';
#[inline(always)]
const fn byte_to_hex(byt: u8, idx: usize) -> u8 {
const BASE: usize = 4;
const BASE_DIGIT: usize = (1 << BASE) - 1;
const HEX_DIGITS: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f'];
HEX_DIGITS[((byt as usize) >> (BASE * idx)) & BASE_DIGIT]
}
#[inline]
const fn hex_to_byte(hex: &[u8], cursor: usize) -> Result<u8, ParseError> {
let left = match hex[cursor] {
chr @ b'0'..=b'9' => chr - b'0',
chr @ b'a'..=b'f' => chr - b'a' + 10,
chr @ b'A'..=b'F' => chr - b'A' + 10,
chr => return Err(ParseError::InvalidByte(chr, cursor)),
};
let right = match hex[cursor + 1] {
chr @ b'0'..=b'9' => chr - b'0',
chr @ b'a'..=b'f' => chr - b'a' + 10,
chr @ b'A'..=b'F' => chr - b'A' + 10,
chr => return Err(ParseError::InvalidByte(chr, cursor + 1)),
};
Ok(left * 16 + right)
}
macro_rules! hex_to_byte_try {
($bytes:expr, $cursor:expr) => {
match hex_to_byte($bytes, $cursor) {
Ok(result) => result,
Err(error) => return Err(error),
}
}
}
pub const NAMESPACE_DNS: Uuid = Uuid::from_bytes([
0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8
]);
pub const NAMESPACE_URL: Uuid = Uuid::from_bytes([
0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8
]);
pub const NAMESPACE_OID: Uuid = Uuid::from_bytes([
0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8
]);
pub const NAMESPACE_X500: Uuid = Uuid::from_bytes([
0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8
]);
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Version {
Nil = 0,
Mac,
Dce,
Md5,
Random,
Sha1,
}
#[derive(Clone, Debug, Copy)]
pub struct Timestamp {
ticks: u64,
counter: u16
}
const V1_NS_TICKS: u64 = 0x01B2_1DD2_1381_4000;
impl Timestamp {
#[inline(always)]
pub const fn from_parts(ticks: u64, counter: u16) -> Self {
Self {
ticks,
counter,
}
}
#[inline]
pub const fn from_unix(time: time::Duration) -> Self {
let ticks = V1_NS_TICKS + time.as_secs() * 10_000_000 + (time.subsec_nanos() as u64) / 100;
Self::from_parts(ticks, 0)
}
#[cfg(feature = "std")]
#[inline]
pub fn now() -> Self {
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("System time is behind unix epoch");
Self::from_unix(now)
}
#[inline]
pub const fn set_counter(mut self, counter: u16) -> Self {
self.counter = counter;
self
}
#[inline(always)]
pub const fn into_parts(self) -> (u64, u16) {
(self.ticks, self.counter)
}
}
const UUID_SIZE: usize = 16;
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Uuid {
data: [u8; UUID_SIZE]
}
impl Uuid {
#[inline]
pub const fn nil() -> Self {
Self::from_bytes([0; UUID_SIZE])
}
#[inline]
pub const fn from_bytes(data: [u8; UUID_SIZE]) -> Self {
Self { data }
}
#[inline]
pub const fn from_slice(data: &[u8]) -> Option<Uuid> {
#[cold]
const fn fail() -> Option<Uuid> {
None
}
if data.len() != UUID_SIZE {
return fail();
}
Some(Self::from_bytes([
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15],
]))
}
#[inline]
pub const fn from_guid(d1: u32, d2: u16, d3: u16, d4: [u8; 8]) -> Self {
let d1 = d1.to_be_bytes();
let d2 = d2.to_be_bytes();
let d3 = d3.to_be_bytes();
Self::from_bytes([
d1[0], d1[1], d1[2], d1[3],
d2[0], d2[1],
d3[0], d3[1],
d4[0],
d4[1],
d4[2],
d4[3],
d4[4],
d4[5],
d4[6],
d4[7],
])
}
#[inline]
pub const fn as_bytes(&self) -> &[u8] {
&self.data
}
#[inline]
pub const fn bytes(&self) -> [u8; UUID_SIZE] {
self.data
}
#[inline]
pub const fn time_low(&self) -> u32 {
u32::from_ne_bytes([self.data[0], self.data[1], self.data[2], self.data[3]])
}
#[inline]
pub const fn time_mid(&self) -> u16 {
u16::from_ne_bytes([self.data[4], self.data[5]])
}
#[inline]
pub const fn time_high_and_version(&self) -> u16 {
u16::from_ne_bytes([self.data[6], self.data[7]])
}
#[inline]
pub const fn clock_sequence(&self) -> u16 {
u16::from_ne_bytes([self.data[8], self.data[9]])
}
#[inline]
pub const fn node(&self) -> [u8; 6] {
[self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15]]
}
#[inline]
pub const fn is_version(&self, version: Version) -> bool {
(self.data[6] >> 4) == version as u8
}
#[inline]
pub const fn is_variant(&self) -> bool {
(self.data[8] & 0xc0) == 0x80
}
pub const fn v1(timestamp: Timestamp, mac: [u8; 6]) -> Self {
let time_low = (timestamp.ticks & 0xFFFF_FFFF) as u32;
let time_mid = ((timestamp.ticks >> 32) & 0xFFFF) as u16;
let time_high_and_version = (((timestamp.ticks >> 48) & 0x0FFF) as u16) | (1 << 12);
Self::from_bytes([
(time_low >> 24) as u8,
(time_low >> 16) as u8,
(time_low >> 8) as u8,
time_low as u8,
(time_mid >> 8) as u8,
time_mid as u8,
(time_high_and_version >> 8) as u8,
time_high_and_version as u8,
(((timestamp.counter & 0x3F00) >> 8) as u8) | 0x80,
(timestamp.counter & 0xFF) as u8,
mac[0],
mac[1],
mac[2],
mac[3],
mac[4],
mac[5]
])
}
#[cfg(feature = "md5")]
pub const fn v3(namespace: Uuid, name: &[u8]) -> Self {
let hash = lhash::Md5::new().const_update(&namespace.data)
.const_update(name)
.const_result();
Self::from_bytes([
hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7],
hash[8], hash[9], hash[10], hash[11], hash[12], hash[13], hash[14], hash[15],
]).set_variant().set_version(Version::Md5)
}
#[inline]
pub const fn v4_from(random: [u8; UUID_SIZE]) -> Self {
Self::from_bytes(random).set_variant().set_version(Version::Random)
}
#[cfg(feature = "osrng")]
pub fn v4() -> Self {
let mut bytes = [0; UUID_SIZE];
if let Err(error) = getrandom::getrandom(&mut bytes[..]) {
panic!("OS RNG is not available for use: {}", error)
}
Self::v4_from(bytes)
}
#[cfg(feature = "prng")]
pub fn v4_prng() -> Self {
static RANDOM: squares_rnd::Rand = squares_rnd::Rand::new(1);
let right = u128::from(RANDOM.next_u64());
let left = u128::from(RANDOM.next_u64());
Self::v4_from(((left << 64) | right).to_ne_bytes())
}
#[cfg(feature = "sha1")]
pub const fn v5(namespace: Uuid, name: &[u8]) -> Self {
let sha1 = lhash::Sha1::new().const_update(&namespace.data)
.const_update(name)
.const_result();
Self::from_bytes([
sha1[0], sha1[1], sha1[2], sha1[3], sha1[4], sha1[5], sha1[6], sha1[7],
sha1[8], sha1[9], sha1[10], sha1[11], sha1[12], sha1[13], sha1[14], sha1[15],
]).set_variant().set_version(Version::Sha1)
}
#[inline]
pub const fn set_variant(mut self) -> Self {
self.data[8] = (self.data[8] & 0x3f) | 0x80;
self
}
#[inline]
pub const fn set_version(mut self, version: Version) -> Self {
self.data[6] = (self.data[6] & 0x0f) | ((version as u8) << 4);
self
}
pub const fn parse_ascii_bytes(input: &[u8]) -> Result<Self, ParseError> {
if input.len() == StrBuf::capacity() {
if input[8] != SEP {
return Err(ParseError::InvalidGroup(1));
} else if input[13] != SEP {
return Err(ParseError::InvalidGroup(2));
} else if input[18] != SEP {
return Err(ParseError::InvalidGroup(3));
} else if input[23] != SEP {
return Err(ParseError::InvalidGroup(4));
}
Ok(Self::from_bytes([
hex_to_byte_try!(input, 0),
hex_to_byte_try!(input, 2),
hex_to_byte_try!(input, 4),
hex_to_byte_try!(input, 6),
hex_to_byte_try!(input, 8 + 1),
hex_to_byte_try!(input, 10 + 1),
hex_to_byte_try!(input, 12 + 2),
hex_to_byte_try!(input, 14 + 2),
hex_to_byte_try!(input, 16 + 3),
hex_to_byte_try!(input, 18 + 3),
hex_to_byte_try!(input, 20 + 4),
hex_to_byte_try!(input, 22 + 4),
hex_to_byte_try!(input, 24 + 4),
hex_to_byte_try!(input, 26 + 4),
hex_to_byte_try!(input, 28 + 4),
hex_to_byte_try!(input, 30 + 4),
]))
} else if input.len() == StrBuf::capacity() - 4 {
Ok(Self::from_bytes([
hex_to_byte_try!(input, 0),
hex_to_byte_try!(input, 2),
hex_to_byte_try!(input, 4),
hex_to_byte_try!(input, 6),
hex_to_byte_try!(input, 8),
hex_to_byte_try!(input, 10),
hex_to_byte_try!(input, 12),
hex_to_byte_try!(input, 14),
hex_to_byte_try!(input, 16),
hex_to_byte_try!(input, 18),
hex_to_byte_try!(input, 20),
hex_to_byte_try!(input, 22),
hex_to_byte_try!(input, 24),
hex_to_byte_try!(input, 26),
hex_to_byte_try!(input, 28),
hex_to_byte_try!(input, 30),
]))
} else {
Err(ParseError::InvalidLength(input.len()))
}
}
#[inline(always)]
pub const fn parse_str(input: &str) -> Result<Self, ParseError> {
Self::parse_ascii_bytes(input.as_bytes())
}
#[inline]
pub const fn to_str(&self) -> TextRepr {
let storage = [
mem::MaybeUninit::new(byte_to_hex(self.data[0], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[0], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[1], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[1], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[2], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[2], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[3], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[3], 0)),
mem::MaybeUninit::new(SEP),
mem::MaybeUninit::new(byte_to_hex(self.data[4], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[4], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[5], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[5], 0)),
mem::MaybeUninit::new(SEP),
mem::MaybeUninit::new(byte_to_hex(self.data[6], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[6], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[7], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[7], 0)),
mem::MaybeUninit::new(SEP),
mem::MaybeUninit::new(byte_to_hex(self.data[8], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[8], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[9], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[9], 0)),
mem::MaybeUninit::new(SEP),
mem::MaybeUninit::new(byte_to_hex(self.data[10], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[10], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[11], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[11], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[12], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[12], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[13], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[13], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[14], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[14], 0)),
mem::MaybeUninit::new(byte_to_hex(self.data[15], 1)),
mem::MaybeUninit::new(byte_to_hex(self.data[15], 0)),
];
unsafe {
TextRepr(StrBuf::from_storage(storage, StrBuf::capacity() as u8))
}
}
}
impl fmt::Debug for Uuid {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str(self.to_str().as_str())
}
}
impl fmt::Display for Uuid {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str(self.to_str().as_str())
}
}
impl Default for Uuid {
#[inline(always)]
fn default() -> Self {
Self::nil()
}
}
impl AsRef<[u8]> for Uuid {
#[inline(always)]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl From<[u8; UUID_SIZE]> for Uuid {
#[inline(always)]
fn from(bytes: [u8; UUID_SIZE]) -> Self {
Self::from_bytes(bytes)
}
}
impl core::str::FromStr for Uuid {
type Err = ParseError;
#[inline(always)]
fn from_str(input: &str) -> Result<Self, Self::Err> {
Self::parse_ascii_bytes(input.as_bytes())
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ParseError {
InvalidLength(usize),
InvalidGroup(u8),
InvalidGroupLen(u8, usize),
InvalidByte(u8, usize)
}
impl fmt::Display for ParseError {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::InvalidLength(len) => fmt.write_fmt(format_args!("Invalid length {}", len)),
ParseError::InvalidGroup(idx) => fmt.write_fmt(format_args!("Group {} has unexpected length", idx)),
ParseError::InvalidGroupLen(idx, len) => fmt.write_fmt(format_args!("Group {} has unexpected length {}", idx, len)),
ParseError::InvalidByte(byte, pos) => fmt.write_fmt(format_args!("Invalid character '{:x}' at position {}", byte, pos)),
}
}
}
#[cfg(test)]
mod tests {
use crate::byte_to_hex;
#[test]
fn should_convert_byte_to_hex() {
assert_eq!([byte_to_hex(254, 1), byte_to_hex(254, 0)], *b"fe");
assert_eq!([byte_to_hex(255, 1), byte_to_hex(255, 0)], *b"ff");
assert_eq!([byte_to_hex(1, 1), byte_to_hex(1, 0)], *b"01");
assert_eq!([byte_to_hex(15, 1), byte_to_hex(15, 0)], *b"0f");
assert_eq!([byte_to_hex(0, 1), byte_to_hex(0, 0)], *b"00");
}
}