Skip to main content

sql_builder/value/
binding_hash.rs

1use super::Value;
2use chrono::Offset;
3use std::hash::{Hash, Hasher};
4
5impl Value {
6    /// Hash the binding representation, including details ignored by value equality.
7    ///
8    /// This is deliberately separate from value hashing: numerically equal decimals,
9    /// float zeroes and timestamps can carry different data to a driver.
10    pub fn hash_binding<H: Hasher>(&self, state: &mut H) {
11        std::mem::discriminant(self).hash(state);
12        match self {
13            Self::Float(value) => value.map(f32::to_bits).hash(state),
14            Self::Double(value) => value.map(f64::to_bits).hash(state),
15            Self::Decimal(value) => value.map(|v| v.serialize()).hash(state),
16            Self::ChronoDateTimeUtc(value) => value
17                .map(|v| (v.naive_utc(), v.offset().fix().local_minus_utc()))
18                .hash(state),
19            Self::ChronoDateTimeLocal(value) => value
20                .map(|v| (v.naive_utc(), v.offset().fix().local_minus_utc()))
21                .hash(state),
22            Self::ChronoDateTimeWithTimeZone(value) => value
23                .map(|v| (v.naive_utc(), v.offset().local_minus_utc()))
24                .hash(state),
25            // A JSON `null` document is a value, which SQL NULL is not.
26            Self::Json(value) => {
27                value.is_some().hash(state);
28                self.hash(state);
29            }
30            Self::Array(element_type, values) => {
31                element_type.hash(state);
32                values.is_some().hash(state);
33                if let Some(values) = values {
34                    values.len().hash(state);
35                    for value in values.iter() {
36                        value.hash_binding(state);
37                    }
38                }
39            }
40            // These variants already hash every part of their binding payload,
41            // including the enum type name and the distinction between NULL and empty.
42            _ => self.hash(state),
43        }
44    }
45}
46
47#[cfg(test)]
48#[path = "../../tests/unit/binding_hash_tests.rs"]
49mod tests;