use std::{error, fmt, fmt::Display, io};
use serde::ser;
use crate::bson::Bson;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
IoError(io::Error),
InvalidMapKeyType {
key: Bson,
},
SerializationError {
message: String,
},
#[cfg(not(feature = "u2i"))]
UnsupportedUnsignedType,
#[cfg(feature = "u2i")]
UnsignedTypesValueExceedsRange(u64),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::IoError(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::IoError(ref inner) => inner.fmt(fmt),
Error::InvalidMapKeyType { ref key } => write!(fmt, "Invalid map key type: {}", key),
Error::SerializationError { ref message } => message.fmt(fmt),
#[cfg(not(feature = "u2i"))]
Error::UnsupportedUnsignedType => fmt.write_str("BSON does not support unsigned type"),
#[cfg(feature = "u2i")]
Error::UnsignedTypesValueExceedsRange(value) => write!(
fmt,
"BSON does not support unsigned types.
An attempt to serialize the value: {} in a signed type failed due to the value's \
size.",
value
),
}
}
}
impl error::Error for Error {
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
Error::IoError(ref inner) => Some(inner),
_ => None,
}
}
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Error {
Error::SerializationError {
message: msg.to_string(),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;