Skip to content

Commit 5622ad4

Browse files
authored
RUST-2228 Normalize conversions between raw types and base crate types (#580)
1 parent 5f5e41d commit 5622ad4

33 files changed

+430
-430
lines changed

fuzz/fuzz_targets/decode.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ use bson::Document;
77
use std::io::Cursor;
88

99
fuzz_target!(|buf: &[u8]| {
10-
if let Ok(doc) = Document::decode_from_reader(&mut Cursor::new(&buf[..])) {
10+
if let Ok(doc) = Document::from_reader(&mut Cursor::new(&buf[..])) {
1111
let mut vec = Vec::with_capacity(buf.len());
12-
let _ = doc.encode_to_writer(&mut vec);
12+
let _ = doc.to_writer(&mut vec);
1313
}
1414
});

fuzz/fuzz_targets/encoding.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,12 @@ fn compare_values(val1: &Bson, val2: &Bson) -> bool {
4545
}
4646

4747
fuzz_target!(|input: &[u8]| {
48-
if let Ok(rawdoc) = RawDocument::decode_from_bytes(&input) {
48+
if let Ok(rawdoc) = RawDocument::from_bytes(&input) {
4949
if let Ok(doc) = Document::try_from(rawdoc) {
5050
let out = RawDocumentBuf::try_from(&doc).unwrap();
5151
let out_bytes = out.as_bytes();
5252
if input != out_bytes {
53-
let reencoded = RawDocument::decode_from_bytes(&out_bytes).unwrap();
53+
let reencoded = RawDocument::from_bytes(&out_bytes).unwrap();
5454
let reencoded_doc = Document::try_from(reencoded).unwrap();
5555
// Ensure that the re-encoded document is the same as the original document, the
5656
// bytes can differ while still resulting in the same Document.

fuzz/fuzz_targets/iterate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ extern crate bson;
55
use bson::RawDocument;
66

77
fuzz_target!(|buf: &[u8]| {
8-
if let Ok(doc) = RawDocument::decode_from_bytes(buf) {
8+
if let Ok(doc) = RawDocument::from_bytes(buf) {
99
for _ in doc {}
1010
}
1111
});

fuzz/fuzz_targets/raw_deserialize_utf8_lossy.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
#[macro_use]
33
extern crate libfuzzer_sys;
44
extern crate bson;
5-
use bson::{serde_helpers::Utf8LossyDeserialization, Document};
5+
use bson::{Document, Utf8Lossy};
66

77
fuzz_target!(|buf: &[u8]| {
8-
if let Ok(doc) = bson::deserialize_from_slice::<Utf8LossyDeserialization<Document>>(buf) {
8+
if let Ok(doc) = bson::deserialize_from_slice::<Utf8Lossy<Document>>(buf) {
99
let _ = bson::serialize_to_vec(&doc.0);
1010
}
1111
});

fuzz/fuzz_targets/string_handling.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use bson::{RawBsonRef, RawDocument};
66
use std::convert::TryInto;
77

88
fuzz_target!(|buf: &[u8]| {
9-
if let Ok(doc) = RawDocument::decode_from_bytes(buf) {
9+
if let Ok(doc) = RawDocument::from_bytes(buf) {
1010
for elem in doc.iter_elements().flatten() {
1111
// Convert to RawBsonRef and check string-related types
1212
if let Ok(bson) = elem.try_into() {

fuzz/fuzz_targets/type_markers.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use bson::{RawBsonRef, RawDocument};
66
use std::convert::TryInto;
77

88
fuzz_target!(|buf: &[u8]| {
9-
if let Ok(doc) = RawDocument::decode_from_bytes(buf) {
9+
if let Ok(doc) = RawDocument::from_bytes(buf) {
1010
for elem in doc.iter_elements().flatten() {
1111
let _: Result<RawBsonRef, _> = elem.try_into();
1212
}

fuzz/generate_corpus.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ fn generate_length_edge_cases(dir: &Path) -> std::io::Result<()> {
3030
fs::write(
3131
target_dir.join("min_doc"),
3232
min_doc
33-
.encode_to_vec()
33+
.to_vec()
3434
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?,
3535
)?;
3636

@@ -39,7 +39,7 @@ fn generate_length_edge_cases(dir: &Path) -> std::io::Result<()> {
3939
fs::write(
4040
target_dir.join("large_doc"),
4141
large_doc
42-
.encode_to_vec()
42+
.to_vec()
4343
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?,
4444
)?;
4545

@@ -78,7 +78,7 @@ fn generate_type_marker_cases(dir: &Path) -> std::io::Result<()> {
7878
fs::write(
7979
target_dir.join("all_types"),
8080
all_types
81-
.encode_to_vec()
81+
.to_vec()
8282
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?,
8383
)?;
8484

@@ -107,7 +107,7 @@ fn generate_string_edge_cases(dir: &Path) -> std::io::Result<()> {
107107
fs::write(
108108
target_dir.join("utf8_cases"),
109109
utf8_cases
110-
.encode_to_vec()
110+
.to_vec()
111111
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?,
112112
)?;
113113

@@ -133,7 +133,7 @@ fn generate_serialization_cases(dir: &Path) -> std::io::Result<()> {
133133
fs::write(
134134
target_dir.join("nested_doc"),
135135
nested_doc
136-
.encode_to_vec()
136+
.to_vec()
137137
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?,
138138
)?;
139139

@@ -147,7 +147,7 @@ fn generate_serialization_cases(dir: &Path) -> std::io::Result<()> {
147147
fs::write(
148148
target_dir.join("large_binary"),
149149
large_binary
150-
.encode_to_vec()
150+
.to_vec()
151151
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?,
152152
)?;
153153

serde-tests/test.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ use bson::{
2121
cstr,
2222
doc,
2323
oid::ObjectId,
24-
serde_helpers::Utf8LossyDeserialization,
2524
spec::BinarySubtype,
2625
Binary,
2726
Bson,
@@ -43,6 +42,7 @@ use bson::{
4342
RawRegexRef,
4443
Regex,
4544
Timestamp,
45+
Utf8Lossy,
4646
Uuid,
4747
};
4848

@@ -59,7 +59,7 @@ fn run_test<T>(expected_value: &T, expected_doc: &Document, description: &str)
5959
where
6060
T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug,
6161
{
62-
let expected_bytes = expected_doc.encode_to_vec().expect(description);
62+
let expected_bytes = expected_doc.to_vec().expect(description);
6363

6464
let expected_bytes_serde = bson::serialize_to_vec(&expected_value).expect(description);
6565

@@ -104,7 +104,7 @@ fn run_deserialize_test<T>(expected_value: &T, expected_doc: &Document, descript
104104
where
105105
T: DeserializeOwned + PartialEq + std::fmt::Debug,
106106
{
107-
let expected_bytes = expected_doc.encode_to_vec().expect(description);
107+
let expected_bytes = expected_doc.to_vec().expect(description);
108108

109109
assert_eq!(
110110
&bson::deserialize_from_document::<T>(expected_doc.clone()).expect(description),
@@ -445,7 +445,7 @@ fn type_conversion() {
445445
let deserialized: Foo = bson::deserialize_from_document(doc.clone()).unwrap();
446446
assert_eq!(deserialized, v);
447447

448-
let bytes = doc.encode_to_vec().unwrap();
448+
let bytes = doc.to_vec().unwrap();
449449

450450
let bson_deserialized: Foo = bson::deserialize_from_reader(bytes.as_slice()).unwrap();
451451
assert_eq!(bson_deserialized, v);
@@ -462,7 +462,7 @@ fn missing_errors() {
462462

463463
bson::deserialize_from_document::<Foo>(doc.clone()).unwrap_err();
464464

465-
let bytes = doc.encode_to_vec().unwrap();
465+
let bytes = doc.to_vec().unwrap();
466466

467467
bson::deserialize_from_reader::<_, Foo>(bytes.as_slice()).unwrap_err();
468468
}
@@ -681,7 +681,7 @@ fn unused_fields_deny() {
681681
bson::deserialize_from_document::<Foo>(doc.clone())
682682
.expect_err("extra fields should cause failure");
683683

684-
let bytes = doc.encode_to_vec().unwrap();
684+
let bytes = doc.to_vec().unwrap();
685685
bson::deserialize_from_reader::<_, Foo>(bytes.as_slice())
686686
.expect_err("extra fields should cause failure");
687687
}
@@ -946,7 +946,7 @@ impl AllTypes {
946946

947947
let decimal = {
948948
let bytes = hex::decode("18000000136400D0070000000000000000000000003A3000").unwrap();
949-
let d = Document::decode_from_reader(bytes.as_slice()).unwrap();
949+
let d = Document::from_reader(bytes.as_slice()).unwrap();
950950
match d.get("d") {
951951
Some(Bson::Decimal128(d)) => *d,
952952
c => panic!("expected decimal128, got {:?}", c),
@@ -1065,7 +1065,7 @@ fn all_raw_types_rmp() {
10651065
}
10661066
})
10671067
.unwrap();
1068-
let doc_buf = RawDocumentBuf::decode_from_bytes(doc_bytes).unwrap();
1068+
let doc_buf = RawDocumentBuf::from_bytes(doc_bytes).unwrap();
10691069
let document = &doc_buf;
10701070
let array = document.get_array("array").unwrap();
10711071

@@ -1121,7 +1121,7 @@ fn borrowed() {
11211121
"cow": "cow",
11221122
"array": ["borrowed string"],
11231123
};
1124-
let bson = doc.encode_to_vec().unwrap();
1124+
let bson = doc.to_vec().unwrap();
11251125

11261126
let s = "borrowed string".to_string();
11271127
let ss = "another borrowed string".to_string();
@@ -1315,7 +1315,7 @@ fn hint_cleared() {
13151315

13161316
let bytes = bson::serialize_to_vec(&doc_value).unwrap();
13171317

1318-
let doc = RawDocument::decode_from_bytes(&bytes).unwrap();
1318+
let doc = RawDocument::from_bytes(&bytes).unwrap();
13191319
let binary = doc.get_binary("binary").unwrap();
13201320

13211321
let f = Foo { doc, binary };
@@ -1336,5 +1336,5 @@ fn invalid_length() {
13361336
fn code_with_scope_too_long() {
13371337
// This is a regression test for fuzzer-generated input (RUST-2241).
13381338
let bytes = base64::decode("KAAAAAsBCRwPAAAACwFAAAAEAA8AEAAAAAYAAAAA9wD5/wAABgALAA==").unwrap();
1339-
assert!(bson::deserialize_from_slice::<Utf8LossyDeserialization<Document>>(&bytes).is_err());
1339+
assert!(bson::deserialize_from_slice::<Utf8Lossy<Document>>(&bytes).is_err());
13401340
}

src/de/raw.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ use crate::{
1919
RAW_BSON_NEWTYPE,
2020
RAW_DOCUMENT_NEWTYPE,
2121
},
22-
serde_helpers::{HUMAN_READABLE_NEWTYPE, UTF8_LOSSY_NEWTYPE},
22+
serde_helpers::HUMAN_READABLE_NEWTYPE,
2323
spec::{BinarySubtype, ElementType},
24+
utf8_lossy::UTF8_LOSSY_NEWTYPE,
2425
uuid::UUID_NEWTYPE_NAME,
2526
DateTime,
2627
DbPointer,

src/document.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -674,8 +674,8 @@ impl Document {
674674
}
675675

676676
/// Attempt to encode the [`Document`] into a byte [`Vec`].
677-
pub fn encode_to_vec(&self) -> Result<Vec<u8>> {
678-
Ok(crate::RawDocumentBuf::from_document(self)?.into_bytes())
677+
pub fn to_vec(&self) -> Result<Vec<u8>> {
678+
Ok(crate::RawDocumentBuf::try_from(self)?.into_bytes())
679679
}
680680

681681
/// Attempts to encode the [`Document`] into a byte stream.
@@ -690,12 +690,12 @@ impl Document {
690690
///
691691
/// let mut v: Vec<u8> = Vec::new();
692692
/// let doc = doc! { "x" : 1 };
693-
/// doc.encode_to_writer(&mut v)?;
693+
/// doc.to_writer(&mut v)?;
694694
/// # Ok(())
695695
/// # }
696696
/// ```
697-
pub fn encode_to_writer<W: Write>(&self, mut writer: W) -> crate::error::Result<()> {
698-
let buf = crate::RawDocumentBuf::from_document(self)?;
697+
pub fn to_writer<W: Write>(&self, mut writer: W) -> crate::error::Result<()> {
698+
let buf = crate::RawDocumentBuf::try_from(self)?;
699699
writer.write_all(buf.as_bytes())?;
700700
Ok(())
701701
}
@@ -714,22 +714,22 @@ impl Document {
714714
///
715715
/// let mut v: Vec<u8> = Vec::new();
716716
/// let doc = doc! { "x" : 1 };
717-
/// doc.encode_to_writer(&mut v)?;
717+
/// doc.to_writer(&mut v)?;
718718
///
719719
/// // read from mutable reference
720720
/// let mut reader = Cursor::new(v.clone());
721-
/// let doc1 = Document::decode_from_reader(&mut reader)?;
721+
/// let doc1 = Document::from_reader(&mut reader)?;
722722
///
723723
/// // read from owned value
724-
/// let doc2 = Document::decode_from_reader(Cursor::new(v))?;
724+
/// let doc2 = Document::from_reader(Cursor::new(v))?;
725725
///
726726
/// assert_eq!(doc, doc1);
727727
/// assert_eq!(doc, doc2);
728728
/// # Ok(())
729729
/// # }
730730
/// ```
731-
pub fn decode_from_reader<R: Read>(reader: R) -> crate::error::Result<Document> {
732-
let raw = crate::raw::RawDocumentBuf::decode_from_reader(reader)?;
731+
pub fn from_reader<R: Read>(reader: R) -> crate::error::Result<Document> {
732+
let raw = crate::raw::RawDocumentBuf::from_reader(reader)?;
733733
raw.try_into()
734734
}
735735
}

0 commit comments

Comments
 (0)