1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! #Example
//!
//! ```Rust
//! extern crate conshash;
//!
//! use std::hash::SipHasher;
//!
//! #[derive(Clone, Debug)]
//! struct TestNode {
//!     host_name: &'static str,
//!     ip_address: &'static str,
//!     port: u32,
//! }
//!
//! impl ToString for TestNode {
//!     fn to_string(&self) -> String {
//!         format!("{}{}", self.ip_address.to_string(), self.port.to_string())
//!     }
//! }
//!
//! let mut hash_ring = Ring::new(5);
//!
//! let test_node = TestNode{host_name: "Skynet", ip_address: "192.168.1.1", port: 42};
//! hash_ring.add_node(&test_node);
//! hash_ring.remove_node(&test_node);
//! hash_ring.add_node(&test_node);
//! let x = hash_ring.get_node(hash::<_, SipHasher>(&format!("{}{}", test_node.to_string(), 0.to_string())));
//! // x is the node in the form of an Option<T> where T: Clone + ToString + Debug
//! ```


use std::hash::{Hash, Hasher, SipHasher};
use std::clone::Clone;
use std::fmt::Debug;
use std::string::ToString;
use std::collections::BTreeMap;


pub fn hash<T: Hash, H:Hasher + Default>(value: &T) -> u64 {
    let mut h: H = Default::default();
    value.hash(&mut h);
    h.finish()
}

pub struct Ring <T: Clone + ToString + Debug> {
    num_replicas: usize,
    ring: BTreeMap<u64, T>,
}


impl <T> Ring<T> where T: Clone + ToString + Debug {
    pub fn new(num_replicas: usize) -> Ring<T> {
        Ring {
            num_replicas: num_replicas,
            ring: BTreeMap::new(),
        }
    }

    pub fn add_nodes(&mut self, nodes: &[T]) {
        if !nodes.is_empty() {
            for node in nodes.iter() { self.add_node(node); }
        }
    }

    pub fn remove_nodes(&mut self, nodes: &[T]) {
        if !nodes.is_empty() {
            for node in nodes.iter() { self.remove_node(node); }
        }
    }

    pub fn add_node(&mut self, node: &T) {
        for i in 0..self.num_replicas {
            let key = hash::<_, SipHasher>(&format!("{}{}", node.to_string(), i.to_string()));
            self.ring.insert(key, node.clone());
        }
    }

    pub fn remove_node(&mut self, node: &T) {
        assert!(!self.ring.is_empty());

        for i in 0..self.num_replicas {
            let key = hash::<_, SipHasher>(&format!("{}{}", node.to_string(), i.to_string()));
            self.ring.remove(&key);
        }
    }

    pub fn get_node(&self, key: u64) -> Option<&T> {
        assert!(!self.ring.is_empty());
        let mut keys = self.ring.keys();
        keys.find(|k| *k >= &key)
            .and_then(|k| self.ring.get(k))
            .or(keys.nth(0).and_then(|x| self.ring.get(x)))
    }
}


#[cfg (test)]
mod tests {

    use super::*;
    use std::string::ToString;
    use std::hash::SipHasher;

    #[derive(Clone, Debug)]
    struct TestNode {
        host_name: &'static str,
        ip_address: &'static str,
        port: u32,
    }

    impl ToString for TestNode {
        fn to_string(&self) -> String {
            format!("{}{}", self.ip_address.to_string(), self.port.to_string())
        }
    }

    #[test]
    fn test_add_node(){
        let mut hash_ring = Ring::new(3);
        assert_eq!(hash_ring.num_replicas, 3);

        let test_node = TestNode{host_name: "Skynet", ip_address: "192.168.1.1", port: 42};
        hash_ring.add_node(&test_node);

    }

    #[test]
    fn test_remove_node(){
        let mut hash_ring = Ring::new(3);
        assert_eq!(hash_ring.num_replicas, 3);

        let test_node = TestNode{host_name: "Skynet", ip_address: "192.168.1.1", port: 42};
        hash_ring.add_node(&test_node);
        hash_ring.remove_node(&test_node);
    }

    #[test]
    fn test_get_node(){
        let mut hash_ring = Ring::new(3);
        assert_eq!(hash_ring.num_replicas, 3);

        let test_node = TestNode{host_name: "Skynet", ip_address: "192.168.1.1", port: 42};
        hash_ring.add_node(&test_node);
        let my_node = hash_ring.get_node(hash::<_, SipHasher>(&test_node.to_string()));

        assert_eq!(my_node.unwrap().host_name, test_node.host_name);
        assert_eq!(my_node.unwrap().ip_address, test_node.ip_address);
        assert_eq!(my_node.unwrap().port, test_node.port);
    }

    #[test]
    fn test_add_nodes(){
        let mut hash_ring = Ring::new(3);
        assert_eq!(hash_ring.num_replicas, 3);

        let test_node1 = TestNode{host_name: "Skynet", ip_address: "192.168.1.1", port: 42};
        let test_node2 = TestNode{host_name: "Inferno", ip_address: "10.0.1.1", port: 666};
        let test_node3 = TestNode{host_name: "Klimt", ip_address: "127.0.0.1", port: 1};

        let v = vec![test_node1.clone(), test_node2.clone(), test_node3.clone()];
        hash_ring.add_nodes(&v);

        let node1 = hash_ring.get_node(hash::<_, SipHasher>(&format!("{}{}", test_node1.to_string(), 0.to_string())));
        let node2 = hash_ring.get_node(hash::<_, SipHasher>(&format!("{}{}", test_node2.to_string(), 0.to_string())));
        let node3 = hash_ring.get_node(hash::<_, SipHasher>(&format!("{}{}", test_node3.to_string(), 0.to_string())));

        assert_eq!(node1.unwrap().host_name, test_node1.host_name);
        assert_eq!(node1.unwrap().ip_address, test_node1.ip_address);
        assert_eq!(node1.unwrap().port, test_node1.port);

        assert_eq!(node2.unwrap().host_name, test_node2.host_name);
        assert_eq!(node2.unwrap().ip_address, test_node2.ip_address);
        assert_eq!(node2.unwrap().port, test_node2.port);

        assert_eq!(node3.unwrap().host_name, test_node3.host_name);
        assert_eq!(node3.unwrap().ip_address, test_node3.ip_address);
        assert_eq!(node3.unwrap().port, test_node3.port);
    }

    #[test]
    fn test_remove_nodes(){
        let mut hash_ring = Ring::new(3);
        assert_eq!(hash_ring.num_replicas, 3);

        let test_node1 = TestNode{host_name: "Skynet", ip_address: "192.168.1.1", port: 42};
        let test_node2 = TestNode{host_name: "Inferno", ip_address: "10.0.1.1", port: 666};
        let test_node3 = TestNode{host_name: "Klimt", ip_address: "127.0.0.1", port: 1};

        let v = vec![test_node1.clone(), test_node2.clone(), test_node3.clone()];
        hash_ring.add_nodes(&v);
        hash_ring.remove_nodes(&v);

        assert!(hash_ring.ring.is_empty());
    }
}