Skip to content

Commit 406fc80

Browse files
committed
RUST-882 Fix or improve lossy From unsigned integer impls for Bson (#281)
1 parent da8799c commit 406fc80

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/bson.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
//! BSON definition
2323
2424
use std::{
25+
convert::{TryFrom, TryInto},
2526
fmt::{self, Debug, Display},
2627
ops::{Deref, DerefMut},
2728
};
@@ -266,13 +267,22 @@ impl From<i64> for Bson {
266267

267268
impl From<u32> for Bson {
268269
fn from(a: u32) -> Bson {
269-
Bson::Int32(a as i32)
270+
if let Ok(i) = i32::try_from(a) {
271+
Bson::Int32(i)
272+
} else {
273+
Bson::Int64(a.into())
274+
}
270275
}
271276
}
272277

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

src/tests/modules/bson.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ fn from_impls() {
110110
assert_eq!(Bson::from(-48i32), Bson::Int32(-48));
111111
assert_eq!(Bson::from(-96i64), Bson::Int64(-96));
112112
assert_eq!(Bson::from(152u32), Bson::Int32(152));
113+
assert_eq!(Bson::from(i32::MAX as u32 + 1), Bson::Int64(i32::MAX as i64 + 1));
113114
assert_eq!(Bson::from(4096u64), Bson::Int64(4096));
114115

115116
let oid = ObjectId::new();

0 commit comments

Comments
 (0)