Skip to main content

docsrs_cli/domain/
crate_name.rs

1//! Validated crates.io / stdlib crate name.
2
3use std::fmt;
4use std::str::FromStr;
5use std::sync::LazyLock;
6
7use regex::Regex;
8
9use crate::config::MAX_CRATE_NAME_CHARS;
10use crate::error::{AppError, AppResult, ErrorDetail, Subject};
11
12use super::regex::compile_bounded_regex;
13
14/// Canonical stdlib crate names documented on `doc.rust-lang.org` (single source).
15pub(crate) const STDLIB_NAMES: &[&str] = &["std", "core", "alloc"];
16
17/// True when `name` is a Rust standard library crate (`std` / `core` / `alloc`).
18///
19/// Accepts raw strings for HTML scrape / allowlist helpers. Prefer
20/// [`CrateName::is_stdlib`] when a validated name is already in hand.
21#[must_use]
22pub fn is_stdlib_name(name: &str) -> bool {
23    STDLIB_NAMES.contains(&name)
24}
25
26/// Validated crates.io / stdlib crate name.
27#[repr(transparent)]
28#[derive(Debug, Clone, PartialEq, Eq, Hash)]
29pub struct CrateName(String);
30
31impl CrateName {
32    /// Parses and validates a crate name (trim, length, charset).
33    ///
34    /// # Errors
35    ///
36    /// Returns [`crate::error::ErrorKind::InvalidInput`] when the name is empty, too long, or
37    /// contains characters outside the crates.io charset.
38    ///
39    /// # Panics
40    ///
41    /// Panics only if the hardcoded crate-name regex fails to compile inside its
42    /// [`std::sync::LazyLock`]. The pattern is a compile-time literal well under
43    /// the bounded `size_limit` / `dfa_size_limit`, so no runtime input can reach
44    /// this path.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use docsrs_cli::domain::CrateName;
50    ///
51    /// let name = CrateName::parse("tokio").expect("valid");
52    /// assert_eq!(name.as_str(), "tokio");
53    /// assert!(CrateName::parse("").is_err());
54    /// ```
55    pub fn parse(name: &str) -> AppResult<Self> {
56        let name = name.trim();
57        if name.is_empty() {
58            return Err(AppError::of(ErrorDetail::Empty {
59                subject: Subject::CrateName,
60            }));
61        }
62        if name.chars().count() > MAX_CRATE_NAME_CHARS {
63            return Err(AppError::of(ErrorDetail::TooLong {
64                subject: Subject::CrateName,
65                limit: MAX_CRATE_NAME_CHARS,
66            }));
67        }
68        static RE: LazyLock<Regex> = LazyLock::new(|| {
69            compile_bounded_regex(r"^[a-zA-Z][a-zA-Z0-9_-]*$")
70                .expect("hardcoded crate-name regex is valid by construction")
71        });
72        if !RE.is_match(name) {
73            return Err(AppError::of(ErrorDetail::Invalid {
74                subject: Subject::CrateName,
75                value: name.to_string(),
76            }));
77        }
78        Ok(Self(name.to_string()))
79    }
80
81    /// Borrow the validated name.
82    #[must_use]
83    pub fn as_str(&self) -> &str {
84        &self.0
85    }
86
87    /// True for `std` / `core` / `alloc` (docs on doc.rust-lang.org).
88    #[must_use]
89    pub fn is_stdlib(&self) -> bool {
90        is_stdlib_name(self.as_str())
91    }
92}
93
94impl AsRef<str> for CrateName {
95    fn as_ref(&self) -> &str {
96        self.as_str()
97    }
98}
99
100impl fmt::Display for CrateName {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        f.write_str(self.as_str())
103    }
104}
105
106impl FromStr for CrateName {
107    type Err = AppError;
108
109    /// Parses via [`CrateName::parse`].
110    ///
111    /// # Errors
112    ///
113    /// Returns [`crate::error::ErrorKind::InvalidInput`] for empty, oversized, or illegal names.
114    fn from_str(s: &str) -> Result<Self, Self::Err> {
115        Self::parse(s)
116    }
117}
118
119impl TryFrom<&str> for CrateName {
120    type Error = AppError;
121
122    /// Converts via [`CrateName::parse`].
123    ///
124    /// # Errors
125    ///
126    /// Returns [`crate::error::ErrorKind::InvalidInput`] for empty, oversized, or illegal names.
127    fn try_from(value: &str) -> Result<Self, Self::Error> {
128        Self::parse(value)
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use std::mem::size_of;
136
137    #[test]
138    fn crate_name_ok_and_stdlib() {
139        let s = CrateName::parse("serde").unwrap();
140        assert_eq!(s.as_str(), "serde");
141        assert!(!s.is_stdlib());
142        assert!(CrateName::parse("async-trait").unwrap().as_str() == "async-trait");
143        for n in STDLIB_NAMES {
144            let c = CrateName::parse(n).unwrap();
145            assert!(c.is_stdlib(), "{n}");
146            assert!(is_stdlib_name(n));
147        }
148        assert!(!is_stdlib_name("serde"));
149    }
150
151    #[test]
152    fn crate_name_err() {
153        assert!(CrateName::parse("").is_err());
154        assert!(CrateName::parse("1bad").is_err());
155        assert!(CrateName::parse(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
156    }
157
158    #[test]
159    fn crate_name_transparent_layout() {
160        assert_eq!(size_of::<CrateName>(), size_of::<String>());
161    }
162}