#hashing #consistent-hashing #consistent

maglev

Maglev - Google's consistent hashing algorithm

6 releases

0.2.1 Oct 26, 2021
0.2.0 Nov 14, 2020
0.1.3 Jan 23, 2017

#1598 in Algorithms

Download history 5156/week @ 2024-06-09 2811/week @ 2024-06-16 1978/week @ 2024-06-23 2640/week @ 2024-06-30 2959/week @ 2024-07-07 3154/week @ 2024-07-14 2041/week @ 2024-07-21 3415/week @ 2024-07-28 985/week @ 2024-08-04 2789/week @ 2024-08-11 2482/week @ 2024-08-18 2987/week @ 2024-08-25 2524/week @ 2024-09-01 2372/week @ 2024-09-08 2485/week @ 2024-09-15 2183/week @ 2024-09-22

9,701 downloads per month
Used in sonya-proxy

Apache-2.0

16KB
281 lines

rust-maglev travis build crate docs

Google's consistent hashing algorithm

Usage

To use maglev, first add this to your Cargo.toml:

[dependencies]
maglev = "0.2"

And then, use Maglev with ConsistentHasher trait

use maglev::{ConsistentHasher, Maglev};

fn main() {
    let m = Maglev::new(vec!["Monday",
                            "Tuesday",
                            "Wednesday",
                            "Thursday",
                            "Friday",
                            "Saturday",
                            "Sunday"]);

    assert_eq!(m["alice"], "Friday");
    assert_eq!(m["bob"], "Wednesday");

    // When the node list changed, ensure to use same `capacity` to rebuild

    let m = Maglev::with_capacity(vec!["Monday",
                                  // "Tuesday",
                                    "Wednesday",
                                  // "Thursday",
                                    "Friday",
                                    "Saturday",
                                    "Sunday"],
                                m.capacity());

    assert_eq!(m["alice"], "Friday");
    assert_eq!(m["bob"], "Wednesday");
}

Maglev use std::collections::hash_map::DefaultHasher by default, we could use the given hash builder to hash keys.

use fasthash::spooky::Hash128;
use maglev::Maglev;

fn main() {
    let m = Maglev::with_hasher(vec!["Monday",
                                     "Tuesday",
                                     "Wednesday",
                                     "Thursday",
                                     "Friday",
                                     "Saturday",
                                     "Sunday"],
                                Hash128 {});

    assert_eq!(m["alice"], "Monday");
    assert_eq!(m["bob"], "Wednesday");
}

Dependencies

~0.8–2.1MB
~31K SLoC