serde-hashkey

github crates.io docs.rs build status

Serde-based in-memory key serialization which supports hashing.

This allows any serde-serializable type to be converted into a value which implements PartialEq, Eq, ParialOrd, Ord, and Hash.

[Key] is useful because it allows for a form of type-erasure. Let's say you want to build a generic in-memory key-value store where you want to store arbitrary serde-serializable keys. This is typical for things like caches or dependency injection frameworks.

Float policies

By default, [Key] can't include floating point types such as f32 and f64. Neither of these are [totally ordered nor hashable].

To enable the [Key] type to use f32 and f64 it can be constructed with a specific float policy.

Available float policies are: * [RejectFloat] - the default behavior when using [tokey]. * [OrderedFloat] - the behavior when using [tokeywithordered_float]. The ordered-float feature must be enabled to use this. The behavior is derived from the [ordered-float crate].

Features

Examples

You can run this example with cargo run --example book

```rust use serdederive::{Deserialize, Serialize}; use serdehashkey::{fromkey, tokey, Error, Key}; use std::{collections::HashMap, error};

[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]

struct Author { name: String, age: u32, }

[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]

struct Book { title: String, author: Author, }

fn main() -> Result<(), Box> { 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)?
);

Ok(())

} ```

License: MIT/Apache-2.0