11 个版本
| 0.4.5 | 2023 年 1 月 2 日 |
|---|---|
| 0.4.4 | 2022 年 11 月 24 日 |
| 0.4.3 | 2022 年 10 月 11 日 |
| 0.4.0 | 2020 年 12 月 29 日 |
| 0.2.2 | 2019 年 10 月 4 日 |
#275 in 编码
4,711 个月的下载量
用于 9 个 crate(6 个直接使用)
60KB
1.5K SLoC
serde-hashkey
基于 Serde 的内存键序列化,支持散列。
这允许任何 serde-serializable 类型被转换为实现了 PartialEq、Eq、ParialOrd、Ord 和 Hash 的值。
Key 有用,因为它允许一种类型擦除的形式。假设你想构建一个通用的内存键值存储,其中你想存储任意的 serde-serializable 键。这对于缓存或依赖注入框架等事物很有用。
用法
将以下内容添加到你的 Cargo.toml
[dependencies]
serde-hashkey = "0.4.5"
浮点策略
默认情况下,Key 不能包含浮点类型,如 f32 和 f64。这两个都不是完全有序或可散列的。
要启用 Key 类型使用 f32 和 f64,它可以用特定的浮点策略来构建。
可用的浮点策略有
- RejectFloatPolicy - 使用 to_key 时的默认行为。
- OrderedFloat - 使用 to_key_with_ordered_float 时的行为。必须启用
ordered-float功能才能使用此功能。该行为来自ordered-floatcrate。
特性
ordered-float- 通过从ordered-float包 衍生的行为启用浮点数的序列化
示例
您可以使用以下命令运行此示例:
cargo run --example book
use std::collections::HashMap;
use serde_derive::{Deserialize, Serialize};
use serde_hashkey::{from_key, to_key, Error, Key};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Author {
name: String,
age: u32,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Book {
title: String,
author: Author,
}
let book = Book {
title: String::from("Birds of a feather"),
author: Author {
name: String::from("Noah"),
age: 42,
},
};
let key = to_key(&book)?;
let mut ratings = HashMap::new();
ratings.insert(key.clone(), 5);
println!("ratings: {:?}", ratings);
println!(
"book as json (through key): {}",
serde_json::to_string_pretty(&key)?
);
println!(
"book as json (through original object): {}",
serde_json::to_string_pretty(&book)?
);
依赖项
~110–405KB