custom_hasher/
custom_hasher.rs

1extern crate hash_ring;
2
3use hash_ring::HashRing;
4use hash_ring::NodeInfo;
5use std::hash::BuildHasherDefault;
6use std::hash::Hasher;
7
8// This is a hasher that always returns the same number
9// no matter the input. This is meant as an example and
10// should never be used in production code as all keys go
11// to the same node.
12#[derive(Default)]
13struct ConstantHasher;
14
15impl Hasher for ConstantHasher {
16    fn write(&mut self, _bytes: &[u8]) {
17        // Do nothing
18    }
19
20    fn finish(&self) -> u64 {
21        return 1;
22    }
23}
24
25type ConstantBuildHasher = BuildHasherDefault<ConstantHasher>;
26
27fn main() {
28    let mut nodes: Vec<NodeInfo> = Vec::new();
29    nodes.push(NodeInfo {
30        host: "localhost",
31        port: 15324,
32    });
33    nodes.push(NodeInfo {
34        host: "localhost",
35        port: 15325,
36    });
37    nodes.push(NodeInfo {
38        host: "localhost",
39        port: 15326,
40    });
41    nodes.push(NodeInfo {
42        host: "localhost",
43        port: 15327,
44    });
45    nodes.push(NodeInfo {
46        host: "localhost",
47        port: 15328,
48    });
49    nodes.push(NodeInfo {
50        host: "localhost",
51        port: 15329,
52    });
53
54    let hash_ring: HashRing<NodeInfo, ConstantBuildHasher> =
55        HashRing::with_hasher(nodes, 10, ConstantBuildHasher::default());
56
57    println!(
58        "Key: '{}', Node: {}",
59        "hello",
60        hash_ring.get_node(("hello").to_string()).unwrap()
61    );
62    println!(
63        "Key: '{}', Node: {}",
64        "dude",
65        hash_ring.get_node(("dude").to_string()).unwrap()
66    );
67    println!(
68        "Key: '{}', Node: {}",
69        "martian",
70        hash_ring.get_node(("martian").to_string()).unwrap()
71    );
72    println!(
73        "Key: '{}', Node: {}",
74        "tardis",
75        hash_ring.get_node(("tardis").to_string()).unwrap()
76    );
77}