strata_primitives/
quantization.rs1pub fn largest_remainder_quantization(shares: &[f32], total_available: u16) -> Vec<u16> {
9 let n = shares.len();
10 if n == 0 {
11 return Vec::new();
12 }
13 if total_available == 0 {
14 return vec![0; n];
15 }
16
17 let sum_shares: f32 = shares.iter().filter(|&&s| s > 0.0).sum();
18 if sum_shares <= 0.0 {
19 let base = total_available / (n as u16);
21 let mut rem = total_available % (n as u16);
22 let mut out = vec![base; n];
23 for val in out.iter_mut() {
24 if rem > 0 {
25 *val += 1;
26 rem -= 1;
27 }
28 }
29 return out;
30 }
31
32 let total_f = total_available as f32;
33 let mut allocated = Vec::with_capacity(n);
34 let mut remainders = Vec::with_capacity(n);
35 let mut current_sum = 0u16;
36
37 for (idx, &s) in shares.iter().enumerate() {
38 let proportion = (s.max(0.0) / sum_shares) * total_f;
39 let floor_val = proportion.floor() as u16;
40 let remainder = proportion - (floor_val as f32);
41
42 allocated.push(floor_val);
43 remainders.push((remainder, idx));
44 current_sum = current_sum.saturating_add(floor_val);
45 }
46
47 remainders.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
49
50 let deficit = total_available.saturating_sub(current_sum);
51 for &(_, track_idx) in &remainders[..(deficit as usize).min(n)] {
52 allocated[track_idx] += 1;
53 }
54
55 allocated
56}