├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benches └── my_benchmark.rs └── src ├── conhash.rs ├── lib.rs └── node.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | /.vscode 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | script: 4 | - cargo build -v 5 | - cargo test -v 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "conhash" 3 | version = "0.5.1" 4 | edition = "2021" 5 | authors = ["Y. T. Chung "] 6 | description = "Consistent Hashing library in Rust" 7 | repository = "https://github.com/zonyitoo/conhash-rs" 8 | keywords = ["consistent", "hash", "cache"] 9 | license = "MIT/Apache-2.0" 10 | 11 | [lib] 12 | name = "conhash" 13 | 14 | [dependencies] 15 | md5 = "0.7" 16 | log = "0.4" 17 | 18 | [dev-dependencies] 19 | criterion = "0.3" 20 | once_cell = "1.9.0" 21 | 22 | [[bench]] 23 | name = "my_benchmark" 24 | harness = false 25 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2015 ty 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Consistent Hashing for Rust 2 | 3 | [![Build & Test](https://github.com/zonyitoo/conhash-rs/actions/workflows/rust.yml/badge.svg)](https://github.com/zonyitoo/conhash-rs/actions/workflows/rust.yml) 4 | 5 | [Consistent hashing](http://en.wikipedia.org/wiki/Consistent_hashing) is a special kind of hashing such that 6 | when a hash table is resized and consistent hashing is used, only K/n keys need to be remapped on average, 7 | where K is the number of keys, and n is the number of slots. 8 | 9 | ## Usage 10 | 11 | ```toml 12 | [dependencies] 13 | conhash = "*" 14 | ``` 15 | 16 | ```rust 17 | extern crate conhash; 18 | 19 | use conhash::{ConsistentHash, Node}; 20 | 21 | #[derive(Debug, Clone, Eq, PartialEq)] 22 | struct ServerNode { 23 | host: String, 24 | port: u16, 25 | } 26 | 27 | impl Node for ServerNode { 28 | fn name(&self) -> String { 29 | format!("{}:{}", self.host, self.port) 30 | } 31 | } 32 | 33 | impl ServerNode { 34 | fn new(host: &str, port: u16) -> ServerNode { 35 | ServerNode { 36 | host: host.to_owned(), 37 | port: port, 38 | } 39 | } 40 | } 41 | 42 | fn main() { 43 | let nodes = [ 44 | ServerNode::new("localhost", 12345), 45 | ServerNode::new("localhost", 12346), 46 | ServerNode::new("localhost", 12347), 47 | ServerNode::new("localhost", 12348), 48 | ServerNode::new("localhost", 12349), 49 | ServerNode::new("localhost", 12350), 50 | ServerNode::new("localhost", 12351), 51 | ServerNode::new("localhost", 12352), 52 | ServerNode::new("localhost", 12353), 53 | ]; 54 | 55 | const REPLICAS: usize = 20; 56 | 57 | let mut ch = ConsistentHash::new(); 58 | 59 | for node in nodes.iter() { 60 | ch.add(node, REPLICAS); 61 | } 62 | 63 | assert_eq!(ch.len(), nodes.len() * REPLICAS); 64 | 65 | let node_for_hello = ch.get("hello").unwrap().clone(); 66 | assert_eq!(node_for_hello, ServerNode::new("localhost", 12347)); 67 | 68 | ch.remove(&ServerNode::new("localhost", 12350)); 69 | assert_eq!(ch.get("hello").unwrap().clone(), node_for_hello); 70 | } 71 | ``` 72 | 73 | ## License 74 | 75 | Licensed under either of 76 | 77 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 78 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 79 | 80 | at your option. 81 | 82 | ### Contribution 83 | 84 | Unless you explicitly state otherwise, any contribution intentionally submitted 85 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 86 | additional terms or conditions. 87 | -------------------------------------------------------------------------------- /benches/my_benchmark.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Mutex; 2 | 3 | use conhash::{ConsistentHash, Node}; 4 | use criterion::{black_box, criterion_group, criterion_main, Criterion}; 5 | use once_cell::sync::Lazy; 6 | 7 | #[derive(Debug, Clone, Eq, PartialEq)] 8 | struct ServerNode { 9 | host: String, 10 | port: u16, 11 | } 12 | 13 | impl Node for ServerNode { 14 | fn name(&self) -> String { 15 | format!("{}:{}", self.host, self.port) 16 | } 17 | } 18 | 19 | impl ServerNode { 20 | fn new(host: &str, port: u16) -> ServerNode { 21 | ServerNode { 22 | host: host.to_owned(), 23 | port: port, 24 | } 25 | } 26 | } 27 | 28 | type Nodes = ConsistentHash; 29 | 30 | static CH: Lazy = Lazy::new(|| new_large_nodes()); 31 | static CH_MUT: Lazy> = Lazy::new(|| Mutex::new(new_large_nodes())); 32 | 33 | fn new_large_nodes() -> Nodes { 34 | const NODES: usize = 1000; 35 | const REPLICAS: usize = NODES; 36 | let mut ch = Nodes::new(); 37 | 38 | for i in 0..NODES { 39 | let node = ServerNode::new("localhost", 10000 + i as u16); 40 | ch.add(&node, REPLICAS); 41 | } 42 | ch 43 | } 44 | 45 | fn get(key: &str) { 46 | CH.get_str(key); 47 | } 48 | 49 | fn get_mut(key: &str) { 50 | CH_MUT.lock().unwrap().get_str_mut(key); 51 | } 52 | 53 | fn bench_get(c: &mut Criterion) { 54 | c.bench_function("get", |b| b.iter(|| get(black_box("")))); 55 | } 56 | 57 | fn bench_get_mut(c: &mut Criterion) { 58 | c.bench_function("get_mut", |b| b.iter(|| get_mut(black_box("")))); 59 | } 60 | 61 | criterion_group!(benches, bench_get, bench_get_mut); 62 | criterion_main!(benches); 63 | -------------------------------------------------------------------------------- /src/conhash.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 conhash-rs developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use std::collections::{BTreeMap, HashMap}; 10 | 11 | use md5; 12 | 13 | use crate::Node; 14 | 15 | fn default_md5_hash_fn(input: &[u8]) -> Vec { 16 | let digest = md5::compute(input); 17 | digest.to_vec() 18 | } 19 | 20 | /// Consistent Hash 21 | pub struct ConsistentHash { 22 | hash_fn: fn(&[u8]) -> Vec, 23 | nodes: BTreeMap, N>, 24 | replicas: HashMap, 25 | } 26 | 27 | impl ConsistentHash { 28 | /// Construct with default hash function (Md5) 29 | pub fn new() -> ConsistentHash { 30 | ConsistentHash::with_hash(default_md5_hash_fn) 31 | } 32 | 33 | /// Construct with customized hash function 34 | pub fn with_hash(hash_fn: fn(&[u8]) -> Vec) -> ConsistentHash { 35 | ConsistentHash { 36 | hash_fn, 37 | nodes: BTreeMap::new(), 38 | replicas: HashMap::new(), 39 | } 40 | } 41 | 42 | /// Add a new node 43 | pub fn add(&mut self, node: &N, num_replicas: usize) { 44 | let node_name = node.name(); 45 | debug!("Adding node {:?} with {} replicas", node_name, num_replicas); 46 | 47 | // Remove it first 48 | self.remove(node); 49 | 50 | self.replicas.insert(node_name.clone(), num_replicas); 51 | for replica in 0..num_replicas { 52 | let node_ident = format!("{}:{}", node_name, replica); 53 | let key = (self.hash_fn)(node_ident.as_bytes()); 54 | debug!( 55 | "Adding node {:?} of replica {}, hashed key is {:?}", 56 | node.name(), 57 | replica, 58 | key 59 | ); 60 | 61 | self.nodes.insert(key, node.clone()); 62 | } 63 | } 64 | 65 | /// Get a node by key. Return `None` if no valid node inside 66 | pub fn get<'a>(&'a self, key: &[u8]) -> Option<&'a N> { 67 | if self.nodes.is_empty() { 68 | debug!("The container is empty"); 69 | return None; 70 | } 71 | 72 | let hashed_key = (self.hash_fn)(key); 73 | debug!("Getting key {:?}, hashed key is {:?}", key, hashed_key); 74 | 75 | let entry = self.nodes.range(hashed_key..).next(); 76 | if let Some((_k, v)) = entry { 77 | debug!("Found node {:?}", v.name()); 78 | return Some(v); 79 | } 80 | 81 | // Back to the first one 82 | debug!("Search to the end, coming back to the head ..."); 83 | let first = self.nodes.iter().next(); 84 | debug_assert!(first.is_some()); 85 | let (_k, v) = first.unwrap(); 86 | debug!("Found node {:?}", v.name()); 87 | Some(v) 88 | } 89 | 90 | /// Get a node by string key 91 | pub fn get_str<'a>(&'a self, key: &str) -> Option<&'a N> { 92 | self.get(key.as_bytes()) 93 | } 94 | 95 | /// Get a node by key. Return `None` if no valid node inside 96 | pub fn get_mut<'a>(&'a mut self, key: &[u8]) -> Option<&'a mut N> { 97 | let hashed_key = self.get_node_hashed_key(key); 98 | hashed_key.and_then(move |k| self.nodes.get_mut(&k)) 99 | } 100 | 101 | // Get a node's hashed key by key. Return `None` if no valid node inside 102 | fn get_node_hashed_key(&self, key: &[u8]) -> Option> { 103 | if self.nodes.is_empty() { 104 | debug!("The container is empty"); 105 | return None; 106 | } 107 | 108 | let hashed_key = (self.hash_fn)(key); 109 | debug!("Getting key {:?}, hashed key is {:?}", key, hashed_key); 110 | 111 | let entry = self.nodes.range(hashed_key..).next(); 112 | if let Some((k, v)) = entry { 113 | debug!("Found node {:?}", v.name()); 114 | return Some(k.clone()); 115 | } 116 | 117 | // Back to the first one 118 | debug!("Search to the end, coming back to the head ..."); 119 | let first = self.nodes.iter().next(); 120 | debug_assert!(first.is_some()); 121 | let (k, v) = first.unwrap(); 122 | debug!("Found node {:?}", v.name()); 123 | Some(k.clone()) 124 | } 125 | 126 | /// Get a node by string key 127 | pub fn get_str_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut N> { 128 | self.get_mut(key.as_bytes()) 129 | } 130 | 131 | /// Remove a node with all replicas (virtual nodes) 132 | pub fn remove(&mut self, node: &N) { 133 | let node_name = node.name(); 134 | debug!("Removing node {:?}", node_name); 135 | 136 | let num_replicas = match self.replicas.remove(&node_name) { 137 | Some(val) => { 138 | debug!("Node {:?} has {} replicas", node_name, val); 139 | val 140 | } 141 | None => { 142 | debug!("Node {:?} not exists", node_name); 143 | return; 144 | } 145 | }; 146 | 147 | debug!("Node {:?} replicas {}", node_name, num_replicas); 148 | 149 | for replica in 0..num_replicas { 150 | let node_ident = format!("{}:{}", node.name(), replica); 151 | let key = (self.hash_fn)(node_ident.as_bytes()); 152 | self.nodes.remove(&key); 153 | } 154 | } 155 | 156 | /// Number of nodes 157 | pub fn len(&self) -> usize { 158 | self.nodes.len() 159 | } 160 | 161 | /// Is empty 162 | pub fn is_empty(&self) -> bool { 163 | self.len() == 0 164 | } 165 | } 166 | 167 | impl Default for ConsistentHash { 168 | fn default() -> Self { 169 | Self::new() 170 | } 171 | } 172 | 173 | #[cfg(test)] 174 | mod test { 175 | use super::*; 176 | 177 | #[derive(Debug, Clone, Eq, PartialEq)] 178 | struct ServerNode { 179 | host: String, 180 | port: u16, 181 | } 182 | 183 | impl Node for ServerNode { 184 | fn name(&self) -> String { 185 | format!("{}:{}", self.host, self.port) 186 | } 187 | } 188 | 189 | impl ServerNode { 190 | fn new(host: &str, port: u16) -> ServerNode { 191 | ServerNode { 192 | host: host.to_owned(), 193 | port: port, 194 | } 195 | } 196 | } 197 | 198 | #[test] 199 | fn test_basic() { 200 | let nodes = [ 201 | ServerNode::new("localhost", 12345), 202 | ServerNode::new("localhost", 12346), 203 | ServerNode::new("localhost", 12347), 204 | ServerNode::new("localhost", 12348), 205 | ServerNode::new("localhost", 12349), 206 | ServerNode::new("localhost", 12350), 207 | ServerNode::new("localhost", 12351), 208 | ServerNode::new("localhost", 12352), 209 | ServerNode::new("localhost", 12353), 210 | ]; 211 | 212 | const REPLICAS: usize = 20; 213 | 214 | let mut ch = ConsistentHash::new(); 215 | 216 | for node in nodes.iter() { 217 | ch.add(node, REPLICAS); 218 | } 219 | 220 | assert_eq!(ch.len(), nodes.len() * REPLICAS); 221 | 222 | let node_for_hello = ch.get_str("hello").unwrap().clone(); 223 | assert_eq!(node_for_hello, ServerNode::new("localhost", 12347)); 224 | 225 | ch.remove(&ServerNode::new("localhost", 12350)); 226 | assert_eq!(ch.get_str("hello").unwrap().clone(), node_for_hello); 227 | 228 | assert_eq!(ch.len(), (nodes.len() - 1) * REPLICAS); 229 | 230 | ch.remove(&ServerNode::new("localhost", 12347)); 231 | assert_ne!(ch.get_str("hello").unwrap().clone(), node_for_hello); 232 | 233 | assert_eq!(ch.len(), (nodes.len() - 2) * REPLICAS); 234 | } 235 | 236 | #[test] 237 | fn get_from_empty() { 238 | let mut ch = ConsistentHash::::new(); 239 | assert_eq!(ch.get_str(""), None); 240 | assert_eq!(ch.get_str_mut(""), None); 241 | } 242 | 243 | #[test] 244 | fn get_from_one_node() { 245 | let mut node = ServerNode::new("localhost", 12345); 246 | for replicas in 1..10_usize { 247 | let mut ch = ConsistentHash::::new(); 248 | ch.add(&node, replicas); 249 | assert_eq!(ch.len(), replicas); 250 | for i in 0..replicas * 100 { 251 | let s = format!("{}", i); 252 | assert_eq!(ch.get_str(&s), Some(&node)); 253 | assert_eq!(ch.get_str_mut(&s), Some(&mut node)); 254 | } 255 | } 256 | } 257 | 258 | #[test] 259 | fn get_from_two_nodes() { 260 | let mut node0 = ServerNode::new("localhost", 12345); 261 | let mut node1 = ServerNode::new("localhost", 54321); 262 | for replicas in 1..10_usize { 263 | let mut ch = ConsistentHash::::new(); 264 | ch.add(&node0, replicas); 265 | ch.add(&node1, replicas); 266 | assert_eq!(ch.len(), 2 * replicas); 267 | for i in 0..replicas * 100 { 268 | let s = format!("{}", i); 269 | let n = ch.get_str(&s).unwrap(); 270 | assert!(n == &node0 || n == &node1); 271 | let n = ch.get_str(&s).unwrap(); 272 | assert!(n == &mut node0 || n == &mut node1); 273 | } 274 | } 275 | } 276 | 277 | #[test] 278 | fn get_exact_node() { 279 | let mut ch = ConsistentHash::new(); 280 | const NODES: usize = 1000; 281 | const REPLICAS: usize = 20; 282 | let mut nodes = Vec::::with_capacity(NODES); 283 | for i in 0..NODES { 284 | let node = ServerNode::new("localhost", 10000 + i as u16); 285 | ch.add(&node, REPLICAS); 286 | nodes.push(node); 287 | } 288 | assert_eq!(ch.len(), NODES * REPLICAS); 289 | for i in 0..NODES { 290 | for r in 0..REPLICAS { 291 | let s = format!("{}:{}", nodes[i].name(), r); 292 | assert_eq!(ch.get_str(&s), Some(&nodes[i])); 293 | assert_eq!(ch.get_str_mut(&s).cloned().as_ref(), Some(&nodes[i])); 294 | } 295 | } 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 conhash-rs developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | //! [Consistent Hashing](http://en.wikipedia.org/wiki/Consistent_hashing) is a special 10 | //! kind of hashing such that when a hash table is resized and consistent hashing is used, 11 | //! only K/n keys need to be remapped on average, where K is the number of keys, and n 12 | //! is hte number of slots. 13 | 14 | #[macro_use] 15 | extern crate log; 16 | extern crate md5; 17 | 18 | pub use crate::conhash::ConsistentHash; 19 | pub use node::Node; 20 | 21 | pub mod conhash; 22 | pub mod node; 23 | -------------------------------------------------------------------------------- /src/node.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 conhash-rs developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | pub trait Node: Clone { 10 | fn name(&self) -> String; 11 | } 12 | --------------------------------------------------------------------------------