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
use sc_cli::Result;
use clap::Args;
use serde::Serialize;
use std::path::PathBuf;
use super::{StatSelect, Stats};
#[derive(Debug, Default, Serialize, Clone, PartialEq, Args)]
pub struct WeightParams {
#[clap(long)]
pub weight_path: Option<PathBuf>,
#[clap(long = "metric", default_value = "average")]
pub weight_metric: StatSelect,
#[clap(long = "mul", default_value = "1")]
pub weight_mul: f64,
#[clap(long = "add", default_value = "0")]
pub weight_add: u64,
}
impl WeightParams {
pub fn calc_weight(&self, stat: &Stats) -> Result<u64> {
if self.weight_mul.is_sign_negative() || !self.weight_mul.is_normal() {
return Err("invalid floating number for `weight_mul`".into())
}
let s = stat.select(self.weight_metric) as f64;
let w = s.mul_add(self.weight_mul, self.weight_add as f64).ceil();
Ok(w as u64) }
}
#[cfg(test)]
mod test_weight_params {
use super::WeightParams;
use crate::shared::{StatSelect, Stats};
#[test]
fn calc_weight_works() {
let stats = Stats { avg: 113, ..Default::default() };
let params = WeightParams {
weight_metric: StatSelect::Average,
weight_mul: 0.75,
weight_add: 3,
..Default::default()
};
let want = (113.0f64 * 0.75 + 3.0).ceil() as u64; let got = params.calc_weight(&stats).unwrap();
assert_eq!(want, got);
}
#[test]
fn calc_weight_detects_negative_mul() {
let stats = Stats::default();
let params = WeightParams { weight_mul: -0.75, ..Default::default() };
assert!(params.calc_weight(&stats).is_err());
}
}