Crate compact_map

source ·
Expand description

Small map in various sizes. These store a certain number of entries inline, and fall back to a HashMap for larger allocations.

Provides (almost) 1:1 API compatibility with HashMap.

§Examples

use compact_map::CompactMap;

// Type inference lets us omit an explicit type signature except for the capacity
// (which would be `CompactMap<String, String, N>` in this example).
// Also with default capacity of 16.
let mut book_reviews = CompactMap::default();

// Review some books.
book_reviews.insert(
    "Adventures of Huckleberry Finn".to_string(),
    "My favorite book.".to_string(),
);
book_reviews.insert(
    "Grimms' Fairy Tales".to_string(),
    "Masterpiece.".to_string(),
);
book_reviews.insert(
    "Pride and Prejudice".to_string(),
    "Very enjoyable.".to_string(),
);
book_reviews.insert(
    "The Adventures of Sherlock Holmes".to_string(),
    "Eye lyked it alot.".to_string(),
);

// Check for a specific one.
// When collections store owned values (String), they can still be
// queried using references (&str).
if !book_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             book_reviews.len());
}

// oops, this review has a lot of spelling mistakes, let's delete it.
book_reviews.remove("The Adventures of Sherlock Holmes");

// Look up the values associated with some keys.
let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
for &book in &to_find {
    match book_reviews.get(book) {
        Some(review) => println!("{book}: {review}"),
        None => println!("{book} is unreviewed.")
    }
}

// Look up the value for a key (will panic if the key is not found).
println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);

// Iterate over everything.
for (book, review) in &book_reviews {
    println!("{book}: \"{review}\"");
}

A CompactMap with a known list of items can be initialized from an array:

use compact_map::CompactMap;

// You need to specify the size of the map.
let solar_distance = CompactMap::<_, _, 4>::from([
    ("Mercury", 0.4),
    ("Venus", 0.7),
    ("Earth", 1.0),
    ("Mars", 1.5),
]);

CompactMap implements an Entry API, which allows for complex methods of getting, setting, updating and removing keys and their values:

use compact_map::CompactMap;

// type inference lets us omit an explicit type signature except for the capacity
// (which would be `CompactMap<&str, u8, N>` in this example).
let mut player_stats = CompactMap::<_, _, 5>::new();

fn random_stat_buff() -> u8 {
    // could actually return some random value here - let's just return
    // some fixed value for now
    42
}

// insert a key only if it doesn't already exist
player_stats.entry("health").or_insert(100);

// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry("defence").or_insert_with(random_stat_buff);

// update a key, guarding against the key possibly not being set
let stat = player_stats.entry("attack").or_insert(100);
*stat += random_stat_buff();

// modify an entry before an insert with in-place mutation
player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);

§Optional Features

§map_entry_replace

This feature is unstable and requires a nightly build of the Rust toolchain.

This feature enables the map_entry_replace feature gate.

This feature enables the OccupiedEntry::replace_entry method, it makes operations that would otherwise require two look-ups into operations that require only one.

Tracking issue: rust-lang/rust#44286

§extract_if

This feature is unstable and requires a nightly build of the Rust toolchain.

This feature enables the hash_extract_if feature gate.

This feature enables the CompactMap::extract_if method, provides a draining, filtering iterator over the entries of a Map.

Tracking issue: rust-lang/rust#59618

§entry_insert

This feature is unstable and requires a nightly build of the Rust toolchain.

This feature enables the entry_insert feature gate.

This feature enables the Entry::insert_entry method.

Tracking issue: rust-lang/rust#65225

§map_try_insert

This feature is unstable and requires a nightly build of the Rust toolchain.

This feature enables the map_try_insert feature gate.

This feature enables the CompactMap::try_insert method.

Tracking issue: rust-lang/rust#82766

§many_mut

This feature is unstable and requires a nightly build of the Rust toolchain.

This feature enables the map_many_mut, get_many_mut feature gate.

This feature enables the CompactMap::get_many_mut, CompactMap::get_many_unchecked_mut methods.

Tracking issue:

Structs§

  • A map that inlines entries to avoid heap allocations for small maps.
  • A draining iterator over the entries of a CompactMap.
  • ExtractIfextract_if
    A draining, filtering iterator over the entries of a CompactMap.
  • An owning iterator over the entries of a CompactMap.
  • An owning iterator over the keys of a CompactMap.
  • An owning iterator over the values of a CompactMap.
  • An iterator over the entries of a CompactMap.
  • A mutable iterator over the entries of a CompactMap.
  • An iterator over the keys of a CompactMap.
  • The error returned by try_insert when the key already exists.
  • The error type for try_reserve methods.
  • An iterator over the values of a CompactMap.
  • A mutable iterator over the values of a CompactMap.

Enums§

  • A view into a single entry in a map, which may either be vacant or occupied.
  • A view into an occupied entry in a CompactMap. It is part of the Entry enum.
  • A view into a vacant entry in a CompactMap. It is part of the Entry enum.