Skip to content

A design for single-pass borrowed insert_if_not_there #93

Closed
@CAD97

Description

@CAD97

I have an IndexSet<String> that I want to be able to insert or get index from &str without allocating needlessly if the value is already in the set.

This is actually possible with one small library addition: entry_index. It would return an entry for the value at the index up to and including .len(), thus allowing insertion of the value there. It wouldn't even need to be unsafe: having two keys that compare equal in the map is only very bad for domain correctness, but not for memory correctness if I understand correctly.

It could then be used for inserting if not present with something like the following:

set.get(&key)
    .unwrap_or_else(|| set.entry_index(set.len)
        .insert(key.to_owned())

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