csv_stream/
error.rs

1use std::error::Error as StdError;
2use std::fmt;
3use std::result;
4
5/// A type alias for `Result<T, csv_stream::Error>`.
6pub type Result<T> = result::Result<T, Error>;
7
8/// An error that can occur when processing CSV data.
9///
10/// This error can happen when writing or reading CSV data.
11///
12/// There are some important scenarios where an error is impossible to occur.
13/// For example, if a CSV reader is used on an in-memory buffer with the
14/// `flexible` option enabled and one is reading records as raw byte strings,
15/// then no error can occur.
16#[derive(Debug)]
17pub struct Error(Box<ErrorKind>);
18
19impl Error {
20    /// A crate private constructor for `Error`.
21    pub(crate) fn new(kind: ErrorKind) -> Error {
22        Error(Box::new(kind))
23    }
24
25    /// Return the specific type of this error.
26    pub fn kind(&self) -> &ErrorKind {
27        &self.0
28    }
29
30    /// Unwrap this error into its underlying type.
31    pub fn into_kind(self) -> ErrorKind {
32        *self.0
33    }
34}
35
36/// The specific type of an error.
37#[derive(Debug)]
38#[non_exhaustive]
39pub enum ErrorKind {
40    /// This error occurs when two records with an unequal number of fields
41    /// are found. This error only occurs when the `flexible` option in a
42    /// CSV reader/writer is disabled.
43    UnequalLengths {
44        /// The expected number of fields in a record. This is the number of
45        /// fields in the record read prior to the record indicated by
46        /// `pos`.
47        expected_len: u64,
48        /// The number of fields in the bad record.
49        len: u64,
50    },
51    /// An error of this kind occurs only when using the Serde serializer.
52    Serialize(String),
53}
54
55impl StdError for Error {
56    fn source(&self) -> Option<&(dyn StdError + 'static)> {
57        match *self.0 {
58            ErrorKind::UnequalLengths { .. } => None,
59            ErrorKind::Serialize(_) => None,
60        }
61    }
62}
63
64impl fmt::Display for Error {
65    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66        match *self.0 {
67            ErrorKind::UnequalLengths {
68                expected_len,
69                len,
70            } => {
71                write!(
72                    f,
73                    "CSV error: \
74                     found record with {} fields, but the previous record \
75                     has {} fields",
76                    len, expected_len
77                )
78            }
79            ErrorKind::Serialize(ref err) => {
80                write!(f, "CSV write error: {}", err)
81            }
82        }
83    }
84}