diff --git a/src/bson.rs b/src/bson.rs index 8b16a6f9..1c28a050 100644 --- a/src/bson.rs +++ b/src/bson.rs @@ -22,6 +22,7 @@ //! BSON definition use std::{ + convert::{TryFrom, TryInto}, fmt::{self, Debug, Display}, ops::{Deref, DerefMut}, }; @@ -266,13 +267,22 @@ impl From for Bson { impl From 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 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)) } } diff --git a/src/de/mod.rs b/src/de/mod.rs index 401dc432..1e87838e 100644 --- a/src/de/mod.rs +++ b/src/de/mod.rs @@ -164,9 +164,7 @@ fn read_f128(reader: &mut R) -> Result { #[cfg(feature = "decimal128")] #[inline] fn read_f128(reader: &mut R) -> Result { - use std::mem; - - let mut local_buf: [u8; 16] = unsafe { mem::MaybeUninit::uninit().assume_init() }; + let mut local_buf = [0u8; 16]; reader.read_exact(&mut local_buf)?; let val = unsafe { Decimal128::from_raw_bytes_le(local_buf) }; Ok(val) diff --git a/src/tests/modules/bson.rs b/src/tests/modules/bson.rs index c0aaf1a1..ea959aa4 100644 --- a/src/tests/modules/bson.rs +++ b/src/tests/modules/bson.rs @@ -110,6 +110,10 @@ 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(); diff --git a/src/tests/modules/ordered.rs b/src/tests/modules/ordered.rs index 0a0d211e..2f75efa1 100644 --- a/src/tests/modules/ordered.rs +++ b/src/tests/modules/ordered.rs @@ -105,8 +105,8 @@ fn test_getters() { doc.insert("null".to_string(), Bson::Null); assert_eq!(Some(&Bson::Null), doc.get("null")); - assert_eq!(true, doc.is_null("null")); - assert_eq!(false, doc.is_null("array")); + assert!(doc.is_null("null")); + assert!(!doc.is_null("array")); assert_eq!(Some(&Bson::Int32(1)), doc.get("i32")); assert_eq!(Ok(1i32), doc.get_i32("i32")); diff --git a/src/tests/modules/ser.rs b/src/tests/modules/ser.rs index 63983b6e..37f2a5dd 100644 --- a/src/tests/modules/ser.rs +++ b/src/tests/modules/ser.rs @@ -50,7 +50,7 @@ fn boolean() { let _guard = LOCK.run_concurrently(); let obj = Bson::Boolean(true); let b: bool = from_bson(obj.clone()).unwrap(); - assert_eq!(b, true); + assert!(b); let deser: Bson = to_bson(&b).unwrap(); assert_eq!(deser, obj);