Debian Codegraph @

src/binary.rs

raw
1 use crate::{spec::BinarySubtype, Document, RawBinaryRef};
2 use std::{
3 convert::TryFrom,
4 error,
5 fmt::{self, Display},
6 };
7
8 /// Represents a BSON binary value.
9 #[derive(Debug, Clone, PartialEq)]
10 pub struct Binary {
11 /// The subtype of the bytes.
12 pub subtype: BinarySubtype,
13
14 /// The binary bytes.
15 pub bytes: Vec<u8>,
16 }
17
18 impl Display for Binary {
19 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
20 write!(
21 fmt,
22 "Binary({:#x}, {})",
23 u8::from(self.subtype),
24 base64::encode(&self.bytes)
25 )
26 }
27 }
28
29 impl Binary {
30 /// Creates a [`Binary`] from a base64 string and optional [`BinarySubtype`]. If the
31 /// `subtype` argument is [`None`], the [`Binary`] constructed will default to
32 /// [`BinarySubtype::Generic`].
33 ///
34 /// ```rust
35 /// # use bson::{Binary, binary::Result};
36 /// # fn example() -> Result<()> {
37 /// let input = base64::encode("hello");
38 /// let binary = Binary::from_base64(input, None)?;
39 /// println!("{:?}", binary);
40 /// // binary: Binary { subtype: Generic, bytes: [104, 101, 108, 108, 111] }
41 /// # Ok(())
42 /// # }
43 /// ```
44 pub fn from_base64(
45 input: impl AsRef<str>,
46 subtype: impl Into<Option<BinarySubtype>>,
47 ) -> Result<Self> {
48 let bytes = base64::decode(input.as_ref()).map_err(|e| Error::DecodingError {
49 message: e.to_string(),
50 })?;
51 let subtype = match subtype.into() {
52 Some(s) => s,
53 None => BinarySubtype::Generic,
54 };
55 Ok(Binary { subtype, bytes })
56 }
57
58 pub(crate) fn from_extended_doc(doc: &Document) -> Option<Self> {
59 let binary_doc = doc.get_document("$binary").ok()?;
60
61 if let Ok(bytes) = binary_doc.get_str("base64") {
62 let bytes = base64::decode(bytes).ok()?;
63 let subtype = binary_doc.get_str("subType").ok()?;
64 let subtype = hex::decode(subtype).ok()?;
65 if subtype.len() == 1 {
66 Some(Self {
67 bytes,
68 subtype: subtype[0].into(),
69 })
70 } else {
71 None
72 }
73 } else {
74 // in non-human-readable mode, RawBinary will serialize as
75 // { "$binary": { "bytes": <bytes>, "subType": <i32> } };
76 let binary = binary_doc.get_binary_generic("bytes").ok()?;
77 let subtype = binary_doc.get_i32("subType").ok()?;
78
79 Some(Self {
80 bytes: binary.clone(),
81 subtype: u8::try_from(subtype).ok()?.into(),
82 })
83 }
84 }
85
86 /// Borrow the contents as a [`RawBinaryRef`].
87 pub fn as_raw_binary(&self) -> RawBinaryRef<'_> {
88 RawBinaryRef {
89 bytes: self.bytes.as_slice(),
90 subtype: self.subtype,
91 }
92 }
93 }
94
95 /// Possible errors that can arise during [`Binary`] construction.
96 #[derive(Clone, Debug)]
97 #[non_exhaustive]
98 pub enum Error {
99 /// While trying to decode from base64, an error was returned.
100 DecodingError { message: String },
101 }
102
103 impl error::Error for Error {}
104
105 impl std::fmt::Display for Error {
106 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
107 match self {
108 Error::DecodingError { message: m } => fmt.write_str(m),
109 }
110 }
111 }
112
113 pub type Result<T> = std::result::Result<T, Error>;