Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is any purpose served by a Rust function consisting solely of a block of unsafe code?

Tags:

rust

The code is copied from Listing 19-10 of The Rust Programming Language. It's meant to illustrate the use of mutable static variables, but that's not my concern here. Even though this may be fairly labelled as a "toy example", in a book introducing Rust, it raises what I think are serious issues.

All of the code of add_to_count is in an unsafe block. What good does this do, as opposed to making the function itself unsafe? As is, the signature of the function gives no clue that it is - in essence if not in Rust parlance - unsafe. I wonder why the compiler even allows this. The "benefit" is that, as can be seen below, the function can be called outside of an unsafe block. Why would an introductory text on Rust show how to circumvent a safe programming practice?

static mut COUNTER: u32 = 0;

fn add_to_count(inc: u32) {
    unsafe {
        COUNTER += inc;
    }
}

fn main() {
    add_to_count(3);

    unsafe {
        println!("COUNTER: {}", COUNTER);
    }
}
like image 882
grjash Avatar asked Mar 03 '23 06:03

grjash


1 Answers

If a function is marked as unsafe it means that the caller is responsible for upholding some number of conditions, otherwise undefined behavior may be introduced.

If a function is not marked as unsafe but contains unsafe code, then it means that the function is guaranteeing that no choice of parameters will cause unsafe behavior. In practice this often means the function will check some conditions and panic if the conditions aren't met.

By not marking the function as unsafe in your example, the author is asserting that nothing can go wrong by mutating a static mut u32 by some caller-defined amount.

like image 71
turbulencetoo Avatar answered Mar 05 '23 19:03

turbulencetoo