| 1 |
use std::{error, fmt, fmt::Display, io, sync::Arc}; |
| 2 |
|
| 3 |
use serde::ser; |
| 4 |
|
| 5 |
use crate::bson::Bson; |
| 6 |
|
| 7 |
/// Possible errors that can arise during encoding. |
| 8 |
#[derive(Clone, Debug)] |
| 9 |
#[non_exhaustive] |
| 10 |
pub enum Error { |
| 11 |
/// A [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) encountered while serializing. |
| 12 |
Io(Arc<io::Error>), |
| 13 |
|
| 14 |
/// A key could not be serialized to a BSON string. |
| 15 |
InvalidDocumentKey(Bson), |
| 16 |
|
| 17 |
/// An invalid string was specified. |
| 18 |
InvalidCString(String), |
| 19 |
|
| 20 |
/// A general error that occurred during serialization. |
| 21 |
/// See: <https://docs.rs/serde/1.0.110/serde/ser/trait.Error.html#tymethod.custom> |
| 22 |
#[non_exhaustive] |
| 23 |
SerializationError { |
| 24 |
/// A message describing the error. |
| 25 |
message: String, |
| 26 |
}, |
| 27 |
|
| 28 |
/// An unsigned integer type could not fit into a signed integer type. |
| 29 |
UnsignedIntegerExceededRange(u64), |
| 30 |
} |
| 31 |
|
| 32 |
impl From<io::Error> for Error { |
| 33 |
fn from(err: io::Error) -> Error { |
| 34 |
Error::Io(Arc::new(err)) |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
impl fmt::Display for Error { |
| 39 |
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 40 |
match *self { |
| 41 |
Error::Io(ref inner) => inner.fmt(fmt), |
| 42 |
Error::InvalidDocumentKey(ref key) => write!(fmt, "Invalid map key type: {}", key), |
| 43 |
Error::InvalidCString(ref string) => { |
| 44 |
write!(fmt, "cstrings cannot contain null bytes: {:?}", string) |
| 45 |
} |
| 46 |
Error::SerializationError { ref message } => message.fmt(fmt), |
| 47 |
Error::UnsignedIntegerExceededRange(value) => write!( |
| 48 |
fmt, |
| 49 |
"BSON does not support unsigned integers. |
| 50 |
An attempt to serialize the value: {} in a signed type failed due to the value's \ |
| 51 |
size.", |
| 52 |
value |
| 53 |
), |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
impl error::Error for Error { |
| 59 |
fn cause(&self) -> Option<&dyn error::Error> { |
| 60 |
match *self { |
| 61 |
Error::Io(ref inner) => Some(inner.as_ref()), |
| 62 |
_ => None, |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
impl ser::Error for Error { |
| 68 |
fn custom<T: Display>(msg: T) -> Error { |
| 69 |
Error::SerializationError { |
| 70 |
message: msg.to_string(), |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
/// Alias for `Result<T, Error>`. |
| 76 |
pub type Result<T> = std::result::Result<T, Error>; |