typeid_prefix 1.2.0-alpha

A Rust library that implements a type-safe version of the TypePrefix section of the `TypeID` Specification
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![allow(clippy::module_name_repetitions)]
#![cfg_attr(docsrs, feature(doc_cfg))]
//! # `TypeID` Prefix
//!
//! This crate provides a type-safe implementation of the `TypePrefix` section of the
//! [TypeID Specification](https://github.com/jetpack-io/typeid).
//!
//! The main type provided by this crate is [`TypeIdPrefix`], which represents a valid
//! `TypeID` prefix. This type ensures that all instances conform to the `TypeID` specification:
//!
//! - Maximum length of 63 characters
//! - Contains only lowercase ASCII letters and underscores
//! - Does not start or end with an underscore
//! - Starts and ends with a lowercase letter
//!
//! ## Features
//!
//! - **Type-safe**: Ensures that `TypeID` prefixes conform to the specification.
//! - **Validation**: Provides robust validation for `TypeID` prefixes.
//! - **Sanitization**: Offers methods to clean and sanitize input strings into valid `TypeID` prefixes.
//! - **Zero-cost abstractions**: Designed to have minimal runtime overhead.
//! - **Optional tracing**: Integrates with the `tracing` crate for logging (optional feature).
//!
//! ## Usage
//!
//! ```rust
//! use typeid_prefix::{TypeIdPrefix, Sanitize};
//! use std::convert::TryFrom;
//!
//! // Create a TypeIdPrefix from a valid string
//! let prefix = TypeIdPrefix::try_from("user").unwrap();
//! assert_eq!(prefix.as_str(), "user");
//!
//! // Attempt to create from an invalid string
//! let result = TypeIdPrefix::try_from("Invalid_Prefix");
//! assert!(result.is_err());
//!
//! // Sanitize an invalid string
//! let sanitized = "Invalid_Prefix123".create_prefix_sanitized();
//! assert_eq!(sanitized.as_str(), "invalid_prefix");
//! ```
//!
//! ## Optional Tracing
//!
//! When the `instrument` feature is enabled, the crate will log validation errors
//! using the `tracing` crate.

use std::cmp::PartialEq;
use std::convert::TryFrom;
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;

#[cfg(feature = "instrument")]
use tracing;

pub use crate::error::ValidationError;

mod error;

pub mod prelude {
    //! A prelude for the `TypeID` prefix crate.
    //!
    //! This module contains the most commonly used items from the crate.
    //!
    //! # Usage
    //!
    //! ```
    //! use typeid_prefix::prelude::*;
    //! ```

    pub use crate::{Sanitize, TypeIdPrefix, Validate, ValidationError};
}

/// Represents a valid `TypeID` prefix as defined by the `TypeID` specification.
///
/// A `TypeIdPrefix` is guaranteed to:
/// - Have a maximum length of 63 characters
/// - Contain only lowercase ASCII letters and underscores
/// - Not start or end with an underscore
/// - Start and end with a lowercase letter
///
/// # Examples
///
/// ```
/// use typeid_prefix::TypeIdPrefix;
/// use std::convert::TryFrom;
///
/// let prefix = TypeIdPrefix::try_from("valid_prefix").unwrap();
/// assert_eq!(prefix.as_str(), "valid_prefix");
///
/// let invalid = TypeIdPrefix::try_from("Invalid_Prefix");
/// assert!(invalid.is_err());
/// ```
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct TypeIdPrefix(String);

/// A trait for sanitizing and creating a valid `TypeIdPrefix` from a given input.
///
/// This trait is implemented for any type that can be converted to a string slice (`AsRef<str>`).
/// It provides a method to clean and create a valid `TypeIdPrefix`, even from invalid input.
///
/// # Examples
///
/// ```
/// use typeid_prefix::Sanitize;
///
/// let sanitized = "Invalid String 123!@#".create_prefix_sanitized();
/// assert_eq!(sanitized.as_str(), "invalidstring");
/// ```
pub trait Sanitize {
    /// Sanitizes the input and creates a valid `TypeIdPrefix`.
    ///
    /// This method will modify the input to conform to the `TypeID` specification by:
    /// - Removing invalid characters
    /// - Converting all characters to lowercase
    /// - Truncating to the maximum allowed length if necessary
    /// - Ensuring the result starts and ends with a lowercase alphabetic character
    ///
    /// # Examples
    ///
    /// ```
    /// use typeid_prefix::prelude::*;
    ///
    /// let valid_input = "User123";
    /// let prefix = valid_input.create_prefix_sanitized();
    /// assert_eq!(prefix.as_str(), "user");
    ///
    /// let invalid_input = "123_USER_456";
    /// let prefix = invalid_input.create_prefix_sanitized();
    /// assert_eq!(prefix.as_str(), "user");
    ///
    /// let empty_input = "123";
    /// let prefix = empty_input.create_prefix_sanitized();
    /// assert_eq!(prefix.as_str(), "");
    /// ```
    ///
    /// # Return Value
    ///
    /// - If the input can be sanitized into a valid prefix, returns a `TypeIdPrefix` containing the sanitized value.
    /// - If the input is invalid and cannot be sanitized into a valid prefix (e.g., contains no valid characters),
    ///   returns an empty `TypeIdPrefix`.
    ///
    /// # Note
    ///
    /// This method will always return a `TypeIdPrefix`, even if it's empty. If you need to ensure
    /// the input is valid without modification, use `try_create_prefix` instead.
    fn create_prefix_sanitized(&self) -> TypeIdPrefix
    where
        Self: AsRef<str>;

