Skip to main content

sql_builder/value/
value_key.rs

1use super::Value;
2use std::hash::{Hash, Hasher};
3
4/// A [`Value`] compared the way a key column compares it.
5///
6/// Integers compare by value, whatever their width or signedness, so
7/// `Int(1)`, `BigInt(1)` and `BigUnsigned(1)` are one key, and every other
8/// value as [`Value`]'s own equality compares it. An integer and a
9/// non-integer are never equal.
10#[derive(Clone, Debug)]
11pub struct ValueKey(Value);
12
13impl ValueKey {
14    /// The key of `value`.
15    pub fn new(value: Value) -> Self {
16        Self(value)
17    }
18
19    /// The value the key was made from.
20    pub fn value(&self) -> &Value {
21        &self.0
22    }
23
24    /// The integer the value holds, widened, if it is one: `Some(None)` for
25    /// an integer NULL.
26    fn integer(&self) -> Option<Option<i128>> {
27        Some(match self.0 {
28            Value::TinyInt(value) => value.map(i128::from),
29            Value::SmallInt(value) => value.map(i128::from),
30            Value::Int(value) => value.map(i128::from),
31            Value::BigInt(value) => value.map(i128::from),
32            Value::TinyUnsigned(value) => value.map(i128::from),
33            Value::SmallUnsigned(value) => value.map(i128::from),
34            Value::Unsigned(value) => value.map(i128::from),
35            Value::BigUnsigned(value) => value.map(i128::from),
36            _ => return None,
37        })
38    }
39}
40
41impl From<Value> for ValueKey {
42    fn from(value: Value) -> Self {
43        Self(value)
44    }
45}
46
47impl PartialEq for ValueKey {
48    fn eq(&self, other: &Self) -> bool {
49        match (self.integer(), other.integer()) {
50            (Some(left), Some(right)) => left == right,
51            (None, None) => self.0 == other.0,
52            _ => false,
53        }
54    }
55}
56
57impl Eq for ValueKey {}
58
59impl Hash for ValueKey {
60    fn hash<H: Hasher>(&self, state: &mut H) {
61        match self.integer() {
62            Some(integer) => {
63                true.hash(state);
64                integer.hash(state);
65            }
66            None => {
67                false.hash(state);
68                self.0.hash(state);
69            }
70        }
71    }
72}
73
74#[cfg(test)]
75#[path = "../../tests/unit/value_key_tests.rs"]
76mod tests;