9 unstable releases

0.5.1 Jun 14, 2023
0.5.0 Apr 6, 2022
0.4.0 Jan 14, 2018
0.3.2 Apr 8, 2016
0.3.0 May 1, 2015

#216 in Caching

Download history 16793/week @ 2025-09-20 17183/week @ 2025-09-27 21202/week @ 2025-10-04 19792/week @ 2025-10-11 17777/week @ 2025-10-18 18353/week @ 2025-10-25 18360/week @ 2025-11-01 13054/week @ 2025-11-08 14958/week @ 2025-11-15 8617/week @ 2025-11-22 14603/week @ 2025-11-29 8982/week @ 2025-12-06 12974/week @ 2025-12-13 5221/week @ 2025-12-20 3577/week @ 2025-12-27 17299/week @ 2026-01-03

40,578 downloads per month
Used in 4 crates (3 directly)

MIT/Apache

15KB
238 lines

Consistent Hashing for Rust

Build & Test

Consistent hashing is a special kind of hashing such that when a hash table is resized and consistent hashing is used, only K/n keys need to be remapped on average, where K is the number of keys, and n is the number of slots.

Usage

[dependencies]
conhash = "*"
extern crate conhash;

use conhash::{ConsistentHash, Node};

#[derive(Debug, Clone, Eq, PartialEq)]
struct ServerNode {
    host: String,
    port: u16,
}

impl Node for ServerNode {
    fn name(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}

impl ServerNode {
    fn new(host: &str, port: u16) -> ServerNode {
        ServerNode {
            host: host.to_owned(),
            port: port,
        }
    }
}

fn main() {
    let nodes = [
        ServerNode::new("localhost", 12345),
        ServerNode::new("localhost", 12346),
        ServerNode::new("localhost", 12347),
        ServerNode::new("localhost", 12348),
        ServerNode::new("localhost", 12349),
        ServerNode::new("localhost", 12350),
        ServerNode::new("localhost", 12351),
        ServerNode::new("localhost", 12352),
        ServerNode::new("localhost", 12353),
    ];

    const REPLICAS: usize = 20;

    let mut ch = ConsistentHash::new();

    for node in nodes.iter() {
        ch.add(node, REPLICAS);
    }

    assert_eq!(ch.len(), nodes.len() * REPLICAS);

    let node_for_hello = ch.get("hello").unwrap().clone();
    assert_eq!(node_for_hello, ServerNode::new("localhost", 12347));

    ch.remove(&ServerNode::new("localhost", 12350));
    assert_eq!(ch.get("hello").unwrap().clone(), node_for_hello);
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~120KB