    /// Attempts to create a `TypeIdPrefix` from the input without modifying it.
    ///
    /// This method validates the input according to the `TypeID` specification
    /// and returns a `Result` containing either the valid `TypeIdPrefix` or a
    /// `ValidationError` describing why the input is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use typeid_prefix::prelude::*;
    ///
    /// let valid_input = "user";
    /// assert!(valid_input.try_create_prefix().is_ok());
    ///
    /// let invalid_input = "User123";
    /// assert!(invalid_input.try_create_prefix().is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// This method will return a `ValidationError` if the input does not meet
    /// the requirements of a valid TypeID prefix. Possible error conditions include:
    ///
    /// - The input exceeds the maximum allowed length of 63 characters.
    /// - The input contains characters other than lowercase ASCII letters and underscores.
    /// - The input starts or ends with an underscore.
    /// - The input does not start or end with a lowercase alphabetic character.
    ///
    /// For more details on specific error conditions, see the `ValidationError` enum.
    ///
    /// # Note
    ///
    /// Unlike `create_prefix_sanitized`, this method does not modify the input.
    /// If you need to automatically correct invalid inputs, use `create_prefix_sanitized` instead.
    fn try_create_prefix(&self) -> Result<TypeIdPrefix, ValidationError>
    where
        Self: AsRef<str>;
}
/// A marker trait for types that can be validated as a `TypeID` prefix.
///
/// This trait is automatically implemented for any type that implements
/// `AsRef<str>` and can be converted to a `TypeIdPrefix` using `TryFrom`.
pub trait Validate {}

impl<T> Validate for T
where
    T: AsRef<str> + TryFrom<T, Error=ValidationError>,
{}


#[allow(unused_variables)]
impl<T> Sanitize for T
where
    T: AsRef<str>,
{
    fn create_prefix_sanitized(&self) -> TypeIdPrefix {
        let input = TypeIdPrefix::clean_inner(self.as_ref());
        TypeIdPrefix::validate(&input).unwrap_or_else(|e| {
            #[cfg(feature = "instrument")]
            tracing::warn!("Invalid TypeIdPrefix: {:?}. Using empty string instead.", e);
            TypeIdPrefix(String::new())
        })
    }
    fn try_create_prefix(&self) -> Result<TypeIdPrefix, ValidationError> {
        TypeIdPrefix::from_str(self.as_ref())
    }
}

impl Deref for TypeIdPrefix {
    type Target = String;

    fn deref(&self) -> &String {
        &self.0
    }
}

impl PartialEq<String> for TypeIdPrefix {
    fn eq(&self, other: &String) -> bool {
        &self.0 == other
    }
}

impl PartialEq<TypeIdPrefix> for String {
    fn eq(&self, other: &TypeIdPrefix) -> bool {
        self == &other.0
    }
}

// You can also implement PartialEq<&str> if needed
impl PartialEq<&str> for TypeIdPrefix {
    fn eq(&self, other: &&str) -> bool {
        &self.0 == other
    }
}

impl PartialEq<TypeIdPrefix> for &str {
    fn eq(&self, other: &TypeIdPrefix) -> bool {
        self == &other.0
    }
}

/// Implements the `FromStr` trait for `TypeIdPrefix`.
///
/// This implementation allows creating a `TypeIdPrefix` from a string slice,
/// validating the input according to the TypeID specification.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use typeid_prefix::TypeIdPrefix;
///
/// let valid_prefix = TypeIdPrefix::from_str("user").expect("Valid prefix");
/// assert_eq!(valid_prefix.as_str(), "user");
///
/// let invalid_prefix = TypeIdPrefix::from_str("123");
/// assert!(invalid_prefix.is_err());
/// ```
///
/// # Errors
///
/// This method will return a `ValidationError` if the input string does not meet
/// the requirements of a valid TypeID prefix. Possible error conditions include:
///
/// - The input exceeds the maximum allowed length of 63 characters.
/// - The input contains characters other than lowercase ASCII letters and underscores.
/// - The input starts or ends with an underscore.
/// - The input does not start or end with a lowercase alphabetic character.
///
/// For more details on error conditions, see the `ValidationError` enum.
impl FromStr for TypeIdPrefix {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::validate(s)
    }
}
impl TryFrom<String> for TypeIdPrefix
{
    type Error = ValidationError;

