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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use crate::record::value::Value;
use minicbor::{
    data::{Tag, Type},
    Decoder,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use unicode_normalization::UnicodeNormalization;
// The conv crate is used to provide checked lossles conversions between different data types.
use conv::{NegOverflow, PosOverflow, RangeError, ValueInto};

/// A DataType is any of the valid CipherStash [datatypes] that can be contained inside an index.
/// It also supports nested fields using the Map type.
///
/// - uint64,
/// - float64,
/// - bool,
/// - string,
/// - date
///
/// [datatypes]: https://docs.cipherstash.com/reference/data-types/index.html
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum DataType {
    Uint64,
    Float64,
    String,
    Boolean,
    Date,
}

impl DataType {
    /// Indicate that a certain type can't be decoded in to the current SchemaField
    fn as_decode_not_supported<V>(&self, from: Type) -> Result<V, DataTypeDecodeError> {
        Err(DataTypeDecodeError::DecodeNotSupported {
            from,
            to: self.clone(),
        })
    }
}

#[derive(Error, Debug)]
pub enum DataTypeDecodeError {
    #[error("CborDecodeError: {0}")]
    CborDecode(minicbor::decode::Error),
    #[error("Type {from} cannot be decoded into {:?}", .to)]
    DecodeNotSupported { from: Type, to: DataType },
    #[error("Conversion failed: {0}")]
    ConversionFailed(String),
    #[error("{0}")]
    Other(String),
}

impl From<minicbor::decode::Error> for DataTypeDecodeError {
    fn from(val: minicbor::decode::Error) -> Self {
        Self::CborDecode(val)
    }
}

impl<T> From<NegOverflow<T>> for DataTypeDecodeError {
    fn from(val: NegOverflow<T>) -> Self {
        Self::ConversionFailed(format!("{}", val))
    }
}

impl<T> From<PosOverflow<T>> for DataTypeDecodeError {
    fn from(val: PosOverflow<T>) -> Self {
        Self::ConversionFailed(format!("{}", val))
    }
}

impl<T> From<RangeError<T>> for DataTypeDecodeError {
    fn from(val: RangeError<T>) -> Self {
        Self::ConversionFailed(format!("{}", val))
    }
}

/// Losslessly convert an f64 into a u64
///
/// If this method cannot convert the numbers losslessly it will return a [`FieldDecodeError`]
fn f64_to_u64(value: f64) -> Result<u64, DataTypeDecodeError> {
    let x = value as u64;

    // This roundtrip casting method seems to be the most reliable way to tell if something will
    // fit. If you can think of a case where this falls through please add a test.
    if x as f64 != value {
        return Err(DataTypeDecodeError::ConversionFailed(
            "f64 doesn\'t correctly fit into u64".into(),
        ));
    }

    Ok(x)
}

/// Create a u64 from a slice of big endian bytes of any length
///
/// Slices smaller than 8 bytes will be padded with zeroes to make a u64
fn u64_from_be_bytes(source_bytes: &[u8]) -> Result<u64, DataTypeDecodeError> {
    const BYTES_IN_U64: usize = std::mem::size_of::<u64>();

    let mut u64_bytes = [0; BYTES_IN_U64];

    let source_len = source_bytes.len();

    // In the case that the source bytes are empty we could return 0,
    // but I think it's better to throw an error.
    if source_len == 0 {
        return Err(DataTypeDecodeError::Other(
            "Provided byte slice was empty".to_string(),
        ));
    }

    if source_len > BYTES_IN_U64 {
        return Err(DataTypeDecodeError::Other(format!(
            "Bytes do not fit in u64. Expected length {}, got {}",
            BYTES_IN_U64, source_len
        )));
    }

    u64_bytes[BYTES_IN_U64 - source_len..].clone_from_slice(source_bytes);

    Ok(u64::from_be_bytes(u64_bytes))
}

pub fn decode_field_for_data_type(
    data_type: &DataType,
    d: &mut Decoder,
) -> Result<Value, DataTypeDecodeError> {
    Ok(match data_type {
        DataType::Uint64 => Value::Uint64(match d.datatype()? {
            // Unsigned ints go into a u64 easily
            Type::U8 | Type::U16 | Type::U32 | Type::U64 => d.u64()?,

            // Signed ints go into a u64 if positive, if negative they'll return a negative
            // overflow error. This method can also return a positive overflow but that won't
            // happen in practice.
            Type::I8 | Type::I16 | Type::I32 | Type::I64 => d.i64()?.value_into()?,

            // Floats can be negative or have a fractional component so they don't go nicely
            // into an unsigned integer. This method will try and convert them and return err if
            // the conversion is not lossless.
            Type::F16 | Type::F32 | Type::F64 => f64_to_u64(d.f64()?)?,

            Type::Tag => match d.tag()? {
                Tag::PosBignum => u64_from_be_bytes(d.bytes()?)?,
                tag => {
                    return Err(DataTypeDecodeError::Other(format!(
                        "Expected PosBignum tag. Received: {:?}",
                        tag
                    )));
                }
            },

            t => {
                return data_type.as_decode_not_supported(t);
            }
        }),

        DataType::Float64 => Value::Float64(match d.datatype()? {
            // Smaller unsigned ints go fine into an f64
            // A u64 can result in a positive overflow error when it's too big to fit.
            Type::U8 | Type::U16 | Type::U32 | Type::U64 => d.u64()?.value_into()?,

            // Smaller signed ints go fine into an f64
            // An i64 might lose precision which will result in a range error
            Type::I8 | Type::I16 | Type::I32 | Type::I64 => d.i64()?.value_into()?,

            // All floats fit fine into an f64
            Type::F16 | Type::F32 | Type::F64 => d.f64()?,

            t => {
                return data_type.as_decode_not_supported(t);
            }
        }),

        DataType::String => Value::String(match d.datatype()? {
            Type::String => d.str()?.nfc().collect(),
            t => {
                return data_type.as_decode_not_supported(t);
            }
        }),

        DataType::Boolean => Value::Boolean(match d.datatype()? {
            Type::Bool => d.bool()?,
            t => {
                return data_type.as_decode_not_supported(t);
            }
        }),

        DataType::Date => match d.datatype()? {
            Type::Tag => match d.tag()? {
                Tag::Timestamp => Value::date_from_millis(match d.datatype()? {
                    Type::U8
                    | Type::U16
                    | Type::U32
                    | Type::U64
                    | Type::I8
                    | Type::I16
                    | Type::I32
                    | Type::I64 => {
                        // If the seconds in the timestamp are exact it's possible this will come through as an int
                        (i128::from(d.int()?) * 1000) as i64
                    }

                    // The standard says that f64 is the only type of float will be sent through as a timestamp
                    Type::F64 => (d.f64()? * 1000.) as i64,

                    t => return data_type.as_decode_not_supported(t),
                }),
                tag => {
                    return Err(DataTypeDecodeError::Other(format!(
                        "Expected date time tag. Received: {:?}",
                        tag
                    )));
                }
            },
            t => {
                return data_type.as_decode_not_supported(t);
            }
        },
    })
}

#[cfg(test)]
mod tests {
    use super::u64_from_be_bytes;

    #[test]
    fn test_u64_from_bytes() {
        let u8_bytes = 123_u8.to_be_bytes();
        let u16_bytes = 123_u16.to_be_bytes();
        let u32_bytes = 123_u32.to_be_bytes();
        let u64_bytes = 123_u64.to_be_bytes();
        let u128_bytes = 123_u128.to_be_bytes();

        let padded_bytes = [0, 0, 123];

        assert_eq!(u64_from_be_bytes(&u8_bytes).unwrap(), 123);
        assert_eq!(u64_from_be_bytes(&u16_bytes).unwrap(), 123);
        assert_eq!(u64_from_be_bytes(&u32_bytes).unwrap(), 123);
        assert_eq!(u64_from_be_bytes(&u64_bytes).unwrap(), 123);
        assert_eq!(u64_from_be_bytes(&padded_bytes).unwrap(), 123);

        assert_eq!(
            u64_from_be_bytes(&u128_bytes).unwrap_err().to_string(),
            "Bytes do not fit in u64. Expected length 8, got 16"
        );

        assert_eq!(
            u64_from_be_bytes(&[]).unwrap_err().to_string(),
            "Provided byte slice was empty"
        );
    }
}