short-uuid 0.2.1

A library to generate and parse short uuids
Documentation
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
// THE MIT License (MIT)
//
// Copyright (c) 2024 Radim Höfer
// See the license.txt file in the project root

//! Generate and translate standard UUIDs into shorter or just different formats and back.
//!
//! A port of the JavaScript npm package [short-uuid](https://www.npmjs.com/package/short-uuid) so big thanks to the author.
//!
//! An example of short uuid string in default flickrBase58 alphabet:
//!```text
//! mhvXdrZT4jP5T8vBxuvm75
//!```
//!
//! ## Getting started
//!
//! Install the package with `cargo`:
//!
//! ```sh
//! cargo add short-uuid
//! ```
//!
//! or add it to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! short-uuid = "0.2.0"
//! ```
//! ### Examples
//!
//! Generate short uuidv4 encoded in flickrBase58 format:
//
//! ```rust
//! use short_uuid::ShortUuid;
//!
//! let shortened_uuid = ShortUuid::generate();
//! ```
//!
//! Generate short uuidv4 encoded in flickrBase58 format using macro:
//! ```rust
//! use short_uuid::short;
//!
//! let shortened_uuid = short!();
//! ```
//!
//! Generate short uuidv4 using custom alphabet:
//!
//! ```rust
//! use short_uuid::{ShortUuidCustom, CustomTranslator};
//!
//! let custom_alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
//! let translator = CustomTranslator::new(custom_alphabet).unwrap();
//!
//! let custom_short = ShortUuidCustom::generate(&translator);
//! let custom_short_string = custom_short.to_string();
//! ```
//!
//! Get shortened uuid from standard uuid:
//!
//! ```rust
//! use short_uuid::ShortUuid;
//! // create normal uuid v4
//! let uuid = uuid::Uuid::new_v4();
//!
//! let short = ShortUuid::from_uuid(&uuid);
//! ```
//! Get shortened uuid from uuid using custom alphabet:
//!
//! ```rust
//! use short_uuid::{ShortUuidCustom, CustomTranslator};
//!
//! let custom_alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
//! let translator = CustomTranslator::new(custom_alphabet).unwrap();
//!
//! let uuid = uuid::Uuid::new_v4();
//! let short_custom = ShortUuidCustom::from_uuid(&uuid, &translator);
//! let short_custom_string = short_custom.to_string();
//! ```
//!
//! Get shortened uuid from uuid string:
//!
//! ```rust
//! use short_uuid::ShortUuid;
//!
//! let uuid_str = "3cfb46e7-c391-42ef-90b8-0c1d9508e752";
//! let short_uuid = ShortUuid::from_uuid_str(&uuid_str);
//! ```
//!
//! Get shortened uuid from uuid string using custom alphabet:
//!
//! ```rust
//! use short_uuid::{ShortUuidCustom, CustomTranslator};
//!
//! let custom_alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
//! let translator = CustomTranslator::new(custom_alphabet).unwrap();
//!
//! let uuid_str = "3cfb46e7-c391-42ef-90b8-0c1d9508e752";
//! let short_custom = ShortUuidCustom::from_uuid_str(&uuid_str, &translator).unwrap();
//! let short_custom_string = short_custom.to_string();
//! ```
//!
//! Serialize and deserialize struct with short uuid (you must enable the `serde` feature):
//!
//! ```toml
//! [dependencies]
//! short-uuid = { version = "0.2.0", features = ["serde"] }
//! ```
//!
//! Example usage:
//! ```rust
//! #[cfg(feature = "serde")]
//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
//! struct TestStruct {
//!     id: ShortUuid,
//! }
//!
//! #[cfg(feature = "serde")]
//! fn example() {
//!     let uuid_str = "0408510d-ce4f-4761-ab67-2dfe2931c898";
//!     let short_id = ShortUuid::from_uuid_str(uuid_str).unwrap();
//!
//!     let test_struct = TestStruct {
//!         id: short_id,
//!     };
//!
//!     let serialized = serde_json::to_string(&test_struct).unwrap();
//! }
//! ```
//!
//! # References
//! * [Wikipedia: Universally Unique Identifier](http://en.wikipedia.org/wiki/Universally_unique_identifier)
//! * [uuid crate](https://crates.io/crates/uuid)

