1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-26 10:41:01 +02:00

Add safety comments and use consistent format for existing ones. (#1981)

We should have safety comments on all `unsafe` blocks, to set a good
example.
This commit is contained in:
Andrew Walbran
2024-04-12 18:19:19 +01:00
committed by GitHub
parent 8433ad9a3d
commit b808887006
18 changed files with 65 additions and 53 deletions

View File

@ -13,11 +13,11 @@ fn main() {
let r1 = &mut s as *mut String;
let r2 = r1 as *const String;
// Safe because r1 and r2 were obtained from references and so are
// guaranteed to be non-null and properly aligned, the objects underlying
// the references from which they were obtained are live throughout the
// whole unsafe block, and they are not accessed either through the
// references or concurrently through any other pointers.
// SAFETY: r1 and r2 were obtained from references and so are guaranteed to
// be non-null and properly aligned, the objects underlying the references
// from which they were obtained are live throughout the whole unsafe
// block, and they are not accessed either through the references or
// concurrently through any other pointers.
unsafe {
println!("r1 is: {}", *r1);
*r1 = String::from("uhoh");

View File

@ -21,6 +21,7 @@ static variables:
static mut COUNTER: u32 = 0;
fn add_to_counter(inc: u32) {
// SAFETY: There are no other threads which could be accessing `COUNTER`.
unsafe {
COUNTER += inc;
}
@ -29,6 +30,7 @@ fn add_to_counter(inc: u32) {
fn main() {
add_to_counter(42);
// SAFETY: There are no other threads which could be accessing `COUNTER`.
unsafe {
println!("COUNTER: {COUNTER}");
}

View File

@ -17,8 +17,8 @@ extern "C" {
fn main() {
let emojis = "🗻∈🌏";
// Safe because the indices are in the correct order, within the bounds of
// the string slice, and lie on UTF-8 sequence boundaries.
// SAFETY: The indices are in the correct order, within the bounds of the
// string slice, and lie on UTF-8 sequence boundaries.
unsafe {
println!("emoji: {}", emojis.get_unchecked(0..4));
println!("emoji: {}", emojis.get_unchecked(4..7));
@ -27,8 +27,9 @@ fn main() {
println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..7) }));
// SAFETY: `abs` doesn't deal with pointers and doesn't have any safety
// requirements.
unsafe {
// Undefined behavior if abs misbehaves.
println!("Absolute value of -3 according to C: {}", abs(-3));
}
@ -64,7 +65,7 @@ fn main() {
let mut a = 42;
let mut b = 66;
// Safe because ...
// SAFETY: ...
unsafe {
swap(&mut a, &mut b);
}

View File

@ -28,7 +28,7 @@ pub unsafe trait AsBytes {
}
}
// Safe because u32 has a defined representation and no padding.
// SAFETY: `u32` has a defined representation and no padding.
unsafe impl AsBytes for u32 {}
```