weighted_rs/
lib.rs

1//! A libray for weighted balancing algorithm.
2//! It provides three weighted balancing (elect) algorithm.
3//! One is random algorithm.
4//! Another is weighted balancing algorithm used by LVS.
5//! The third is smooth weighted balancing algorithm used by Nginx.
6//!
7//! The LVS weighted round-robin scheduling is introduced at http://kb.linuxvirtualserver.org/wiki/Weighted_Round-Robin_Scheduling.
8//! The Nginx smooth weighted round-robin balancing algorithm is introduced at https://github.com/phusion/nginx/commit/27e94984486058d73157038f7950a0a36ecc6e35.
9//! The random algorithm is not smooth although it follows weight configuration.
10//! Using it is simple:
11//! ```rust
12//!     use weighted_rs::{SmoothWeight, Weight};
13//!     use std::collections::HashMap;
14//!
15//!     let mut sw: SmoothWeight<&str> = SmoothWeight::new();
16//!     sw.add("server1", 5);
17//!     sw.add("server2", 2);
18//!     sw.add("server3", 3);
19//!
20//!     for _ in 0..100 {
21//!         let s = sw.next().unwrap();
22//!         println!("{}", s);
23//!     }
24//! ```
25
26use std::collections::HashMap;
27
28pub mod random_weight;
29pub mod roundrobin_weight;
30pub mod smooth_weight;
31
32pub use random_weight::*;
33pub use roundrobin_weight::*;
34pub use smooth_weight::*;
35
36// A common trait for weight algorithm.
37pub trait Weight {
38    type Item;
39
40    // next gets next selected item.
41    fn next(&mut self) -> Option<Self::Item>;
42    // add adds a weighted item for selection.
43    fn add(&mut self, item: Self::Item, weight: isize);
44
45    // all returns all items.
46    fn all(&self) -> HashMap<Self::Item, isize>;
47
48    // remove_all removes all weighted items.
49    fn remove_all(&mut self);
50
51    // reset resets the balancing algorithm.
52    fn reset(&mut self);
53}