-
Notifications
You must be signed in to change notification settings - Fork 144
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
isabelatkinson
merged 2 commits into
mongodb:main
from
sanav33:RUST-1225/add-base64-to-binary-method
Nov 30, 2022
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`]. | ||
/// | ||
/// ```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>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
mod binary; | ||
mod bson; | ||
mod document; | ||
mod lock; | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.