utf16string/error.rs
1//! Implementations for [`Utf16Error`].
2
3use std::error::Error;
4use std::fmt;
5
6use crate::Utf16Error;
7
8impl fmt::Display for Utf16Error {
9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10 write!(f, "Invalid UTF-16LE data in byte slice")
11 }
12}
13
14impl Error for Utf16Error {}
15
16impl Utf16Error {
17 /// Returns the index in given bytes up to which valid UTF-16 was verified.
18 pub fn valid_up_to(&self) -> usize {
19 self.valid_up_to
20 }
21
22 /// Return the length of the error if it is recoverable.
23 ///
24 /// - `None`: the end of the input was reached unexpectedly.
25 /// [`Utf16Error::valid_up_to`] is 1 to 3 bytes from the end of the input. If a byte
26 /// stream such as a file or a network socket is being decoded incrementally, this
27 /// could still be a valid char whose byte sequence is spanning multiple chunks.
28 ///
29 /// - `Some(len)`: an unexpected byte was encountered. The length provided is that of
30 /// the invalid byte sequence that starts at the index given by
31 /// [`Utf16Error::valid_up_to`]. Decoding should resume after that sequence (after
32 /// inserting a [`U+FFFD REPLACEMENT CHARACTER`](std::char::REPLACEMENT_CHARACTER)) in
33 /// case of lossy decoding. In fact for UTF-16 the `len` reported here will always be
34 /// exactly 2 since this never looks ahead to see if the bytes following the error
35 /// sequence are valid as well as otherwise you would not know how many replacement
36 /// characters to insert when writing a lossy decoder.
37 ///
38 /// The semantics of this API are compatible with the semantics of
39 /// [`Utf8Error`](std::str::Utf8Error).
40 pub fn error_len(&self) -> Option<usize> {
41 self.error_len.map(|len| len.into())
42 }
43}