#key-value #hash-map #btree-map #pattern #key-hash #key-value-store #collection

automap

实现包含键类型的值类型的键值映射的简单模式

1 个不稳定版本

0.1.0 2021年2月26日

2170数据结构

Download history 547/week @ 2024-03-14 835/week @ 2024-03-21 425/week @ 2024-03-28 680/week @ 2024-04-04 730/week @ 2024-04-11 670/week @ 2024-04-18 1064/week @ 2024-04-25 743/week @ 2024-05-02 548/week @ 2024-05-09 841/week @ 2024-05-16 857/week @ 2024-05-23 1154/week @ 2024-05-30 765/week @ 2024-06-06 811/week @ 2024-06-13 746/week @ 2024-06-20 481/week @ 2024-06-27

3,006 每月下载次数
27 个crates中使用(通过 holochain_types

Apache-2.0

11KB
131 代码行

automap

实现包含键类型的值类型的键值映射的简单模式。提供从 std::collections 中的 HashMapBTreeMap 的实现。

示例

use std::collections::HashMap;
use automap::{AutoHashMap, AutoMapped};

// Let's say we want a `Person` to be keyed by their `name` in a HashMap
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Person {
    name: String,
    age: u16,
}

// We can specify how to derive the key from the value
// As long as the Key type meets the bounds for a normal HashMap key, we
// can use this value in an AutoHashMap.
// (Similarly for BTreeMap.)
impl AutoMapped for Person {
    type Key = String;

    fn key(&self) -> &Self::Key {
        &self.name
    }
}

// Then, we can simply use an `AutoHashMap` to insert values directly.
let mut map = AutoHashMap::new();
let michelle = Person { name: "Michelle".into(), age: 37 };
// We don't need to provide the key, because it is derived from the value.
map.insert(michelle.clone());

// You can access all other normal HashMap methods directly:
assert_eq!(map.get("Michelle".into()), Some(&michelle));
assert_eq!(map.remove("Michelle".into()), Some(michelle));

// We can also go From and Into a normal HashMap easily.
let inner: HashMap<_, _> = map.into();
let map: AutoHashMap<_> = inner.into();

Serde支持

在依赖项中设置 serde 功能以包含反序列化支持。

未来改进

  • 避免克隆键:理想情况下,键将从值中借用,但在同时提供serde反序列化的情况下,这不是立即显而易见的。也许可以编写一个定制的数据结构,而不是依赖于 std::collections
    • 这也可以通过一个过程宏来实现,该宏将目标结构分割成键部分和其余部分,这样键就只存储一次,同时仍然使用标准的Map。
  • 允许值类型有多个 Automapped 实现,指定不同情况下不同的键

依赖项

~2MB
~48K SLoC