Skip to main content

score_set/
weighted.rs

1use witnessed::{WitnessExt, Witnessed};
2
3use crate::traits::{EvalF32, EvalF64, V01, V01Error, prove_v01_f32, prove_v01_f64};
4
5/// Creates a witnessed `f64` weight in the `[0, 1]` range.
6pub fn weight64(value: f64) -> Result<Witnessed<f64, V01>, V01Error> {
7    value.witness().by(prove_v01_f64)
8}
9
10/// Creates a witnessed `f32` weight in the `[0, 1]` range.
11pub fn weight32(value: f32) -> Result<Witnessed<f32, V01>, V01Error> {
12    value.witness().by(prove_v01_f32)
13}
14
15/// Applies a witnessed `[0, 1]` weight to an `f64` evaluator.
16pub struct Weighted64<E> {
17    inner: E,
18    weight: Witnessed<f64, V01>,
19}
20
21impl<E> Weighted64<E> {
22    /// Creates a weighted evaluator.
23    pub fn new(inner: E, weight: Witnessed<f64, V01>) -> Self {
24        Self { inner, weight }
25    }
26
27    /// Returns the wrapped evaluator.
28    pub fn inner(&self) -> &E {
29        &self.inner
30    }
31
32    /// Returns the witnessed weight.
33    pub fn weight(&self) -> &Witnessed<f64, V01> {
34        &self.weight
35    }
36
37    /// Consumes the wrapper and returns the evaluator.
38    pub fn into_inner(self) -> E {
39        self.inner
40    }
41}
42
43impl<Ctx, E> EvalF64<Ctx> for Weighted64<E>
44where
45    Ctx: ?Sized,
46    E: EvalF64<Ctx>,
47{
48    #[inline]
49    fn eval(&self, ctx: &Ctx) -> f64 {
50        *self.weight * self.inner.eval(ctx)
51    }
52}
53
54/// Applies a witnessed `[0, 1]` weight to an `f32` evaluator.
55pub struct Weighted32<E> {
56    inner: E,
57    weight: Witnessed<f32, V01>,
58}
59
60impl<E> Weighted32<E> {
61    /// Creates a weighted evaluator.
62    pub fn new(inner: E, weight: Witnessed<f32, V01>) -> Self {
63        Self { inner, weight }
64    }
65
66    /// Returns the wrapped evaluator.
67    pub fn inner(&self) -> &E {
68        &self.inner
69    }
70
71    /// Returns the witnessed weight.
72    pub fn weight(&self) -> &Witnessed<f32, V01> {
73        &self.weight
74    }
75
76    /// Consumes the wrapper and returns the evaluator.
77    pub fn into_inner(self) -> E {
78        self.inner
79    }
80}
81
82impl<Ctx, E> EvalF32<Ctx> for Weighted32<E>
83where
84    Ctx: ?Sized,
85    E: EvalF32<Ctx>,
86{
87    #[inline]
88    fn eval(&self, ctx: &Ctx) -> f32 {
89        *self.weight * self.inner.eval(ctx)
90    }
91}