| 1 | /*! |
| 2 | An implementation that provides unique string values. |
| 3 | |
| 4 | These string values are a fixed length and are generated as a representation of random UUID 128-bit |
| 5 | values. This implementation depends upon the [blob_uuid](https://crates.io/crates/blob-uuid) crate. |
| 6 | |
| 7 | # Example |
| 8 | |
| 9 | ```rust |
| 10 | use unique_id::{Generator, GeneratorWithInvalid}; |
| 11 | use unique_id::string::StringGenerator; |
| 12 | |
| 13 | let gen = StringGenerator::default(); |
| 14 | let id = gen.next_id(); |
| 15 | assert_ne!(id, StringGenerator::invalid_id()) |
| 16 | ``` |
| 17 | */ |
| 18 | |
| 19 | use crate::{Generator, GeneratorFromStr, GeneratorWithInvalid}; |
| 20 | |
| 21 | // ------------------------------------------------------------------------------------------------ |
| 22 | // Public Types |
| 23 | // ------------------------------------------------------------------------------------------------ |
| 24 | |
| 25 | /// |
| 26 | /// Generates random, unique string values from UUIDs. This implementation does provide an invalid |
| 27 | /// value, the empty string. |
| 28 | /// |
| 29 | /// Provides implementations of: |
| 30 | /// |
| 31 | /// * `Generator` - returns random `String` values. |
| 32 | /// * `GeneratorWithInvalid` - returns an invalid, as an ID, `String` value. |
| 33 | /// * `GeneratorFromStr` - ensures validity of a string representation as an `String` ID. |
| 34 | /// |
| 35 | #[derive(Clone, Debug, Default)] |
| 36 | pub struct StringGenerator; |
| 37 | |
| 38 | // ------------------------------------------------------------------------------------------------ |
| 39 | // Implementations |
| 40 | // ------------------------------------------------------------------------------------------------ |
| 41 | |
| 42 | impl Generator<String> for StringGenerator { |
| 43 | #[inline] |
| 44 | fn next_id(&self) -> String { |
| 45 | blob_uuid::random_blob() |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl GeneratorWithInvalid<String> for StringGenerator { |
| 50 | #[inline] |
| 51 | fn invalid_id() -> String |
| 52 | where |
| 53 | Self: Sized, |
| 54 | { |
| 55 | String::new() |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl GeneratorFromStr<String> for StringGenerator { |
| 60 | fn is_valid_value(s: &str) -> bool { |
| 61 | !s.is_empty() |
| 62 | && s.chars() |
| 63 | .all(|c| c.is_alphanumeric() || c == '-' || c == '_') |
| 64 | } |
| 65 | } |