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
// Copyright © 2020-present, Michael Cummings
//
// 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.
//
// MIT License
//
// Copyright © 2020-present, Michael Cummings <mgcummings@yahoo.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

pub use crate::error::*;
use crate::Uuid;
use diesel::{
    backend::Backend,
    deserialize::{self, FromSql},
    serialize::{self, ToSql},
};
use diesel_derives::{AsExpression, FromSqlRow, SqlType};
use rand::{rngs::ThreadRng, Rng};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    convert::{TryFrom, TryInto},
    fmt,
    io::Write,
};

/// Minimum structure for implementing core trait.
///
/// It implements a lot of From and TryFrom traits to allow easy
/// interfacing with most any code and easy conversions between formats.
#[derive(
    AsExpression,
    Clone,
    Debug,
    Deserialize,
    Eq,
    FromSqlRow,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
)]
#[sql_type = "Uuid4Proxy"]
pub struct Uuid4(u128);

impl Uuid4 {
    /// Construct a new random instance.
    ///
    /// ## Arguments
    /// * `rng` - Optional random number generator to save startup overhead when
    /// generating lots of new UUIDs or other custom needs.
    pub fn new<'a, TR>(rng: TR) -> Self
    where
        TR: Into<Option<&'a mut ThreadRng>>,
    {
        let mut v: u128;
        match rng.into() {
            Some(r) => v = r.gen(),
            None => v = rand::random(),
        }
        v &= 0xffffffffffffff3fff0fffffffffffff;
        v |= 0x00000000000000800040000000000000;
        Self(v)
    }
}

impl Uuid for Uuid4 {
    #[inline]
    fn uuid0(&self) -> u128 {
        self.0
    }
    #[inline]
    fn set_uuid0(&mut self, v: u128) {
        self.0 = v;
    }
}

impl Default for Uuid4 {
    fn default() -> Self {
        Self(0x00000000000000800040000000000000)
    }
}

impl fmt::Binary for Uuid4 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let val = self.0;
        fmt::Binary::fmt(&val, f)
    }
}

impl fmt::LowerHex for Uuid4 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let val = self.0;
        fmt::LowerHex::fmt(&val, f)
    }
}

impl fmt::UpperHex for Uuid4 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let val = self.0;
        fmt::UpperHex::fmt(&val, f)
    }
}

impl From<u128> for Uuid4 {
    fn from(v: u128) -> Self {
        let mut v = v;
        v &= 0xffffffffffffff3fff0fffffffffffff;
        v |= 0x00000000000000800040000000000000;
        Self(v)
    }
}

impl From<&[u8; 16]> for Uuid4 {
    fn from(bytes: &[u8; 16]) -> Self {
        let mut result = u128::from_le_bytes(bytes.to_owned());
        result &= 0xffffffffffffff3fff0fffffffffffff;
        result |= 0x00000000000000800040000000000000;
        Self(result)
    }
}

impl TryFrom<&str> for Uuid4 {
    type Error = U64Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Uuid4::try_from(value.as_bytes())
    }
}

impl TryFrom<&[u8]> for Uuid4 {
    type Error = U64Error;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        match value.len() {
            16 => {
                let val: &[u8; 16] = value[..16].try_into()?;
                Ok(val.into())
            }
            22 => {
                let val: &[u8; 22] = value[..22].try_into()?;
                Ok(val.try_into()?)
            }
            32 => {
                let val: &[u8; 32] = value[..32].try_into()?;
                Ok(val.try_into()?)
            }
            36 => {
                let val: &[u8; 36] = value[..36].try_into()?;
                Ok(val.try_into()?)
            }
            n => Err(U64Error::InvalidStrLength(n)),
        }
    }
}

impl TryFrom<&[u8; 22]> for Uuid4 {
    type Error = U64Error;
    fn try_from(value: &[u8; 22]) -> Result<Self, Self::Error> {
        let mut map = HashMap::with_capacity(64);
        for (v, k) in Self::BASE64.iter() {
            map.insert(*k, *v);
        }
        let mut bin = String::new();
        for char in value.iter() {
            let char = &char.to_owned().into();
            match map.get(char) {
                Some(n) => {
                    bin.push_str(*n);
                }
                None => return Err(U64Error::InvalidBase64String),
            }
        }
        // Drop the 4 fill bits that were add to have 22 chars.
        bin = bin.split_off(4);
        let mut result = u128::from_str_radix(&*bin, 2)
            .map_err(|_| U64Error::InvalidBinString)?;
        result = result.to_le();
        result &= 0xffffffffffffff3fff0fffffffffffff;
        result |= 0x00000000000000800040000000000000;
        Ok(Self(result))
    }
}

impl TryFrom<&[u8; 32]> for Uuid4 {
    type Error = U64Error;

    /// Converts an utf-8 hexadecimal byte array into a uuid4 value.
    ///
    /// __NOTE:__ _This function does NOT do any additional validating above
    /// what Rust needs to parse the bytes as a hexadecimal string._
    fn try_from(value: &[u8; 32]) -> Result<Self, Self::Error> {
        let utf = std::str::from_utf8(value)
            .map_err(|_| U64Error::InvalidUtf8String)?;
        let mut result = u128::from_str_radix(utf, 16)
            .map_err(|_| U64Error::InvalidHexString)?;
        result &= 0xffffffffffffff3fff0fffffffffffff;
        result |= 0x00000000000000800040000000000000;
        Ok(Self(result))
    }
}

impl TryFrom<&[u8; 36]> for Uuid4 {
    type Error = U64Error;

    /// Converts an utf-8 hexadecimal byte array into a uuid4 value.
    ///
    /// the first 4 '-' characters found in the `value` will be removed.
    ///
    /// __NOTE:__ _This function does NOT do any additional validating above
    /// what Rust needs to parse the bytes as a hexadecimal string._
    fn try_from(value: &[u8; 36]) -> Result<Self, Self::Error> {
        let utf = std::str::from_utf8(value)
            .map_err(|_| U64Error::InvalidUtf8String)?
            .replacen('-', "", 4);
        let mut result = u128::from_str_radix(&*utf, 16)
            .map_err(|_| U64Error::InvalidUuidString)?;
        result &= 0xffffffffffffff3fff0fffffffffffff;
        result |= 0x00000000000000800040000000000000;
        Ok(Self(result))
    }
}

impl<DB> FromSql<Uuid4Proxy, DB> for Uuid4
where
    DB: Backend<RawValue = [u8]>,
{
    fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
        match bytes {
            Some(bytes) => Ok(bytes.try_into()?),
            None => Err(Box::new(diesel::result::UnexpectedNullError)),
        }
    }
}

impl<DB> ToSql<Uuid4Proxy, DB> for Uuid4
where
    DB: Backend,
    String: ToSql<Uuid4Proxy, DB>,
{
    fn to_sql<W: Write>(
        &self,
        out: &mut serialize::Output<W, DB>,
    ) -> serialize::Result {
        self.as_base64().to_sql(out)
    }
}

#[derive(SqlType)]
pub struct Uuid4Proxy;