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
//! # Implements primary key hashing
//!

use std::ops::Deref;

use latin1str::{Latin1Str, Latin1String};

use crate::value::{Context, Value};

/// This trait is implemented on all types that represent a field value
pub trait FdbHash {
    /// Get the hash value
    fn hash(&self) -> u32;
}

impl FdbHash for u32 {
    fn hash(&self) -> u32 {
        *self
    }
}

impl FdbHash for i32 {
    fn hash(&self) -> u32 {
        u32::from_ne_bytes(self.to_ne_bytes())
    }
}

impl FdbHash for f32 {
    fn hash(&self) -> u32 {
        u32::from_ne_bytes(self.to_ne_bytes())
    }
}

impl FdbHash for Latin1Str {
    fn hash(&self) -> u32 {
        sfhash::digest(self.as_bytes())
    }
}

impl FdbHash for Latin1String {
    fn hash(&self) -> u32 {
        FdbHash::hash(self.deref())
    }
}

impl FdbHash for str {
    fn hash(&self) -> u32 {
        FdbHash::hash(Latin1String::encode(self).as_ref())
    }
}

impl FdbHash for String {
    fn hash(&self) -> u32 {
        FdbHash::hash(self.as_str())
    }
}

impl FdbHash for i64 {
    fn hash(&self) -> u32 {
        FdbHash::hash(&u64::from_ne_bytes(self.to_ne_bytes()))
    }
}

impl FdbHash for u64 {
    fn hash(&self) -> u32 {
        (self & 0xFFFFFFFF) as u32
    }
}

impl FdbHash for bool {
    fn hash(&self) -> u32 {
        match *self {
            true => 1,
            false => 0,
        }
    }
}

impl<C: Context> FdbHash for Value<C>
where
    C::I64: FdbHash,
    C::String: FdbHash,
    C::XML: FdbHash,
{
    fn hash(&self) -> u32 {
        match self {
            Value::Nothing => 0,
            Value::Integer(i) => FdbHash::hash(i),
            Value::Float(f) => FdbHash::hash(f),
            Value::Text(f) => FdbHash::hash(f),
            Value::Boolean(b) => FdbHash::hash(b),
            Value::BigInt(i) => FdbHash::hash(i),
            // FIXME: This may not be correct
            Value::VarChar(v) => FdbHash::hash(v),
        }
    }
}