use converter::BaseConverter;
use error::{CustomAlphabetError, ErrorKind, InvalidShortUuid};

/// Convert between different bases
pub mod converter;
mod error;
mod fmt;

mod macros;
use uuid;

pub const FLICKR_BASE_58: &str = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

pub const COOKIE_BASE_90: &str =
    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+-./:<=>?@[]^_`{|}~";

type UuidError = uuid::Error;

// pub type Bytes = [u8; 16];
/// A byte array containing the ShortUuid
pub type Bytes = Vec<u8>;

/// Shortened UUID
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ShortUuid(Bytes);

/// Shortened UUID using custom alphabet
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ShortUuidCustom(Bytes);

/// Custom alphabet used for short uuid
pub type CustomAlphabet = &'static str;

/// Custom translator used use for base conversion
pub struct CustomTranslator(BaseConverter);

impl CustomTranslator {
    /// Create new custom translator
    pub fn new(custom_alphabet: CustomAlphabet) -> Result<Self, CustomAlphabetError> {
        let converter = BaseConverter::new_custom(custom_alphabet)?;
        Ok(Self(converter))
    }

    fn as_slice(&self) -> &BaseConverter {
        &self.0
    }
}

impl From<ShortUuid> for ShortUuidCustom {
    fn from(short_uuid: ShortUuid) -> Self {
        ShortUuidCustom(short_uuid.0)
    }
}

// serialize into string
#[cfg(feature = "serde")]
impl serde::Serialize for ShortUuid {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let string = String::from_utf8(self.0.clone())
            .map_err(|e| serde::ser::Error::custom(e.to_string()))?;
        serializer.serialize_str(&string)
    }
}

// deserialize from string
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ShortUuid {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        Ok(ShortUuid(string.into_bytes()))
    }
}

// serialize into string
#[cfg(feature = "serde")]
impl serde::Serialize for ShortUuidCustom {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let string = String::from_utf8(self.0.clone())
            .map_err(|e| serde::ser::Error::custom(e.to_string()))?;
        serializer.serialize_str(&string)
    }
}

// deserialize from string
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ShortUuidCustom {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        Ok(ShortUuidCustom(string.into_bytes()))
    }
}

impl ShortUuid {
    /// Generate a short UUID v5 in flickrBase58
    pub fn generate() -> ShortUuid {
        generate_short(None)
    }

    /// Convert uuid to short format using flickrBase58
    pub fn from_uuid_str(uuid_string: &str) -> Result<ShortUuid, UuidError> {
        // validate
        let parsed = uuid::Uuid::parse_str(uuid_string)?;

        let cleaned = parsed.to_string().to_lowercase().replace("-", "");

        let converter = BaseConverter::default();

        // convert to selected base
        let result = converter.convert(&cleaned).unwrap();

        Ok(ShortUuid(result))
    }

    /// Convert uuid to short format using flickrBase58
    pub fn from_uuid(uuid: &uuid::Uuid) -> ShortUuid {
        let uuid_string = uuid.to_string();

        let cleaned = uuid_string.to_lowercase().replace("-", "");

        let converter = BaseConverter::default();

        // convert to selected base
        let result = converter.convert(&cleaned).unwrap();

        ShortUuid(result)
    }

    /// Convert short to uuid
    pub fn to_uuid(self) -> uuid::Uuid {
        // Convert to hex
        let to_hex_converter = BaseConverter::default();

        // Convert to hex string
        let result = to_hex_converter.convert_to_hex(&self.0).unwrap();

        // Format hex string as uuid
        format_uuid(result)
    }

    /// Convert short to uuid string to ShortUuid
    pub fn parse_str(short_uuid_str: &str) -> Result<Self, InvalidShortUuid> {
        let expected_len = 22;

        if short_uuid_str.len() != expected_len {
            return Err(InvalidShortUuid);
        };

        let byte_vector: Vec<u8> = short_uuid_str.as_bytes().to_vec();

        let to_hex_converter = BaseConverter::default();

        // Convert to hex string
        let result = to_hex_converter
            .convert_to_hex(&byte_vector)
            .map_err(|_| InvalidShortUuid)?;

        // validate
        uuid::Uuid::try_parse(&result).map_err(|_| InvalidShortUuid)?;

        Ok(Self(byte_vector))
    }

    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }
}

impl ShortUuidCustom {
    /// Generate a short UUID v4 in custom alphabet
    pub fn generate(translator: &CustomTranslator) -> Self {
        // Generate a short UUID v4 in custom alphabet
        let generated = generate_short(Some(&translator.as_slice()));
        let short_custom: ShortUuidCustom = generated.into();

        short_custom
    }

    /// Convert uuid to short format using custom alphabet
    pub fn from_uuid(uuid: &uuid::Uuid, translator: &CustomTranslator) -> Self {
        let uuid_string = uuid.to_string();

        let cleaned = uuid_string.to_lowercase().replace("-", "");

        // convert to selected base
        let result = translator.as_slice().convert(&cleaned).unwrap();

        Self(result)
    }

    /// Convert uuid string to short format using custom alphabet
    pub fn from_uuid_str(
        uuid_string: &str,
        translator: &CustomTranslator,
    ) -> Result<Self, ErrorKind> {
        // validate
        let parsed = uuid::Uuid::parse_str(uuid_string).map_err(|e| ErrorKind::UuidError(e))?;

        let cleaned = parsed.to_string().to_lowercase().replace("-", "");

        // convert to selected base
        let result = translator.as_slice().convert(&cleaned).unwrap();

        Ok(Self(result))
    }

    /// Convert short to uuid using custom base
    pub fn to_uuid(self, translator: &CustomTranslator) -> Result<uuid::Uuid, CustomAlphabetError> {
        // Convert to hex string
        // Should not fail
        let result = translator
            .as_slice()
            .convert_to_hex(&self.as_slice())
            .unwrap();

        // Format hex string as uuid
        let uuid_value = format_uuid(result);

        Ok(uuid_value)
    }

    /// Validate that short uuid str is valid uuid using custom alphabet
    pub fn parse_str(
        short_uuid_str: &str,
        translator: &CustomTranslator,
    ) -> Result<Self, InvalidShortUuid> {
        let byte_vector: Vec<u8> = short_uuid_str.as_bytes().to_vec();

        let result_string = translator
            .as_slice()
            .convert_to_hex(&byte_vector)
            .map_err(|_| InvalidShortUuid)?;

        // validate
        uuid::Uuid::try_parse(&result_string).map_err(|_| InvalidShortUuid)?;

        Ok(Self(byte_vector))
    }

    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }
}

fn generate_short(base_converter: Option<&BaseConverter>) -> ShortUuid {
    // Generate UUID v4
    let uuid_string = uuid::Uuid::new_v4().to_string();

    // clean string
    let cleaned = uuid_string.to_lowercase().replace("-", "");

    // convert to selected base
    let result = base_converter
        .unwrap_or(&BaseConverter::default())
        .convert(&cleaned)
        .unwrap();

    ShortUuid(result)
}

fn format_uuid(value: String) -> uuid::Uuid {
    let formatted_uuid = format!(
        "{}-{}-{}-{}-{}",
        &value[0..8],
        &value[8..12],
        &value[12..16],
        &value[16..20],
        &value[20..32]
    );

    // Should not fail
    let uuid = uuid::Uuid::parse_str(&formatted_uuid).unwrap();

    return uuid;
}

impl From<uuid::Uuid> for ShortUuid {
    fn from(uuid: uuid::Uuid) -> ShortUuid {
        ShortUuid::from_uuid(&uuid)
    }
}

impl From<ShortUuid> for uuid::Uuid {
    fn from(short_uuid: ShortUuid) -> uuid::Uuid {
        short_uuid.to_uuid()
    }
}