Skip to content

RUST-1225 Add base64 string constructor to Binary #365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/binary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use crate::{spec::BinarySubtype, Document, RawBinaryRef};
use std::{
convert::TryFrom,
error,
fmt::{self, Display},
};

/// Represents a BSON binary value.
#[derive(Debug, Clone, PartialEq)]
pub struct Binary {
/// The subtype of the bytes.
pub subtype: BinarySubtype,

/// The binary bytes.
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 {
/// Creates a [`Binary`] from a base64 string and optional [`BinarySubtype`]. If the
/// `subtype` argument is `None`, the [`Binary`] constructed will default to
/// [`BinarySubtype::Generic`].
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good to have a doc example here. I think the test we added for this would actually be pretty good.

///
/// ```rust
/// # use bson::{Binary, binary::Result};
/// # fn example() -> Result<()> {
/// let input = base64::encode("hello");
/// let binary = Binary::from_base64(input, None)?;
/// println!("{:?}", binary);
/// // binary: Binary { subtype: Generic, bytes: [104, 101, 108, 108, 111] }
/// # Ok(())
/// # }
/// ```
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 {
// in non-human-readable mode, RawBinary will serialize as
// { "$binary": { "bytes": <bytes>, "subType": <i32> } };
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(),
})
}
}

/// Borrow the contents as a `RawBinaryRef`.
pub fn as_raw_binary(&self) -> RawBinaryRef<'_> {
RawBinaryRef {
bytes: self.bytes.as_slice(),
subtype: self.subtype,
}
}
}

/// Possible errors that can arise during [`Binary`] construction.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Error {
/// While trying to decode from base64, an error was returned.
DecodingError { 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: m } => fmt.write_str(m),
}
}
}

pub type Result<T> = std::result::Result<T, Error>;
61 changes: 1 addition & 60 deletions src/bson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ pub use crate::document::Document;
use crate::{
oid::{self, ObjectId},
spec::{BinarySubtype, ElementType},
Binary,
Decimal128,
RawBinaryRef,
};

/// Possible BSON value types.
Expand Down Expand Up @@ -1080,65 +1080,6 @@ impl Display for JavaScriptCodeWithScope {
}
}

/// Represents a BSON binary value.
#[derive(Debug, Clone, PartialEq)]
pub struct Binary {
/// The subtype of the bytes.
pub subtype: BinarySubtype,

/// The binary bytes.
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(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 {
// in non-human-readable mode, RawBinary will serialize as
// { "$binary": { "bytes": <bytes>, "subType": <i32> } };
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(),
})
}
}

/// Borrow the contents as a `RawBinaryRef`.
pub fn as_raw_binary(&self) -> RawBinaryRef<'_> {
RawBinaryRef {
bytes: self.bytes.as_slice(),
subtype: self.subtype,
}
}
}

/// Represents a DBPointer. (Deprecated)
#[derive(Debug, Clone, PartialEq)]
pub struct DbPointer {
Expand Down
3 changes: 2 additions & 1 deletion src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@ pub use self::{
use std::io::Read;

use crate::{
bson::{Array, Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp},
bson::{Array, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp},
oid::{self, ObjectId},
raw::RawBinaryRef,
ser::write_i32,
spec::{self, BinarySubtype},
Binary,
Decimal128,
};

Expand Down
3 changes: 2 additions & 1 deletion src/de/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ use serde::de::{
use serde_bytes::ByteBuf;

use crate::{
bson::{Binary, Bson, DbPointer, JavaScriptCodeWithScope, Regex, Timestamp},
bson::{Bson, DbPointer, JavaScriptCodeWithScope, Regex, Timestamp},
datetime::DateTime,
document::{Document, IntoIter},
oid::ObjectId,
raw::{RawBsonRef, RAW_ARRAY_NEWTYPE, RAW_BSON_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
spec::BinarySubtype,
uuid::UUID_NEWTYPE_NAME,
Binary,
Decimal128,
};

Expand Down
3 changes: 2 additions & 1 deletion src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ use indexmap::IndexMap;
use serde::de::Error;

use crate::{
bson::{Array, Binary, Bson, Timestamp},
bson::{Array, Bson, Timestamp},
de::{deserialize_bson_kvp, ensure_read_exactly, read_i32, MIN_BSON_DOCUMENT_SIZE},
oid::ObjectId,
ser::{serialize_bson, write_i32},
spec::BinarySubtype,
Binary,
Decimal128,
};

Expand Down
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,9 @@

#[doc(inline)]
pub use self::{
bson::{Array, Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp},
bson::{Array, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp},
datetime::DateTime,
binary::Binary,
de::{
from_bson, from_bson_with_options, from_document, from_document_with_options, from_reader,
from_reader_utf8_lossy, from_slice, from_slice_utf8_lossy, Deserializer,
Expand All @@ -291,6 +292,7 @@ pub use self::{
#[macro_use]
mod macros;
mod bson;
pub mod binary;
pub mod datetime;
pub mod de;
pub mod decimal128;
Expand Down
21 changes: 21 additions & 0 deletions src/tests/modules/binary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use crate::{spec::BinarySubtype, tests::LOCK, Binary};

#[test]
fn binary_from_base64() {
let _guard = LOCK.run_concurrently();

let input = base64::encode("hello");
let produced = Binary::from_base64(input, None).unwrap();
let expected = Binary {
bytes: "hello".as_bytes().to_vec(),
subtype: BinarySubtype::Generic,
};
assert_eq!(produced, expected);

let produced = Binary::from_base64("", BinarySubtype::Uuid).unwrap();
let expected = Binary {
bytes: "".as_bytes().to_vec(),
subtype: BinarySubtype::Uuid,
};
assert_eq!(produced, expected);
}
1 change: 1 addition & 0 deletions src/tests/modules/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod binary;
mod bson;
mod document;
mod lock;
Expand Down