    /// Attempts to create a `TypeIdPrefix` from a `String`.
    ///
    /// # Errors
    ///
    /// Returns a `ValidationError` if the input string is not a valid `TypeID` prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use typeid_prefix::TypeIdPrefix;
    /// use std::convert::TryFrom;
    ///
    /// let valid = TypeIdPrefix::try_from("valid_prefix".to_string()).unwrap();
    /// assert_eq!(valid.as_str(), "valid_prefix");
    ///
    /// let invalid = TypeIdPrefix::try_from("Invalid_Prefix".to_string());
    /// assert!(invalid.is_err());
    /// ```
    fn try_from(input: String) -> Result<Self, Self::Error> {
        Self::validate(input.as_ref())
    }
}

impl TryFrom<&str> for TypeIdPrefix
{
    type Error = ValidationError;

    /// Attempts to create a `TypeIdPrefix` from a string slice.
    ///
    /// # Errors
    ///
    /// Returns a `ValidationError` if the input string is not a valid `TypeID` prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use typeid_prefix::TypeIdPrefix;
    /// use std::convert::TryFrom;
    ///
    /// let valid = TypeIdPrefix::try_from("valid_prefix").unwrap();
    /// assert_eq!(valid.as_str(), "valid_prefix");
    ///
    /// let invalid = TypeIdPrefix::try_from("Invalid_Prefix");
    /// assert!(invalid.is_err());
    /// ```
    fn try_from(input: &str) -> Result<Self, Self::Error> {
        Self::validate(input)
    }
}


impl TypeIdPrefix {
    fn validate(input: &str) -> Result<Self, ValidationError> {
        if input.len() > 63 {
            return Err(ValidationError::ExceedsMaxLength);
        }

        if input.is_empty() {
            return Ok(Self(input.to_string()));
        }

        if !input.is_ascii() {
            return Err(ValidationError::ContainsInvalidCharacters);
        }

        if input.starts_with('_') {
            return Err(ValidationError::StartsWithUnderscore);
        }

        if input.ends_with('_') {
            return Err(ValidationError::EndsWithUnderscore);
        }

        if !input.starts_with(|c: char| c.is_ascii_lowercase()) {
            return Err(ValidationError::InvalidStartCharacter);
        }

        if !input.ends_with(|c: char| c.is_ascii_lowercase()) {
            return Err(ValidationError::InvalidEndCharacter);
        }

        if !input.chars().all(|c| c.is_ascii_lowercase() || c == '_') {
            return Err(ValidationError::ContainsInvalidCharacters);
        }

        Ok(Self(input.to_string()))
    }

    fn clean_inner(input: &str) -> String {
        let mut result = input.to_string();
        result = result.to_lowercase();
        // Safely truncate to 63 characters if necessary
        if result.len() > 63 {
            result = result.chars().take(63).collect();
        }

        result = result.to_ascii_lowercase().chars()
            .filter(|&c| (c.is_ascii_lowercase() || c == '_') && c.is_ascii())
            .collect::<String>();

        // Remove leading and trailing underscores
        while result.starts_with('_') {
            result.remove(0);
        }

        while result.ends_with('_') {
            result.pop();
        }

        result
    }

    /// Returns a string slice of the `TypeID` prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use typeid_prefix::TypeIdPrefix;
    /// use std::convert::TryFrom;
    ///
    /// let prefix = TypeIdPrefix::try_from("valid_prefix").unwrap();
    /// assert_eq!(prefix.as_str(), "valid_prefix");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}


impl fmt::Display for TypeIdPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryFrom;

    use super::*;

    #[test]
    fn test_type_id_spaces_sanitize() {
        assert_eq!(
            "Invalid String with Spaces!!__".create_prefix_sanitized().as_str(),
            "invalidstringwithspaces"
        );
    }

    #[test]
    fn test_type_id_truncation() {
        assert_eq!(
            "A_valid_string_that_is_way_too_long_and_should_be_truncated_to_63_chars".create_prefix_sanitized().as_str(),
            "a_valid_string_that_is_way_too_long_and_should_be_truncated_to"
        );
    }

