kdb_codec 1.1.0

Kdb+ IPC codec library for handling kdb+ wire protocol data with Rust.
Documentation
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! This module provides error implementation.

//++++++++++++++++++++++++++++++++++++++++++++++++++//
// >> Load Libraries
//++++++++++++++++++++++++++++++++++++++++++++++++++//

use super::K;
use crate::qtype;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IOError;

//++++++++++++++++++++++++++++++++++++++++++++++++++//
// >>  Structs
//++++++++++++++++++++++++++++++++++++++++++++++++++//

/// Error from network IO or invalid operation.
pub enum Error {
    /// Invalid time was used to build `Date` or `DateTime`.
    InvalidDateTime,
    /// Network error.
    IO(IOError),
    /// Network error with custom message.
    NetworkError(String),
    /// Invalid message size.
    InvalidMessageSize,
    /// Tried to cast to wrong type.
    InvalidCast {
        from: &'static str,
        to: &'static str,
    },
    /// Tried to cast a list to wrong type.
    InvalidCastList(&'static str),
    /// Tried to access an index which is out of range.
    IndexOutOfBounds { length: usize, index: usize },
    /// Invalid operation to a wrong type.
    InvalidOperation {
        operator: &'static str,
        operand_type: &'static str,
        expected: Option<&'static str>,
    },
    /// Length of dictionary key and value do not match.
    LengthMismatch {
        key_length: usize,
        value_length: usize,
    },
    /// Tried to get non-existing column.
    NoSuchColumn(String),
    /// Tried to insert or push wrong element.
    InsertWrongElement {
        is_insert: bool,
        destination: &'static str,
        expected: &'static str,
    },
    /// Tried to pop from empty list.
    PopFromEmptyList,
    /// Tried to convert but coluld not.
    Object(K),
    /// Deserialization error with custom message.
    DeserializationError(String),
    /// Buffer too small for the requested operation.
    InsufficientData { needed: usize, available: usize },
    /// Invalid type byte encountered during deserialization.
    InvalidType(i8),
    /// Missing null terminator in symbol or string data.
    MissingNullTerminator,
    /// Invalid UTF-8 sequence in string data.
    InvalidUtf8,
    /// Maximum recursion depth exceeded during deserialization.
    MaxDepthExceeded { depth: usize, max: usize },
    /// List size exceeds maximum allowed size.
    ListTooLarge { size: usize, max: usize },
    /// Integer overflow in size calculation.
    SizeOverflow,
}

//++++++++++++++++++++++++++++++++++++++++++++++++++//
// >> Implementation
//++++++++++++++++++++++++++++++++++++++++++++++++++//

impl Error {
    /// Construct `InvalidCast` error.
    pub(crate) fn invalid_cast(from: i8, to: i8) -> Self {
        Self::InvalidCast {
            from: type_to_string(from),
            to: type_to_string(to),
        }
    }

    /// Construct `InvalidCastList` error.
    pub(crate) fn invalid_cast_list(from: i8) -> Self {
        Self::InvalidCastList(type_to_string(from))
    }

    /// Construct `IndexOutOfBounds` error.
    pub(crate) fn index_out_of_bounds(length: usize, index: usize) -> Self {
        Self::IndexOutOfBounds { length, index }
    }

    /// Construct `InvalidOperation` error.
    pub(crate) fn invalid_operation(
        operator: &'static str,
        operand_type: i8,
        expected: Option<i8>,
    ) -> Self {
        Self::InvalidOperation {
            operator,
            operand_type: type_to_string(operand_type),
            expected: expected.map(|type_id| type_to_string(type_id)),
        }
    }

    /// Construct `LengthMismatch` error.
    pub(crate) fn length_mismatch(key_length: usize, value_length: usize) -> Self {
        Self::LengthMismatch {
            key_length,
            value_length,
        }
    }

    /// Construct `NoSuchColumn` error.
    pub(crate) fn no_such_column(column: String) -> Self {
        Self::NoSuchColumn(column)
    }

    /// Construct `InsertWrongElement` error.
    pub(crate) fn insert_wrong_element(
        is_insert: bool,
        destination: i8,
        expected: &'static str,
    ) -> Self {
        Self::InsertWrongElement {
            is_insert,
            destination: type_to_string(destination),
            expected,
        }
    }

    /// Construct `PopFromEmptyList` error.
    pub(crate) fn pop_from_empty_list() -> Self {
        Self::PopFromEmptyList
    }

    /// Construct returned object as a result of an error.
    pub(crate) fn object(returned: K) -> Self {
        Self::Object(returned)
    }

