Skip to content

Commit a3fe6c8

Browse files
authored
RUST-1881 Check integer conversions (#1045)
1 parent 05361ce commit a3fe6c8

File tree

18 files changed

+650
-101
lines changed

18 files changed

+650
-101
lines changed

src/bson_util.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@ use std::{
55

66
use crate::{
77
bson::{Bson, Document, RawArrayBuf, RawBson, RawBsonRef, RawDocumentBuf},
8+
checked::Checked,
89
error::{ErrorKind, Result},
910
runtime::SyncLittleEndianRead,
1011
};
1112

1213
/// Coerce numeric types into an `i64` if it would be lossless to do so. If this Bson is not numeric
1314
/// or the conversion would be lossy (e.g. 1.5 -> 1), this returns `None`.
15+
#[allow(clippy::cast_possible_truncation)]
1416
pub(crate) fn get_int(val: &Bson) -> Option<i64> {
1517
match *val {
1618
Bson::Int32(i) => Some(i64::from(i)),
@@ -33,6 +35,7 @@ pub(crate) fn get_int_raw(val: RawBsonRef<'_>) -> Option<i64> {
3335

3436
/// Coerce numeric types into an `u64` if it would be lossless to do so. If this Bson is not numeric
3537
/// or the conversion would be lossy (e.g. 1.5 -> 1), this returns `None`.
38+
#[allow(clippy::cast_possible_truncation)]
3639
pub(crate) fn get_u64(val: &Bson) -> Option<u64> {
3740
match *val {
3841
Bson::Int32(i) => u64::try_from(i).ok(),
@@ -89,18 +92,18 @@ pub(crate) fn update_document_check(update: &Document) -> Result<()> {
8992
}
9093

9194
/// The size in bytes of the provided document's entry in a BSON array at the given index.
92-
pub(crate) fn array_entry_size_bytes(index: usize, doc_len: usize) -> u64 {
95+
pub(crate) fn array_entry_size_bytes(index: usize, doc_len: usize) -> Result<usize> {
9396
// * type (1 byte)
9497
// * number of decimal digits in key
9598
// * null terminator for the key (1 byte)
9699
// * size of value
97100

98-
1 + num_decimal_digits(index) + 1 + doc_len as u64
101+
(Checked::new(1) + num_decimal_digits(index) + 1 + doc_len).get()
99102
}
100103

101104
/// The number of digits in `n` in base 10.
102105
/// Useful for calculating the size of an array entry in BSON.
103-
fn num_decimal_digits(mut n: usize) -> u64 {
106+
fn num_decimal_digits(mut n: usize) -> usize {
104107
let mut digits = 0;
105108

106109
loop {

0 commit comments

Comments
 (0)