    #[test]
    fn test_type_id_underscores_sanitize() {
        assert_eq!(
            "_underscores__everywhere__".create_prefix_sanitized().as_str(),
            "underscores__everywhere"
        );
    }

    #[test]
    fn test_typeid_prefix_non_ascii() {
        assert!(TypeIdPrefix::try_from("🌀").is_err());
        let sanitized_input = "🌀".create_prefix_sanitized();
        assert!(sanitized_input.as_str().is_empty(), "Prefix was not empty: {sanitized_input}");
    }

    #[test]
    fn test_typeid_prefix_empty() {
        assert!(TypeIdPrefix::try_from("").is_ok());
    }

    #[test]
    fn test_typeid_prefix_single_char() {
        assert!(TypeIdPrefix::try_from("a").is_ok());
    }

    #[test]
    fn test_typeid_prefix_valid_string() {
        assert!(TypeIdPrefix::try_from("valid_string").is_ok());
    }

    #[test]
    fn test_typeid_prefix_with_underscores() {
        assert!(TypeIdPrefix::try_from("valid_string_with_underscores").is_ok());
    }

    #[test]
    fn test_typeid_prefix_exceeds_max_length() {
        let input = "a_valid_string_with_underscores_and_length_of_63_characters_____";
        assert_eq!(
            TypeIdPrefix::try_from(input).unwrap_err(),
            ValidationError::ExceedsMaxLength
        );
        assert_eq!(
            input.create_prefix_sanitized().as_str(),
            "a_valid_string_with_underscores_and_length_of__characters"
        );
    }

    #[test]
    fn test_typeid_prefix_invalid_characters() {
        assert_eq!(
            TypeIdPrefix::try_from("InvalidString").unwrap_err(),
            ValidationError::InvalidStartCharacter
        );
        assert_eq!("InvalidString".create_prefix_sanitized().as_str(), "invalidstring");
    }

    #[test]
    fn test_typeid_prefix_starts_with_underscore() {
        assert_eq!(
            TypeIdPrefix::try_from("_invalid").unwrap_err(),
            ValidationError::StartsWithUnderscore
        );
        assert_eq!("_invalid".create_prefix_sanitized().as_str(), "invalid");
    }

    #[test]
    fn test_typeid_prefix_ends_with_underscore() {
        assert_eq!(
            TypeIdPrefix::try_from("invalid_").unwrap_err(),
            ValidationError::EndsWithUnderscore
        );
        assert_eq!("invalid_".create_prefix_sanitized().as_str(), "invalid");
    }

    #[test]
    fn test_typeid_prefix_invalid_characters_with_spaces() {
        assert_eq!(
            TypeIdPrefix::try_from("invalid string with spaces").unwrap_err(),
            ValidationError::ContainsInvalidCharacters
        );
        assert_eq!("invalid string with spaces".create_prefix_sanitized().as_str(), "invalidstringwithspaces");
    }

    #[test]
    fn test_typeid_prefix_max_length() {
        let input = "a".repeat(63);
        assert!(TypeIdPrefix::try_from(input.as_str()).is_ok());
    }

    #[test]
    fn test_typeid_prefix_max_length_exceeded() {
        let input = "a".repeat(64);
        assert_eq!(
            TypeIdPrefix::try_from(input.as_str()).unwrap_err(),
            ValidationError::ExceedsMaxLength
        );
        assert_eq!(input.create_prefix_sanitized().as_str(), "a".repeat(63));
    }

    #[test]
    fn test_typeid_prefix_contains_uppercase() {
        assert_eq!(
            TypeIdPrefix::try_from("InvalidString").unwrap_err(),
            ValidationError::InvalidStartCharacter
        );
        assert_eq!("InvalidString".create_prefix_sanitized().as_str(), "invalidstring");
    }

    #[test]
    fn test_typeid_prefix_non_alphanumeric() {
        assert_eq!(
            TypeIdPrefix::try_from("invalid_string!").unwrap_err(),
            ValidationError::InvalidEndCharacter
        );
        assert_eq!("invalid_string!".create_prefix_sanitized().as_str(), "invalid_string");
    }

    #[test]
    fn test_typeid_prefix_numeric_start() {
        assert_eq!(
            TypeIdPrefix::try_from("1invalid").unwrap_err(),
            ValidationError::InvalidStartCharacter
        );
        assert_eq!("1invalid".create_prefix_sanitized().as_str(), "invalid");
    }

    #[test]
    fn test_typeid_prefix_numeric_end() {
        assert_eq!(
            TypeIdPrefix::try_from("invalid1").unwrap_err(),
            ValidationError::InvalidEndCharacter
        );
        assert_eq!("invalid1".create_prefix_sanitized().as_str(), "invalid");
    }
}