Skip to content

Commit

Permalink
RUST-882 Fix or improve lossy From unsigned integer impls for Bson (#281
Browse files Browse the repository at this point in the history
)
  • Loading branch information
patrickfreed committed Jul 23, 2021
1 parent da8799c commit 406fc80
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/bson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
//! BSON definition

use std::{
convert::{TryFrom, TryInto},
fmt::{self, Debug, Display},
ops::{Deref, DerefMut},
};
Expand Down Expand Up @@ -266,13 +267,22 @@ impl From<i64> for Bson {

impl From<u32> for Bson {
fn from(a: u32) -> Bson {
Bson::Int32(a as i32)
if let Ok(i) = i32::try_from(a) {
Bson::Int32(i)
} else {
Bson::Int64(a.into())
}
}
}

impl From<u64> for Bson {
/// This conversion is lossy if the provided `u64` is greater than `i64::MAX`, which it will be
/// converted to. Using this `From` implementation is highly discouraged and it will be
/// removed in the next major version.
///
/// Note: due to https://github.com/rust-lang/rust/issues/39935 we cannot deprecate this implementation.
fn from(a: u64) -> Bson {
Bson::Int64(a as i64)
Bson::Int64(a.try_into().unwrap_or(i64::MAX))
}
}

Expand Down
1 change: 1 addition & 0 deletions src/tests/modules/bson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ fn from_impls() {
assert_eq!(Bson::from(-48i32), Bson::Int32(-48));
assert_eq!(Bson::from(-96i64), Bson::Int64(-96));
assert_eq!(Bson::from(152u32), Bson::Int32(152));
assert_eq!(Bson::from(i32::MAX as u32 + 1), Bson::Int64(i32::MAX as i64 + 1));
assert_eq!(Bson::from(4096u64), Bson::Int64(4096));

let oid = ObjectId::new();
Expand Down

0 comments on commit 406fc80

Please sign in to comment.