encode_unicode/
errors.rs

1/* Copyright 2016 The encode_unicode Developers
2 *
3 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 * http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 * http://opensource.org/licenses/MIT>, at your option. This file may not be
6 * copied, modified, or distributed except according to those terms.
7 */
8
9
10//! Boilerplatey error types
11
12extern crate core;
13use self::core::fmt::{self,Display,Formatter};
14#[cfg(feature="std")]
15use std::error::Error;
16
17
18macro_rules! description {($err:ty, $desc:expr) => {
19    #[cfg(not(feature="std"))]
20    impl $err {
21        #[allow(missing_docs)]
22        pub fn description(&self) -> &'static str {
23            ($desc)(self)
24        }
25    }
26    #[cfg(feature="std")]
27    impl Error for $err {
28        fn description(&self) -> &'static str {
29            ($desc)(self)
30        }
31    }
32    impl Display for $err {
33        fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
34            write!(fmtr, "{}", self.description())
35        }
36    }
37}}
38
39
40macro_rules! single_cause {(#[$doc1:meta] #[$doc2:meta] $err:ident => $desc:expr) => {
41    // Rust 1.15 doesn't understand $(#[$doc:meta])* $:ident
42    #[$doc1]
43    #[$doc2]
44    #[derive(Clone,Copy, Debug, PartialEq,Eq)]
45    pub struct $err;
46    description!{$err, |_| $desc }
47}}
48
49
50single_cause!{
51    /// Cannot tell whether an `u16` needs an extra unit,
52    /// because it's a trailing surrogate itself.
53    InvalidUtf16FirstUnit => "is a trailing surrogate"
54}
55
56single_cause!{
57    /// Cannot create an `Utf8Char` or `Utf16Char` from the first codepoint of a str,
58    /// because there are none.
59    EmptyStrError => "is empty"
60}
61
62single_cause!{
63    /// Cannot create an `Utf8Char` from a standalone `u8`
64    /// that is not an ASCII character.
65    NonAsciiError => "is not an ASCII character"
66}
67
68single_cause!{
69    /// Cannot create an `Utf16Char` from a standalone `u16` that is not a
70    /// codepoint in the basic multilingual plane, but part of a suurrogate pair.
71    NonBMPError => "is not a codepoint in the basic multilingual plane"
72}
73
74
75
76macro_rules! simple {(#[$tydoc:meta] $err:ident  {
77                          $($(#[$vardoc:meta])* ::$variant:ident => $string:expr),+,
78                      } ) => {
79    #[$tydoc]
80    #[derive(Clone,Copy, Debug, PartialEq,Eq)]
81    pub enum $err {
82        $($(#[$vardoc])* $variant),*
83    }
84    description!{$err, |e: &$err| match *e {$($err::$variant=>$string),*} }
85}}
86
87
88simple!{/// Reasons why an `u32` is not a valid UTF codepoint.
89    InvalidCodepoint {
90        /// It's reserved for UTF-16 surrogate pairs."
91        ::Utf16Reserved => "is reserved for UTF-16 surrogate pairs",
92        /// It's higher than the highest codepoint (which is 0x10ffff).
93        ::TooHigh => "is higher than the highest codepoint",
94    }}
95use self::InvalidCodepoint::*;
96impl InvalidCodepoint {
97    /// Get the range of values for which this error would be given.
98    pub fn error_range(self) -> (u32,u32) {match self {
99        Utf16Reserved => (0xd8_00, 0xdf_ff),
100        TooHigh => (0x00_10_ff_ff, 0xff_ff_ff_ff),
101    }}
102}
103
104
105simple!{/// Reasons why one or two `u16`s are not valid UTF-16, in sinking precedence.
106    InvalidUtf16Tuple {
107        /// The first unit is a trailing/low surrogate, which is never valid.
108        ///
109        /// Note that the value of a low surrogate is actually higher than a high surrogate.
110        ::FirstIsTrailingSurrogate => "the first unit is a trailing / low surrogate, which is never valid",
111        /// You provided a second unit, but the first one stands on its own.
112        ::SuperfluousSecond => "the second unit is superfluous",
113        /// The first and only unit requires a second unit.
114        ::MissingSecond => "the first unit requires a second unit",
115        /// The first unit requires a second unit, but it's not a trailing/low surrogate.
116        ///
117        /// Note that the value of a low surrogate is actually higher than a high surrogate.
118        ::InvalidSecond => "the required second unit is not a trailing / low surrogate",
119    }}
120
121
122simple!{/// Reasons why a slice of `u16`s doesn't start with valid UTF-16.
123    InvalidUtf16Slice {
124        /// The slice is empty.
125        ::EmptySlice => "the slice is empty",
126        /// The first unit is a low surrogate.
127        ::FirstLowSurrogate => "the first unit is a trailing surrogate",
128        /// The first and only unit requires a second unit.
129        ::MissingSecond => "the first and only unit requires a second one",
130        /// The first unit requires a second one, but it's not a trailing surrogate.
131        ::SecondNotLowSurrogate => "the required second unit is not a trailing surrogate",
132    }}
133
134simple!{/// Types of invalid sequences encountered by `Utf16CharParser`.
135    Utf16PairError {
136        /// A trailing surrogate was not preceeded by a leading surrogate.
137        ::UnexpectedTrailingSurrogate => "a trailing surrogate was not preceeded by a leading surrogate",
138        /// A leading surrogate was followed by an unit that was not a trailing surrogate.
139        ::UnmatchedLeadingSurrogate => "a leading surrogate was followed by an unit that was not a trailing surrogate",
140        /// A trailing surrogate was expected when the end was reached.
141        ::Incomplete => "a trailing surrogate was expected when the end was reached",
142    }}
143
144
145simple!{/// Reasons why `Utf8Char::from_str()` or `Utf16Char::from_str()` failed.
146    FromStrError {
147        /// `Utf8Char` or `Utf16Char` cannot store more than a single codepoint.
148        ::MultipleCodepoints => "has more than one codepoint",
149        /// `Utf8Char` or `Utf16Char` cannot be empty.
150        ::Empty => "is empty",
151    }}
152
153
154simple!{/// Reasons why a byte is not the start of a UTF-8 codepoint.
155    InvalidUtf8FirstByte {
156        /// Sequences cannot be longer than 4 bytes. Is given for values >= 240.
157        ::TooLongSeqence => "is greater than 247 (UTF-8 sequences cannot be longer than four bytes)",
158        /// This byte belongs to a previous sequence. Is given for values between 128 and 192 (exclusive).
159        ::ContinuationByte => "is a continuation of a previous sequence",
160    }}
161use self::InvalidUtf8FirstByte::*;
162
163
164
165macro_rules! complex {
166($err:ty
167 {$($sub:ty => $to:expr,)*}
168 {$($desc:pat => $string:expr),+,}
169 => $use_cause:expr =>
170 {$($cause:pat => $result:expr),+,} $(#[$causedoc:meta])*
171) => {
172    $(impl From<$sub> for $err {
173          fn from(error: $sub) -> $err {
174              $to(error)
175          }
176      })*
177    #[cfg(not(feature="std"))]
178    impl $err {
179        #[allow(missing_docs)]
180        pub fn description(&self) -> &'static str {
181            match *self{ $($desc => $string,)* }
182        }
183        /// A hack to avoid two Display impls
184        fn cause(&self) -> Option<&Display> {None}
185    }
186    #[cfg(feature="std")]
187    impl Error for $err {
188        fn description(&self) -> &'static str {
189            match *self{ $($desc => $string,)* }
190        }
191        $(#[$causedoc])*
192        fn cause(&self) -> Option<&Error> {
193            match *self{ $($cause => $result,)* }
194        }
195    }
196    impl Display for $err {
197        fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
198            match (self.cause(), $use_cause) {
199                (Some(d),true) => write!(fmtr, "{}: {}", self.description(), d),
200                        _      => write!(fmtr, "{}", self.description()),
201            }
202        }
203    }
204}}
205
206
207/// Reasons why a byte sequence is not valid UTF-8, excluding invalid codepoint.
208/// In sinking precedence.
209#[derive(Clone,Copy, Debug, PartialEq,Eq)]
210pub enum InvalidUtf8 {
211    /// Something is wrong with the first byte.
212    FirstByte(InvalidUtf8FirstByte),
213    /// The byte at index 1...3 should be a continuation byte,
214    /// but dosesn't fit the pattern 0b10xx_xxxx.
215    NotAContinuationByte(usize),
216    /// There are too many leading zeros: it could be a byte shorter.
217    ///
218    /// [Decoding this could allow someone to input otherwise prohibited
219    /// characters and sequences, such as "../"](https://tools.ietf.org/html/rfc3629#section-10).
220    OverLong,
221}
222use self::InvalidUtf8::*;
223complex!{InvalidUtf8 {
224        InvalidUtf8FirstByte => FirstByte,
225    } {
226        FirstByte(TooLongSeqence) => "the first byte is greater than 239 (UTF-8 sequences cannot be longer than four bytes)",
227        FirstByte(ContinuationByte) => "the first byte is a continuation of a previous sequence",
228        OverLong => "the sequence contains too many zeros and could be shorter",
229        NotAContinuationByte(_) => "the sequence is too short",
230    } => false => {
231        FirstByte(ref cause) => Some(cause),
232        _ => None,
233    }/// Returns `Some` if the error is a `InvalidUtf8FirstByte`.
234}
235
236
237/// Reasons why a byte array is not valid UTF-8, in sinking precedence.
238#[derive(Clone,Copy, Debug, PartialEq,Eq)]
239pub enum InvalidUtf8Array {
240    /// Not a valid UTF-8 sequence.
241    Utf8(InvalidUtf8),
242    /// Not a valid unicode codepoint.
243    Codepoint(InvalidCodepoint),
244}
245complex!{InvalidUtf8Array {
246        InvalidUtf8 => InvalidUtf8Array::Utf8,
247        InvalidCodepoint => InvalidUtf8Array::Codepoint,
248    } {
249        InvalidUtf8Array::Utf8(_) => "the sequence is invalid UTF-8",
250        InvalidUtf8Array::Codepoint(_) => "the encoded codepoint is invalid",
251    } => true => {
252        InvalidUtf8Array::Utf8(ref u) => Some(u),
253        InvalidUtf8Array::Codepoint(ref c) => Some(c),
254    }/// Always returns `Some`.
255}
256
257
258/// Reasons why a byte slice is not valid UTF-8, in sinking precedence.
259#[derive(Clone,Copy, Debug, PartialEq,Eq)]
260pub enum InvalidUtf8Slice {
261    /// Something is certainly wrong with the first byte.
262    Utf8(InvalidUtf8),
263    /// The encoded codepoint is invalid:
264    Codepoint(InvalidCodepoint),
265    /// The slice is too short; n bytes was required.
266    TooShort(usize),
267}
268complex!{InvalidUtf8Slice {
269        InvalidUtf8 => InvalidUtf8Slice::Utf8,
270        InvalidCodepoint => InvalidUtf8Slice::Codepoint,
271    } {
272        InvalidUtf8Slice::Utf8(_) => "the sequence is invalid UTF-8",
273        InvalidUtf8Slice::Codepoint(_) => "the encoded codepoint is invalid",
274        InvalidUtf8Slice::TooShort(1) => "the slice is empty",
275        InvalidUtf8Slice::TooShort(_) => "the slice is shorter than the sequence",
276    } => true => {
277        InvalidUtf8Slice::Utf8(ref u) => Some(u),
278        InvalidUtf8Slice::Codepoint(ref c) => Some(c),
279        InvalidUtf8Slice::TooShort(_) => None,
280    }
281}