#serde #serialization

serde-hashkey

Space efficient, in-memory serde serialization which supports hashing

8 unstable releases (3 breaking)

0.4.0 Dec 29, 2020
0.3.0 Nov 25, 2020
0.2.4 Nov 18, 2020
0.2.2 Oct 4, 2019
0.1.0 Aug 1, 2019

#108 in Encoding

Download history 126/week @ 2021-01-20 16/week @ 2021-01-27 10/week @ 2021-02-03 24/week @ 2021-02-10 44/week @ 2021-02-17 33/week @ 2021-02-24 57/week @ 2021-03-03 64/week @ 2021-03-10 18/week @ 2021-03-17 102/week @ 2021-03-24 69/week @ 2021-03-31 53/week @ 2021-04-07 73/week @ 2021-04-14 66/week @ 2021-04-21 70/week @ 2021-04-28 193/week @ 2021-05-05

161 downloads per month
Used in 3 crates (2 directly)

MIT/Apache

56KB
1.5K SLoC

serde-hashkey

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:

Features

  • ordered-float - Enables serializing floating point numbers through behavior derived from the ordered-float crate

Examples

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

use serde_derive::{Deserialize, Serialize};
use serde_hashkey::{from_key, to_key, 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<dyn error::Error>> {
    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

Dependencies

~150–265KB