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
// Copyright 2018 OysterPack Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Provides a typesafe [ULID](https://github.com/ulid/spec)

use chrono::{DateTime, Utc};
use rusty_ulid::{self, Ulid};
use serde::{
    de::{self, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    marker::PhantomData,
    str::FromStr,
};

#[cfg(test)]
mod tests;

/// Returns a new ULID
pub fn ulid() -> String {
    rusty_ulid::new_ulid_string()
}

/// Returns a new ULID
pub fn ulid_u128() -> u128 {
    rusty_ulid::Ulid::new().into()
}

/// Converts a ULID string representation into u128
pub fn ulid_str_into_u128(ulid: &str) -> Result<u128, DecodingError> {
    rusty_ulid::Ulid::from_str(ulid)
        .map(|ulid| ulid.into())
        .map_err(|err| DecodingError::from(err))
}

/// Converts a ULID u128 representation into String
pub fn ulid_u128_into_string(ulid: u128) -> String {
    rusty_ulid::Ulid::from(ulid).to_string()
}

/// Represents a ULID for some type T.
///
/// By default, Uid is serializable via serde. If serialization is not needed then you can opt out by
/// including the dependency with default features disabled : `default-features = false`.
///
/// # Examples
///
/// ## Uid for structs
/// ```rust
/// # use oysterpack_uid::Uid;
/// struct Domain;
/// type DomainId = Uid<Domain>;
/// let id = DomainId::new();
/// ```
/// ## Uid for traits
/// ```rust
/// # use oysterpack_uid::Uid;
/// trait Foo{}
/// // traits are not Send. Send is added to the type def in order to satisfy Uid type constraints
/// // in order to be able to send the Uid across threads
/// type FooId = Uid<dyn Foo + Send + Sync>;
/// let id = FooId::new();
/// ```
pub struct Uid<T: ?Sized> {
    id: u128,
    _type: PhantomData<T>,
}

#[cfg(feature = "serde")]
impl<T: 'static> Serialize for Uid<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u128(self.id)
    }
}

#[cfg(feature = "serde")]
impl<'de, T: 'static> Deserialize<'de> for Uid<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct UidVisitor<T: 'static>(PhantomData<&'static T>);

        impl<'de, T: 'static> Visitor<'de> for UidVisitor<T> {
            type Value = Uid<T>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("u128")
            }

            #[inline]
            fn visit_u8<E>(self, value: u8) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Uid::from(u128::from(value)))
            }

            #[inline]
            fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Uid::from(u128::from(value)))
            }

            #[inline]
            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Uid::from(u128::from(value)))
            }

            #[inline]
            fn visit_u128<E>(self, value: u128) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Uid::from(value))
            }
        }

        deserializer.deserialize_u128(UidVisitor(PhantomData))
    }
}

impl<T: 'static + ?Sized> Uid<T> {
    /// New Uid instances are guaranteed to be lexographically sortable if they are created within the same
    /// millisecond. In other words, Uid(s) created within the same millisecond are random.
    pub fn new() -> Uid<T> {
        Uid {
            id: Ulid::new().into(),
            _type: PhantomData,
        }
    }

    /// Creates the next strictly monotonic ULID for the given previous ULID.
    /// Returns None if the random part of the next ULID would overflow.
    pub fn next(previous: Uid<T>) -> Option<Uid<T>> {
        Ulid::next_strictly_monotonic(previous.ulid()).map(|next| Uid {
            id: next.into(),
            _type: PhantomData,
        })
    }

    /// returns the id
    pub fn id(&self) -> u128 {
        self.id
    }

    /// Returns the timestamp of this ULID as a DateTime<Utc>.
    pub fn datetime(&self) -> DateTime<Utc> {
        self.ulid().datetime()
    }

    /// Returns a new ULID with the random part incremented by one.
    /// Returns None if the new ULID overflows.
    pub fn increment(self) -> Option<Uid<T>> {
        Self::next(self)
    }

    fn ulid(&self) -> Ulid {
        Ulid::from(self.id)
    }
}

impl<T: 'static + ?Sized> fmt::Display for Uid<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let ulid: Ulid = self.ulid();
        f.write_str(&ulid.to_string())
    }
}

impl<T: 'static + ?Sized> PartialEq for Uid<T> {
    fn eq(&self, other: &Uid<T>) -> bool {
        self.id == other.id
    }
}

impl<T: 'static + ?Sized> PartialOrd for Uid<T> {
    fn partial_cmp(&self, other: &Uid<T>) -> Option<Ordering> {
        self.id.partial_cmp(&other.id)
    }
}

impl<T: 'static + ?Sized> Eq for Uid<T> {}

impl<T: 'static + ?Sized> Ord for Uid<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
    }
}

impl<T: 'static + ?Sized> Hash for Uid<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl<T: 'static + ?Sized> Copy for Uid<T> {}

impl<T: 'static + ?Sized> Clone for Uid<T> {
    fn clone(&self) -> Uid<T> {
        *self
    }
}

impl<T: 'static + ?Sized> fmt::Debug for Uid<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self.id)
    }
}

impl<T: 'static + ?Sized> From<[u8; 16]> for Uid<T> {
    fn from(bytes: [u8; 16]) -> Self {
        let ulid: Ulid = Ulid::from(bytes);
        Uid {
            id: ulid.into(),
            _type: PhantomData,
        }
    }
}

impl<T: 'static + ?Sized> From<u128> for Uid<T> {
    fn from(id: u128) -> Self {
        let ulid: Ulid = Ulid::from(id);
        Uid {
            id: ulid.into(),
            _type: PhantomData,
        }
    }
}

impl<T: 'static + ?Sized> From<(u64, u64)> for Uid<T> {
    fn from(id: (u64, u64)) -> Self {
        let ulid: Ulid = Ulid::from(id);
        Uid {
            id: ulid.into(),
            _type: PhantomData,
        }
    }
}

impl<T: 'static + ?Sized> FromStr for Uid<T> {
    type Err = DecodingError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let ulid: Ulid = Ulid::from_str(s)?;
        Ok(Uid {
            id: ulid.into(),
            _type: PhantomData,
        })
    }
}

impl<T: 'static + ?Sized> From<Uid<T>> for u128 {
    fn from(ulid: Uid<T>) -> Self {
        ulid.id
    }
}

impl<T: 'static + ?Sized> From<Uid<T>> for (u64, u64) {
    fn from(ulid: Uid<T>) -> Self {
        (
            (ulid.id >> 64) as u64,
            (ulid.id & 0xFFFF_FFFF_FFFF_FFFF) as u64,
        )
    }
}

/// Types of errors that can occur while trying to decode a string into a ulid
#[derive(Debug)]
pub enum DecodingError {
    /// The length of the parsed string does not conform to requirements.
    InvalidLength,
    /// The parsed string contains a character that is not allowed in a [crockford Base32](https://crockford.com/wrmg/base32.html) string.
    InvalidChar(char),
    /// Parsing the string overflowed the result value bits
    DataTypeOverflow,
}

impl From<rusty_ulid::crockford::DecodingError> for DecodingError {
    fn from(err: rusty_ulid::crockford::DecodingError) -> Self {
        match err {
            rusty_ulid::crockford::DecodingError::InvalidLength => DecodingError::InvalidLength,
            rusty_ulid::crockford::DecodingError::InvalidChar(c) => DecodingError::InvalidChar(c),
            rusty_ulid::crockford::DecodingError::DataTypeOverflow => {
                DecodingError::DataTypeOverflow
            }
        }
    }
}