#! Module containing functionality related to BSON binary values.
mod vector;
use crate::{base64, spec::BinarySubtype, Document, RawBinaryRef};
use std::{
convert::TryFrom,
error,
fmt::{self, Display},
};
pub use vector::{PackedBitVector, Vector};
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Binary {
pub subtype: BinarySubtype,
pub bytes: Vec<u8>,
}
impl Display for Binary {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"Binary({:#x}, {})",
u8::from(self.subtype),
base64::encode(&self.bytes)
)
}
}
impl Binary {
pub fn from_base64(
input: impl AsRef<str>,
subtype: impl Into<Option<BinarySubtype>>,
) -> Result<Self> {
let bytes = base64::decode(input.as_ref()).map_err(|e| Error::DecodingError {
message: e.to_string(),
})?;
let subtype = match subtype.into() {
Some(s) => s,
None => BinarySubtype::Generic,
};
Ok(Binary { subtype, bytes })
}
pub(crate) fn from_extended_doc(doc: &Document) -> Option<Self> {
let binary_doc = doc.get_document("$binary").ok()?;
if let Ok(bytes) = binary_doc.get_str("base64") {
let bytes = base64::decode(bytes).ok()?;
let subtype = binary_doc.get_str("subType").ok()?;
let subtype = hex::decode(subtype).ok()?;
if subtype.len() == 1 {
Some(Self {
bytes,
subtype: subtype[0].into(),
})
} else {
None
}
} else {
let binary = binary_doc.get_binary_generic("bytes").ok()?;
let subtype = binary_doc.get_i32("subType").ok()?;
Some(Self {
bytes: binary.clone(),
subtype: u8::try_from(subtype).ok()?.into(),
})
}
}
pub fn as_raw_binary(&self) -> RawBinaryRef<'_> {
RawBinaryRef {
bytes: self.bytes.as_slice(),
subtype: self.subtype,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Error {
DecodingError { message: String },
Vector { message: String },
}
impl error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::DecodingError { message } => fmt.write_str(message),
Error::Vector { message } => fmt.write_str(message),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;