1// Copyright (c) 2017-2018 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#![deny(missing_docs)]
8
9use std::convert::From;
10use std::num;
11use std::string;
12use std::fmt;
13use std::net;
14
15use base64;
16use jid;
17use chrono;
18
19/// Contains one of the potential errors triggered while parsing an
20/// [Element](../struct.Element.html) into a specialised struct.
21#[derive(Debug)]
22pub enum Error {
23 /// The usual error when parsing something.
24 ///
25 /// TODO: use a structured error so the user can report it better, instead
26 /// of a freeform string.
27 ParseError(&'static str),
28
29 /// Generated when some base64 content fails to decode, usually due to
30 /// extra characters.
31 Base64Error(base64::DecodeError),
32
33 /// Generated when text which should be an integer fails to parse.
34 ParseIntError(num::ParseIntError),
35
36 /// Generated when text which should be a string fails to parse.
37 ParseStringError(string::ParseError),
38
39 /// Generated when text which should be an IP address (IPv4 or IPv6) fails
40 /// to parse.
41 ParseAddrError(net::AddrParseError),
42
43 /// Generated when text which should be a [JID](../../jid/struct.Jid.html)
44 /// fails to parse.
45 JidParseError(jid::JidParseError),
46
47 /// Generated when text which should be a
48 /// [DateTime](../date/struct.DateTime.html) fails to parse.
49 ChronoParseError(chrono::ParseError),
50}
51
52impl fmt::Display for Error {
53 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
54 match *self {
55 Error::ParseError(s) => write!(fmt, "{}", s),
56 Error::Base64Error(ref e) => write!(fmt, "{}", e),
57 Error::ParseIntError(ref e) => write!(fmt, "{}", e),
58 Error::ParseStringError(ref e) => write!(fmt, "{}", e),
59 Error::ParseAddrError(ref e) => write!(fmt, "{}", e),
60 Error::JidParseError(_) => write!(fmt, "JID parse error"),
61 Error::ChronoParseError(ref e) => write!(fmt, "{}", e),
62 }
63 }
64}
65
66impl From<base64::DecodeError> for Error {
67 fn from(err: base64::DecodeError) -> Error {
68 Error::Base64Error(err)
69 }
70}
71
72impl From<num::ParseIntError> for Error {
73 fn from(err: num::ParseIntError) -> Error {
74 Error::ParseIntError(err)
75 }
76}
77
78impl From<string::ParseError> for Error {
79 fn from(err: string::ParseError) -> Error {
80 Error::ParseStringError(err)
81 }
82}
83
84impl From<net::AddrParseError> for Error {
85 fn from(err: net::AddrParseError) -> Error {
86 Error::ParseAddrError(err)
87 }
88}
89
90impl From<jid::JidParseError> for Error {
91 fn from(err: jid::JidParseError) -> Error {
92 Error::JidParseError(err)
93 }
94}
95
96impl From<chrono::ParseError> for Error {
97 fn from(err: chrono::ParseError) -> Error {
98 Error::ChronoParseError(err)
99 }
100}