Skip to content
This repository was archived by the owner on Nov 9, 2025. It is now read-only.
This repository was archived by the owner on Nov 9, 2025. It is now read-only.

Provide a SmolStr with a lifetime #95

@Jason5Lee

Description

@Jason5Lee

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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions