官术网_书友最值得收藏!

  • Rust Programming Cookbook
  • Claus Matzinger
  • 301字
  • 2021-06-24 12:27:50

How to do it...

In just a few steps, we are unsafe:

  1. Create a new library project using cargo new unsafe-ways --lib. Open the project using Visual Studio Code or another editor. 
  2. Open src/libr.rs to add the following function before the test module:
#![allow(dead_code)]
use std::slice;

fn split_into_equal_parts<T>(slice: &mut [T], parts: usize) -> Vec<&mut [T]> {
let len = slice.len();
assert!(parts <= len);
let step = len / parts;
unsafe {
let ptr = slice.as_mut_ptr();

(0..step + 1)
.map(|i| {
let offset = (i * step) as isize;
let a = ptr.offset(offset);
slice::from_raw_parts_mut(a, step)
})
.collect()
}
}
  1. With that ready, we now have to add some tests inside mod tests {}:

#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_split_into_equal_parts() {
let mut v = vec![1, 2, 3, 4, 5, 6];
assert_eq!(
split_into_equal_parts(&mut v, 3),
&[&[1, 2], &[3, 4], &[5, 6]]
);
}
}
  1. Recalling the unsafe superpowers, we could try and change the way we are reading memory. Let's add this test to see how it works:
#[test]
fn test_str_to_bytes_horribly_unsafe() {
let bytes = unsafe { std::mem::transmute::<&str, &[u8]>("Going
off the menu") };
assert_eq!(
bytes,
&[
71, 111, 105, 110, 103, 32, 111, 102, 102, 32, 116,
104, 101, 32, 109, 101, 110, 117
]
);
}

  1. The last step is to see the positive test results after running cargo test:
$ cargo test
Compiling unsafe-ways v0.1.0 (Rust-Cookbook/Chapter02/unsafe-ways)
Finished dev [unoptimized + debuginfo] target(s) in 0.41s
Running target/debug/deps/unsafe_ways-e7a1d3ffcc456d53

running 2 tests
test tests::test_str_to_bytes_horribly_unsafe ... ok
test tests::test_split_into_equal_parts ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Doc-tests unsafe-ways

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Safety is an important concept in Rust, so let's find out what we trade off by using unsafe.

主站蜘蛛池模板: 湟中县| 德昌县| 岚皋县| 海南省| 乐至县| 拉萨市| 兖州市| 平陆县| 翁源县| 乐东| 浑源县| 阳朔县| 灵宝市| 桃源县| 雷波县| 衡水市| 浏阳市| 南郑县| 丹阳市| 抚顺市| 财经| 鄂温| 嵊州市| 甘南县| 裕民县| 永川市| 元氏县| 华坪县| 上林县| 赤峰市| 宜川县| 工布江达县| 桑日县| 桂阳县| 德兴市| 临汾市| 三门峡市| 梅州市| 丰镇市| 彝良县| 永宁县|