compact_thrift_runtime/
error.rs

1use std::error::Error;
2use std::ffi::CStr;
3use std::ffi::c_char;
4use std::fmt::Debug;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::io::ErrorKind;
8use std::io::Error as IOError;
9
10#[derive(Clone,Debug)]
11pub enum ThriftError {
12    InvalidNumber,
13    InvalidString,
14    InvalidBinaryLen,
15    InvalidCollectionLen,
16    MissingField(FieldName),
17    MissingValue,
18    MissingStop,
19    DuplicateField,
20    InvalidType,
21    ReserveError,
22    IO(ErrorKind)
23}
24
25/// Store static strings used by field names as a single pointer to reduce size of the error enum.
26#[derive(Clone)]
27pub struct FieldName {
28    /// pointer to null-terminated static bytes
29    name: *const c_char,
30}
31
32// Safety: FieldName can only be constructed from static strings
33unsafe impl Send for FieldName {}
34unsafe impl Sync for FieldName {}
35
36impl From<&'static CStr> for FieldName {
37    fn from(value: &'static CStr) -> Self {
38        Self {
39            name: value.as_ptr()
40        }
41    }
42}
43
44impl From<&'static str> for FieldName {
45    fn from(value: &'static str) -> Self {
46        assert!(!value.is_empty() && value.as_bytes()[value.len()-1] == b'\0');
47        Self {
48            name: value.as_ptr().cast::<c_char>()
49        }
50    }
51}
52
53impl Debug for FieldName {
54    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55        unsafe { Debug::fmt(CStr::from_ptr(self.name), f) }
56    }
57}
58
59impl Display for FieldName {
60    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
61        unsafe { Display::fmt(&CStr::from_ptr(self.name).to_string_lossy(), f) }
62    }
63}
64
65impl Display for ThriftError {
66    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67        <Self as Debug>::fmt(self, f)
68    }
69}
70
71impl Error for ThriftError {
72
73}
74
75impl From<IOError> for ThriftError {
76    fn from(e: IOError) -> Self {
77        Self::IO(e.kind())
78    }
79}
80
81impl From<ErrorKind> for ThriftError {
82    fn from(kind: ErrorKind) -> Self {
83        Self::IO(kind)
84    }
85}