    /// Comsume error and retrieve original object returned from some operation.
    /// `None` is returned if the error does not contain `K` object.
    /// ```
    /// use kdb_codec::*;
    ///
    /// fn main(){
    ///   let int = K::new_int(777);
    ///   match int.flip(){
    ///     Ok(_) => eprintln!("miracle!!"),
    ///     Err(original_) => {
    ///       let original = original_.into_inner().unwrap();
    ///       assert_eq!(original.get_int().unwrap(), 777);
    ///     }
    ///   }
    /// }
    /// ```
    pub fn into_inner(self) -> Option<K> {
        match self {
            Self::Object(object) => Some(object),
            _ => None,
        }
    }
}

impl From<IOError> for Error {
    fn from(error: IOError) -> Self {
        Self::IO(error)
    }
}

impl PartialEq<Self> for Error {
    fn eq(&self, other: &Error) -> bool {
        match (self, other) {
            (Self::IO(left), Self::IO(right)) => left.to_string() == right.to_string(),
            (Self::IO(_), _) => false,
            (Self::NetworkError(left), Self::NetworkError(right)) => left == right,
            (Self::InvalidMessageSize, Self::InvalidMessageSize) => true,
            (Self::InvalidCast { from: f, to: t }, Self::InvalidCast { from: f2, to: t2 }) => {
                f == f2 && t == t2
            }
            (Self::InvalidCastList(left), Self::InvalidCastList(right)) => left == right,
            (
                Self::IndexOutOfBounds {
                    length: l,
                    index: i,
                },
                Self::IndexOutOfBounds {
                    length: l2,
                    index: i2,
                },
            ) => l == l2 && i == i2,
            (
                Self::InvalidOperation {
                    operator: o,
                    operand_type: ot,
                    expected: e,
                },
                Self::InvalidOperation {
                    operator: o2,
                    operand_type: ot2,
                    expected: e2,
                },
            ) => o == o2 && ot == ot2 && e == e2,
            (
                Self::LengthMismatch {
                    key_length: k,
                    value_length: l,
                },
                Self::LengthMismatch {
                    key_length: k2,
                    value_length: l2,
                },
            ) => k == k2 && l == l2,
            (Self::NoSuchColumn(left), Self::NoSuchColumn(right)) => left == right,
            (
                Self::InsertWrongElement {
                    is_insert: i,
                    destination: d,
                    expected: e,
                },
                Self::InsertWrongElement {
                    is_insert: i2,
                    destination: d2,
                    expected: e2,
                },
            ) => i == i2 && d == d2 && e == e2,
            (Self::Object(left), Self::Object(right)) => {
                left.0.qtype == right.0.qtype && left.0.attribute == right.0.attribute
            }
            (Self::PopFromEmptyList, Self::PopFromEmptyList) => true,
            _ => false,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InvalidDateTime => write!(f, "invalid datetime"),
            Self::IO(error) => write!(f, "IO error: {}", error),
            Self::NetworkError(msg) => write!(f, "Network error: {}", msg),
            Self::InvalidMessageSize => write!(f, "Invalid message size"),
            Self::InvalidCast { from, to } => write!(f, "invalid cast from {} to {}", from, to),
            Self::InvalidCastList(from) => {
                write!(f, "invalid cast from {} to list of generics T", from)
            }
            Self::IndexOutOfBounds { length, index } => write!(
                f,
                "index out of bounds: specified {} but length is {}",
                index, length
            ),
            Self::InvalidOperation {
                operator,
                operand_type,
                expected,
            } => match expected {
                Some(expected_type) => write!(
                    f,
                    "invalid operation {} on {}. expected: {}",
                    operator, operand_type, expected_type
                ),
                None => write!(f, "invalid operation {} on {}", operator, operand_type),
            },
            Self::LengthMismatch {
                key_length,
                value_length,
            } => write!(
                f,
                "key-value length mismatch: {} and {}",
                key_length, value_length
            ),
            Self::NoSuchColumn(column) => write!(f, "no such column: {}", column),
            Self::InsertWrongElement {
                is_insert,
                destination,
                expected,
            } => {
                let operation = match is_insert {
                    true => "insert",
                    false => "push",
                };
                write!(
                    f,
                    "{} wrong element to {}: expected {}",
                    operation, destination, expected
                )
            }
            Self::Object(object) => write!(f, "{}", object),
            Self::PopFromEmptyList => write!(f, "pop from empty list"),
            Self::DeserializationError(msg) => write!(f, "deserialization error: {}", msg),
            Self::InsufficientData { needed, available } => write!(
                f,
                "insufficient data: needed {} bytes but only {} available",
                needed, available
            ),
            Self::InvalidType(qtype) => {
                write!(f, "unsupported or invalid q type byte: {}", qtype)
            }
            Self::MissingNullTerminator => write!(f, "missing null terminator in symbol or string"),
            Self::InvalidUtf8 => write!(f, "invalid UTF-8 sequence"),
            Self::MaxDepthExceeded { depth, max } => write!(
                f,
                "maximum recursion depth exceeded: {} (max: {})",
                depth, max
            ),
            Self::ListTooLarge { size, max } => {
                write!(f, "list size {} exceeds maximum allowed size {}", size, max)
            }
            Self::SizeOverflow => write!(f, "integer overflow in size calculation"),
        }
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InvalidDateTime => write!(f, "invalid datetime"),
            Self::IO(error) => write!(f, "IO error: {:?}", error),
            Self::NetworkError(msg) => write!(f, "Network error: {}", msg),
            Self::InvalidMessageSize => write!(f, "Invalid message size"),
            Self::InvalidCast { from, to } => write!(f, "invalid cast from {} to {}", from, to),
            Self::InvalidCastList(from) => {
                write!(f, "invalid cast from {} to list of generics T", from)
            }
            Self::IndexOutOfBounds { length, index } => write!(
                f,
                "index out of bounds: specified {} but length is {}",
                index, length
            ),
            Self::InvalidOperation {
                operator,
                operand_type,
                expected,
            } => match expected {
                Some(expected_type) => write!(
                    f,
                    "invalid operation {} on {}. expected: {}",
                    operator, operand_type, expected_type
                ),
                None => write!(f, "invalid operation {} on {}", operator, operand_type),
            },
            Self::LengthMismatch {
                key_length,
                value_length,
            } => write!(
                f,
                "key-value length mismatch: {} and {}",
                key_length, value_length
            ),
            Self::NoSuchColumn(column) => write!(f, "no such column: {}", column),
            Self::InsertWrongElement {
                is_insert,
                destination,
                expected,
            } => {
                let operation = match is_insert {
                    true => "insert",
                    false => "push",
                };
                write!(
                    f,
                    "{} wrong element to {}: expected {}",
                    operation, destination, expected
                )
            }
            Self::Object(object) => write!(f, "{}", object),
            Self::PopFromEmptyList => write!(f, "pop from empty list"),
            Self::DeserializationError(msg) => write!(f, "deserialization error: {}", msg),
            Self::InsufficientData { needed, available } => write!(
                f,
                "insufficient data: needed {} bytes but only {} available",
                needed, available
            ),
            Self::InvalidType(qtype) => {
                write!(f, "unsupported or invalid q type byte: {}", qtype)
            }
            Self::MissingNullTerminator => write!(f, "missing null terminator in symbol or string"),
            Self::InvalidUtf8 => write!(f, "invalid UTF-8 sequence"),
            Self::MaxDepthExceeded { depth, max } => write!(
                f,
                "maximum recursion depth exceeded: {} (max: {})",
                depth, max
            ),
            Self::ListTooLarge { size, max } => {
                write!(f, "list size {} exceeds maximum allowed size {}", size, max)
            }
            Self::SizeOverflow => write!(f, "integer overflow in size calculation"),
        }
    }
}

