compact_thrift_runtime/
error.rs

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
use std::error::Error;
use std::ffi::CStr;
use std::ffi::c_char;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::io::ErrorKind;
use std::io::Error as IOError;

#[derive(Clone,Debug)]
pub enum ThriftError {
    InvalidNumber,
    InvalidString,
    InvalidBinaryLen,
    InvalidCollectionLen,
    MissingField(FieldName),
    MissingValue,
    MissingStop,
    DuplicateField,
    InvalidType,
    ReserveError,
    IO(ErrorKind)
}

/// Store static strings used by field names as a single pointer to reduce size of the error enum.
#[derive(Clone)]
pub struct FieldName {
    /// pointer to null-terminated static bytes
    name: *const c_char,
}

// Safety: FieldName can only be constructed from static strings
unsafe impl Send for FieldName {}
unsafe impl Sync for FieldName {}

impl From<&'static CStr> for FieldName {
    fn from(value: &'static CStr) -> Self {
        Self {
            name: value.as_ptr()
        }
    }
}

impl From<&'static str> for FieldName {
    fn from(value: &'static str) -> Self {
        assert!(!value.is_empty() && value.as_bytes()[value.len()-1] == b'\0');
        Self {
            name: value.as_ptr().cast::<c_char>()
        }
    }
}

impl Debug for FieldName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        unsafe { Debug::fmt(CStr::from_ptr(self.name), f) }
    }
}

impl Display for FieldName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        unsafe { Display::fmt(&CStr::from_ptr(self.name).to_string_lossy(), f) }
    }
}

impl Display for ThriftError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        <Self as Debug>::fmt(self, f)
    }
}

impl Error for ThriftError {

}

impl From<IOError> for ThriftError {
    fn from(e: IOError) -> Self {
        Self::IO(e.kind())
    }
}

impl From<ErrorKind> for ThriftError {
    fn from(kind: ErrorKind) -> Self {
        Self::IO(kind)
    }
}