Skip to content

Commit fbae1a4

Browse files
bonzinijiangliu
authored andcommitted
volatile_memory: replace cast crate with try_from
Fixes #30. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
1 parent c29d2c7 commit fbae1a4

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ backend-mmap = []
1313

1414
[dependencies]
1515
libc = ">=0.2.39"
16-
cast = ">=0"
1716

1817
[target.'cfg(windows)'.dependencies.winapi]
1918
version = ">=0.3"

src/volatile_memory.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
//! not reordered or elided the access.
2525
2626
use std::cmp::min;
27+
use std::convert::TryFrom;
2728
use std::error;
2829
use std::fmt;
2930
use std::io::{self, Read, Write};
@@ -37,9 +38,6 @@ use std::usize;
3738

3839
use crate::{ByteValued, Bytes};
3940

40-
// TODO: replace with TryFrom once we can assume 1.34.0.
41-
extern crate cast;
42-
4341
/// `VolatileMemory` related errors.
4442
#[allow(missing_docs)]
4543
#[derive(Debug)]
@@ -181,7 +179,7 @@ pub trait VolatileMemory {
181179
/// `offset`.
182180
fn get_array_ref<T: ByteValued>(&self, offset: usize, n: usize) -> Result<VolatileArrayRef<T>> {
183181
// Use isize to avoid problems with ptr::offset and ptr::add down the line.
184-
let nbytes = cast::isize(n)
182+
let nbytes = isize::try_from(n)
185183
.ok()
186184
.and_then(|n| n.checked_mul(size_of::<T>() as isize))
187185
.ok_or(Error::TooBig {
@@ -1536,4 +1534,18 @@ mod tests {
15361534
} //.load()
15371535
;
15381536
}
1537+
1538+
#[test]
1539+
fn ref_array_overflow() {
1540+
let mut a = [0, 0, 2, 3, 10];
1541+
let a_ref = &mut a[..];
1542+
let res = a_ref.get_array_ref::<u32>(4, usize::MAX).unwrap_err();
1543+
assert_matches!(
1544+
res,
1545+
Error::TooBig {
1546+
nelements: usize::MAX,
1547+
size: 4,
1548+
}
1549+
);
1550+
}
15391551
}

0 commit comments

Comments
 (0)