#consistent-hashing #hashing #consistent #google

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

#954 in Algorithms

Download history 2185/week @ 2024-07-19 3430/week @ 2024-07-26 1179/week @ 2024-08-02 2450/week @ 2024-08-09 2515/week @ 2024-08-16 2946/week @ 2024-08-23 2303/week @ 2024-08-30 2343/week @ 2024-09-06 2391/week @ 2024-09-13 2713/week @ 2024-09-20 2462/week @ 2024-09-27 2757/week @ 2024-10-04 5557/week @ 2024-10-11 4924/week @ 2024-10-18 3608/week @ 2024-10-25 3997/week @ 2024-11-01

18,904 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