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
extern crate serde;

use std;
use std::fmt::{self, Debug, Display};
use serde::{de};
use serde::ser::{self,Serialize, Serializer, SerializeMap};
use std::io;

pub type Result<T> = ::std::result::Result<T, Error>;

pub struct Error {
    pub err: Box<ErrorImpl>,
}

pub enum ErrorCode {
    Eof,
    Io(io::Error),
    Message(String),
    UnsupportedType,
    //// serialization errors
    UnsupportedTAType,
    UnsupportedCacheType, //temporary
    IntTooLargeFori64,
    //// deserialization errors
    UnmatchedCode(u8),
    Expectedi64, //rawinput read_int got bad int
    ExpectedNonZeroReadLength, //gave length 0 to ByteReader::read_bytes
    ExpectedDoubleCode,
    ExpectedFloatCode,
    ExpectedBooleanCode,
    ExpectedChunkBytesConclusion,
    ExpectedBytesCode,
    ExpectedStringCode,
    MapExpectedListCode,
    ExpectedListCode,
    InvalidUTF8,
    UnexpectedEof,
    AttemptToReadPastEnd,
}

pub struct ErrorImpl {
    pub code: ErrorCode,
    pub position: usize,
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize)]
pub enum Category {
    Io,
    Eof,
    De,
    Ser,
    Misc
}

impl ErrorImpl{
    pub fn classify(&self) -> Category {
        match self.code {
            ErrorCode::Eof => Category::Eof,

            ErrorCode::Io(_) => Category::Io,

            ErrorCode::UnsupportedType
            | ErrorCode::Message(_) => Category::Misc,

            ErrorCode::UnsupportedTAType
            | ErrorCode::UnsupportedCacheType
            | ErrorCode::IntTooLargeFori64 => Category::Ser,

            _ => Category::De
        }
    }
}

impl Serialize for ErrorImpl {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map_state = serializer.serialize_map(None)?;

        map_state.serialize_key("type")?;
        map_state.serialize_value("serde-fressian")?;

        map_state.serialize_key("category")?;
        map_state.serialize_value(&self.classify())?;

        map_state.serialize_key("position")?;
        map_state.serialize_value(&self.position)?;

        map_state.serialize_key("ErrorCode")?;

        match &self.code {
            ErrorCode::Io(_) => {
                map_state.serialize_value("IO::Error")?;
            }
            ErrorCode::Message(msg) => {
                map_state.serialize_value("Message")?;
                map_state.serialize_key("value")?;
                map_state.serialize_value(&msg)?;
            }
            ErrorCode::UnmatchedCode(code) => {
                map_state.serialize_value("UnmatchedCode")?;
                map_state.serialize_key("value")?;
                map_state.serialize_value(&code)?;
            }
            _ => {
                map_state.serialize_value(&self.code.to_string())?;
            }
        }

        map_state.end()
    }
}

impl Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.err.serialize(serializer)
    }
}

impl Error {
    pub fn is_eof(&self) -> bool { self.classify() == Category::Eof }

    pub fn classify(&self) -> Category { self.err.classify() }

    pub fn msg(msg: String) -> Self {
        Error {
            err: Box::new(ErrorImpl {
                code: ErrorCode::Message(msg),
                position: 0,
            }),
        }
    }

    //rename
    pub fn syntax(code: ErrorCode, position: usize) -> Self {
        Error {
            err: Box::new(ErrorImpl {
                code: code,
                position: position,
            }),
        }
    }

    pub fn unmatched_code(code: u8, position: usize) -> Self {
        Error {
            err: Box::new(ErrorImpl {
                code: ErrorCode::UnmatchedCode(code),
                position: position,
            }),
        }
    }

    pub fn eof(position: usize) -> Self {
        Error {
            err: Box::new(ErrorImpl {
                code: ErrorCode::Eof,
                position: position,
            }),
        }
    }
    pub fn io(error: io::Error) -> Self {
        Error {
            err: Box::new(ErrorImpl {
                code: ErrorCode::Io(error),
                position: 0
            }),
        }
    }

    // pub fn fix_position<F>(self, f: F) -> Self
    // where
    //     F: FnOnce(ErrorCode) -> Error,
    // {
    //     if self.err.line == 0 {
    //         f(self.err.code)
    //     } else {
    //         self
    //     }
    // }
}

impl Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ErrorCode::Eof => f.write_str("Eof"),
            ErrorCode::Message(ref msg) => f.write_str(msg),
            ErrorCode::Io(ref err) => Display::fmt(err, f),
            ErrorCode::UnmatchedCode(_code) => f.write_str("UnmatchedCode"),
            ErrorCode::UnsupportedType => f.write_str("UnsupportedType"),
            ErrorCode::UnsupportedTAType => f.write_str("UnsupportedTAType"),
            ErrorCode::UnsupportedCacheType => f.write_str("UnsupportedCacheType"),
            ErrorCode::AttemptToReadPastEnd => f.write_str("AttemptToReadPastEnd"),
            ErrorCode::UnexpectedEof => f.write_str("UnexpectedEof"),
            ErrorCode::ExpectedListCode => f.write_str("ExpectedListCode"),
            ErrorCode::MapExpectedListCode => f.write_str("MapExpectedListCode"),
            ErrorCode::IntTooLargeFori64 => f.write_str("IntTooLargeFori64"),
            ErrorCode::Expectedi64 => f.write_str("Expectedi64"),
            ErrorCode::ExpectedDoubleCode => f.write_str("ExpectedDoubleCode"),
            ErrorCode::ExpectedFloatCode => f.write_str("ExpectedFloatCode"),
            ErrorCode::ExpectedBooleanCode => f.write_str("ExpectedBooleanCode"),
            ErrorCode::ExpectedChunkBytesConclusion => f.write_str("ExpectedChunkBytesConclusion"),
            ErrorCode::ExpectedBytesCode => f.write_str("ExpectedBytesCode"),
            ErrorCode::InvalidUTF8 => f.write_str("InvalidUTF8"),
            ErrorCode::ExpectedStringCode => f.write_str("ExpectedStringCode"),
            ErrorCode::ExpectedNonZeroReadLength => f.write_str("ExpectedNonZeroReadLength")
        }
    }
}


impl Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str(std::error::Error::description(self))
    }
}

impl Display for ErrorImpl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.position == 0 {
            Display::fmt(&self.code, f)
        } else {
            write!(
                f,
                "{} at byte-position {}",
                self.code, self.position
            )
        }
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Error({:?}, byte-position: {})",
            self.err.code.to_string(), // is what unwrap() shows.
            self.err.position
        )
    }
}


impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
         Error::msg(msg.to_string())
    }
}

impl de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
         Error::msg(msg.to_string())
    }
}



impl std::error::Error for Error {
    fn description(&self) -> &str {
        match self.err.code {
            ErrorCode::Io(ref err) => std::error::Error::description(err),
            // should use Display::fmt or to_string().
            _ => "fressian error!",
        }
    }
}