Skip to content

Use small string for index name type #12355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions crates/uv-distribution-types/src/index_name.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
use std::borrow::Cow;
use std::ops::Deref;
use std::str::FromStr;

use thiserror::Error;

use uv_small_str::SmallString;

/// The normalized name of an index.
///
/// Index names may contain letters, digits, hyphens, underscores, and periods, and must be ASCII.
#[derive(Debug, Clone, Hash, Eq, PartialEq, serde::Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct IndexName(String);
pub struct IndexName(SmallString);

impl IndexName {
/// Validates the given index name and returns [`IndexName`] if it's valid, or an error
/// otherwise.
pub fn new(name: String) -> Result<Self, IndexNameError> {
pub fn new(name: &str) -> Result<Self, IndexNameError> {
for c in name.chars() {
match c {
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => {}
c if c.is_ascii() => {
return Err(IndexNameError::UnsupportedCharacter(c, name));
return Err(IndexNameError::UnsupportedCharacter(c, name.to_string()));
}
c => {
return Err(IndexNameError::NonAsciiName(c, name));
return Err(IndexNameError::NonAsciiName(c, name.to_string()));
}
}
}
Ok(Self(name))
Ok(Self(SmallString::from(name)))
}

/// Converts the index name to an environment variable name.
Expand All @@ -49,7 +52,7 @@ impl FromStr for IndexName {
type Err = IndexNameError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s.to_string())
Self::new(s)
}
}

Expand All @@ -58,8 +61,8 @@ impl<'de> serde::de::Deserialize<'de> for IndexName {
where
D: serde::de::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
IndexName::new(s).map_err(serde::de::Error::custom)
let s = Cow::<'_, str>::deserialize(deserializer)?;
IndexName::new(&s).map_err(serde::de::Error::custom)
}
}

Expand Down
Loading