```  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
```
``````use super::Weight;
use std::{collections::HashMap, hash::Hash};

#[derive(Clone, Debug)]
struct SmoothWeightItem<T> {
item: T,
weight: isize,
current_weight: isize,
effective_weight: isize,
}

// SW (Smooth Weighted) is a struct that contains weighted items and provides methods to select a
// weighted item. It is used for the smooth weighted round-robin balancing algorithm. This algorithm
// is implemented in Nginx: https://github.com/phusion/nginx/commit/27e94984486058d73157038f7950a0a36ecc6e35.
// Algorithm is as follows: on each peer selection we increase current_weight
// of each eligible peer by its weight, select peer with greatest current_weight
// and reduce its current_weight by total number of weight points distributed
// among peers.
// In case of { 5, 1, 1 } weights this gives the following sequence of
// current_weight's: (a, a, b, a, c, a, a)
#[derive(Default)]
pub struct SmoothWeight<T> {
items: Vec<SmoothWeightItem<T>>,
n: isize,
}

impl<T: Clone + PartialEq + Eq + Hash> SmoothWeight<T> {
pub fn new() -> Self {
SmoothWeight {
items: Vec::new(),
n: 0,
}
}

//https://github.com/phusion/nginx/commit/27e94984486058d73157038f7950a0a36ecc6e35
fn next_smooth_weighted(&mut self) -> Option<SmoothWeightItem<T>> {
let mut total = 0;

let mut best = self.items[0].clone();
let mut best_index = 0;
let mut found = false;

let items_len = self.items.len();
for i in 0..items_len {
self.items[i].current_weight += self.items[i].effective_weight;
total += self.items[i].effective_weight;
if self.items[i].effective_weight < self.items[i].weight {
self.items[i].effective_weight += 1;
}

if !found || self.items[i].current_weight > best.current_weight {
best = self.items[i].clone();
found = true;
best_index = i;
}
}

if !found {
return None;
}

self.items[best_index].current_weight -= total;
Some(best)
}
}

impl<T: Clone + PartialEq + Eq + Hash> Weight for SmoothWeight<T> {
type Item = T;

fn next(&mut self) -> Option<T> {
if self.n == 0 {
return None;
}
if self.n == 1 {
return Some(self.items[0].item.clone());
}

let rt = self.next_smooth_weighted()?;
Some(rt.item)
}
// add adds a weighted item for selection.
fn add(&mut self, item: T, weight: isize) {
let weight_item = SmoothWeightItem {
item,
weight,
current_weight: 0,
effective_weight: weight,
};

self.items.push(weight_item);
self.n += 1;
}

// all returns all items.
fn all(&self) -> HashMap<T, isize> {
let mut rt: HashMap<T, isize> = HashMap::new();
for w in &self.items {
rt.insert(w.item.clone(), w.weight);
}
rt
}

// remove_all removes all weighted items.
fn remove_all(&mut self) {
self.items.clear();
self.n = 0;
}

// reset resets the balancing algorithm.
fn reset(&mut self) {
for w in &mut self.items {
w.current_weight = 0;
w.effective_weight = w.weight;
}
}
}

#[cfg(test)]
mod tests {
use crate::{SmoothWeight, Weight};
use std::collections::HashMap;

#[test]
fn test_smooth_weight() {
let mut sw: SmoothWeight<&str> = SmoothWeight::new();

let mut results: HashMap<&str, usize> = HashMap::new();

for _ in 0..100 {
let s = sw.next().unwrap();
// *results.get_mut(s).unwrap() += 1;
*results.entry(s).or_insert(0) += 1;
}

assert_eq!(results["server1"], 50);
assert_eq!(results["server2"], 20);
assert_eq!(results["server3"], 30);
}
}
``````