impl StdError for Error {}

//++++++++++++++++++++++++++++++++++++++++++++++++++//
// >> Private Function
//++++++++++++++++++++++++++++++++++++++++++++++++++//

/// Return a corresponding type name of a given type indicator.
fn type_to_string(qtype: i8) -> &'static str {
    match qtype {
        qtype::BOOL_ATOM => "bool",
        qtype::GUID_ATOM => "guid",
        qtype::BYTE_ATOM => "byte",
        qtype::SHORT_ATOM => "short",
        qtype::INT_ATOM => "int",
        qtype::LONG_ATOM => "long",
        qtype::REAL_ATOM => "real",
        qtype::FLOAT_ATOM => "float",
        qtype::CHAR => "char",
        qtype::SYMBOL_ATOM => "symbol",
        qtype::TIMESTAMP_ATOM => "timestamp",
        qtype::MONTH_ATOM => "month",
        qtype::DATE_ATOM => "date",
        qtype::DATETIME_ATOM => "datetime",
        qtype::TIMESPAN_ATOM => "timespan",
        qtype::MINUTE_ATOM => "minute",
        qtype::SECOND_ATOM => "second",
        qtype::TIME_ATOM => "time",
        qtype::COMPOUND_LIST => "compound list",
        qtype::BOOL_LIST => "bool list",
        qtype::GUID_LIST => "guid list",
        qtype::BYTE_LIST => "byte list",
        qtype::SHORT_LIST => "short list",
        qtype::INT_LIST => "int list",
        qtype::LONG_LIST => "long list",
        qtype::REAL_LIST => "real list",
        qtype::FLOAT_LIST => "float list",
        qtype::STRING => "string",
        qtype::SYMBOL_LIST => "symbol list",
        qtype::TIMESTAMP_LIST => "timestamp list",
        qtype::MONTH_LIST => "month list",
        qtype::DATE_LIST => "date list",
        qtype::DATETIME_LIST => "datetime list",
        qtype::TIMESPAN_LIST => "timespan list",
        qtype::MINUTE_LIST => "minute list",
        qtype::SECOND_LIST => "second list",
        qtype::TIME_LIST => "time list",
        qtype::TABLE => "table",
        qtype::DICTIONARY => "dictionary",
        qtype::NULL => "null",
        qtype::SORTED_DICTIONARY => "sorted dictionary",
        qtype::ERROR => "error",
        _ => "not supported",
    }
}