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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//! Datatypes to better represent the domain of Merino.

use anyhow::ensure;
use rand::distributions::{Distribution, Standard};
use serde::{de, Deserialize, Serialize};
use std::fmt::Debug;

/// Represents a value from 0.0 to 1.0, inclusive. That is: a portion of
/// something that cannot be negative or exceed 100%.
///
/// Stored internally as a u32.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Proportion(u32);

impl Proportion {
    /// The lowest value for a portion, corresponding to 0%.
    pub fn zero() -> Self {
        Proportion(0)
    }

    /// The highest value for a portion, corresponding to 100%.
    pub fn one() -> Self {
        Proportion(u32::MAX)
    }

    /// Converts a float value into a Proportion. Panics if the value is not
    /// between zero and one.
    ///
    /// This is not implemented using [`std::config::From`] because you cannot
    /// implement both Try and TryFrom for the same pair of types, due to a
    /// blanket `impl TryFor<T> for U where U: Try<T>`.
    pub fn from<T>(v: T) -> Self
    where
        T: TryInto<Self>,
        <T as TryInto<Self>>::Error: Debug,
    {
        v.try_into().unwrap()
    }
}

/// Implement traits for a float type.
macro_rules! impl_for_float {
    ($type: ty) => {
        impl TryFrom<$type> for Proportion {
            type Error = anyhow::Error;

            fn try_from(v: $type) -> Result<Self, Self::Error> {
                ensure!(!v.is_infinite(), "v cannot be infinite");
                ensure!(v >= 0.0, "v must be positive");
                ensure!(v <= 1.0, "v cannot be greater than 1");

                Ok(Self((v * (u32::MAX as $type)) as u32))
            }
        }

        impl From<Proportion> for $type {
            fn from(portion: Proportion) -> $type {
                (portion.0 as $type) / (u32::MAX as $type)
            }
        }

        impl From<&Proportion> for $type {
            fn from(portion: &Proportion) -> $type {
                (portion.0 as $type) / (u32::MAX as $type)
            }
        }
    };
}

impl_for_float!(f32);
impl_for_float!(f64);

impl Distribution<Proportion> for Standard {
    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Proportion {
        Proportion(rng.gen())
    }
}

impl Serialize for Proportion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_f64(self.into())
    }
}

impl<'de> Deserialize<'de> for Proportion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        /// Visitor for deserializing a Proportion
        struct Visitor;

        impl<'de> de::Visitor<'de> for Visitor {
            type Value = Proportion;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(formatter, "value between 0.0 and 1.0")
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if v >= 0 {
                    self.visit_u64(v as u64)
                } else {
                    Err(de::Error::invalid_value(de::Unexpected::Signed(v), &self))
                }
            }

            // u8, u16, and u32 delegate to this
            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if v == 0 {
                    Ok(Proportion::zero())
                } else if v == 1 {
                    Ok(Proportion::one())
                } else {
                    Err(de::Error::invalid_value(de::Unexpected::Unsigned(v), &self))
                }
            }

            // f32 delegates to this
            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                v.try_into()
                    .map_err(|_err| de::Error::invalid_value(de::Unexpected::Float(v), &self))
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}

/// Gathers inputs to be hashed to determine a cache key.
pub trait CacheInputs {
    /// Add data to the cache key.
    fn add(&mut self, input: &[u8]);
    /// Generate a cache key from the collected inputs so far.
    fn hash(&self) -> String;
}

impl CacheInputs for blake3::Hasher {
    fn add(&mut self, input: &[u8]) {
        self.update(input);
    }

    fn hash(&self) -> String {
        self.finalize().to_hex().to_string()
    }
}