1 个不稳定版本
| 0.1.0 | 2020年1月18日 |
|---|
#3 在 #soundness
7KB
55 行
通过与安全代码的等价性检查来减少不安全代码并检测鲁棒性错误
关于此想法的讨论,请参阅 Rust 内部论坛上的 RFC rfc-use-cfg-reduce-unsafe-to-signal-preference-of-safe-code-over-performance 和 Rust 安全代码工作组 rust-secure-code-wg。
为了表明对安全的优先级高于性能:将 --cfg reduce_unsafe 添加到您的 RUSTFLAGS。
reduce_unsafe::unchecked! 运行不安全代码,除非存在 --cfg reduce_unsafe 标志。
reduce_unsafe::checked! 使用 debug_assertions 来决定是否运行 reduce_unsafe::unchecked! 或运行两个分支并在它们不同时崩溃。
如果您有您认为鲁棒的不安全代码,并且可以(较慢地)使用安全代码实现,请考虑使用 reduce_unsafe::checked! 或 reduce_unsafe::unchecked! 宏或 #[cfg(reduce_unsafe)] 属性。
let my_str = unsafe {
str::from_utf8_unchecked(bytes)
};
变为
let my_str = reduce_unsafe::checked!(
unsafe { str::from_utf8_unchecked(bytes) },
str::from_utf8(bytes).expect("BUG: unsound unsafe code detected")
);
如果返回类型没有实现 PartialEq 或存在可见的副作用
let my_str = reduce_unsafe::unchecked!(
unsafe { str::from_utf8_unchecked(bytes) },
str::from_utf8(bytes).expect("BUG: unsound unsafe code detected")
);