This repository was archived by the owner on Nov 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
Provide a SmolStr with a lifetime #95
Copy link
Copy link
Open
Description
Provide a SmolStr<'a> type, which is implemented exactly the same as the current one. The only difference is that all functions converting from &'static str will become converting from &'a str, resulting in a 'a lifetime, while other cases result in a 'static lifetime. This makes it more flexible to use.
Use case 1: Implement from_utf8_lossy for SmolStr.
fn smolstr_from_utf8_lossy(v: &[u8]) -> SmolStr<'_> {
// Simplified pseudocode
if let Some(s) = v as valid utf-8 &str {
SmolStr::from_str(s)
} else {
let mut res = SmolStrBuilder::new();
build result string
res.finish().as_static_lifetime()
}
}Use case 2: Serialization / Deserialization
#[derive(Serialize, Deserialize)]
struct Data<'a> {
field: SmolStr<'a>,
}
// Serialize: field can be a borrow of a certain lifetime.
fn serialize(field: &str) -> String {
serde_json::to_string(&Data { field: SmolStr::from_str(field) })
}
// Deserialize: get static lifetime, an inline or heap-allocated SmolStr underneath
fn deserialize(json: &str) -> serde_json::Result<Data<'static>> {
serde_json::from_str(json)
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels