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
#![warn(missing_docs)]
extern crate chrono;
#[macro_use] extern crate lazy_static;
extern crate rand;
mod base32;
use chrono::prelude::{DateTime, UTC, TimeZone};
use std::fmt;
pub use base32::EncodingError;
#[derive(Debug, PartialOrd, PartialEq, Clone)]
pub struct Ulid(pub u64, pub u64);
impl Ulid {
pub fn new() -> Ulid {
Ulid::from_datetime(UTC::now())
}
pub fn from_datetime<T: TimeZone>(datetime: DateTime<T>) -> Ulid {
let timestamp = datetime.timestamp() * 1000
+ (datetime.timestamp_subsec_millis() as i64);
let timebits = (timestamp & ((1<<48)-1)) as u64;
return Ulid(
timebits << 16 | rand::random::<u16>() as u64,
rand::random::<u64>()
);
}
pub fn from_string(encoded: &str) -> Result<Ulid, EncodingError> {
return base32::decode(encoded)
.map(|(msb, lsb)| Ulid(msb, lsb));
}
pub fn datetime(&self) -> DateTime<UTC> {
let stamp = self.0 >> 16;
let secs = stamp / 1000;
let millis = stamp % 1000;
return UTC.timestamp(secs as i64, (millis*1000000) as u32);
}
pub fn timestamp_ms(&self) -> u64 {
return self.0 >> 16;
}
pub fn to_string(&self) -> String {
return base32::encode(self.0, self.1);
}
}
impl <'a> Into<String> for &'a Ulid {
fn into(self) -> String {
self.to_string()
}
}
impl From<(u64, u64)> for Ulid {
fn from(tuple: (u64, u64)) -> Self {
Ulid(tuple.0, tuple.1)
}
}
impl Into<(u64, u64)> for Ulid {
fn into(self) -> (u64, u64) {
(self.0, self.1)
}
}
impl fmt::Display for Ulid {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_string())
}
}
#[cfg(test)]
mod tests {
use super::Ulid;
use chrono::prelude::*;
use chrono::Duration;
#[test]
fn test_dynamic() {
let ulid = Ulid::new();
let encoded = ulid.to_string();
let ulid2 = Ulid::from_string(&encoded)
.expect("failed to deserialize");
println!("{}", encoded);
println!("{:?}", ulid);
println!("{:?}", ulid2);
assert_eq!(ulid, ulid2);
}
#[test]
fn test_static() {
let s = Ulid(0x4141414141414141, 0x4141414141414141).to_string();
let u = Ulid::from_string(&s).unwrap();
assert_eq!(&s, "21850M2GA1850M2GA1850M2GA1");
assert_eq!(u.0, 0x4141414141414141);
assert_eq!(u.1, 0x4141414141414141);
}
#[test]
fn test_order() {
let dt = UTC::now();
let ulid1 = Ulid::from_datetime(dt);
let ulid2 = Ulid::from_datetime(dt + Duration::milliseconds(1));
assert!(ulid1 < ulid2);
}
#[test]
fn test_datetime() {
let dt = UTC::now();
let ulid = Ulid::from_datetime(dt);
println!("{:?}, {:?}", dt, ulid.datetime());
assert!(ulid.datetime() <= dt);
assert!(ulid.datetime() + Duration::milliseconds(1) >= dt);
}
#[test]
fn test_timestamp() {
let dt = UTC::now();
let ulid = Ulid::from_datetime(dt);
let ts = dt.timestamp() as u64 * 1000 + dt.timestamp_subsec_millis() as u64;
assert_eq!(ulid.timestamp_ms(), ts);
}
}