A “backwards” introduction to Rust, starting with C-like unsafe code

I think you contradicted yourself: you disagree that it's less readable, but you agree it's more work to investigate what's going on?

The argument that I'm making is that we abstracted away a line of code and turned it into a page of code. This is not the right situation to be involving "API design", since nothing needs to be interfacing with anything else. You can just write the line of code in place, and then you have no API, you just have a line of code.


I also disagree with the assertion that the Rust code is "explicit". The author lists five constraints that the unsafe code must satisfy in order to work. Most of those constraints are still invisible gotchas of some kind, even in the safe version. For example, without studying the code I can't easily see what happens if ROUNDED_INTERACTIONS_COUNT is odd (constraint 2). The code won't work if it's odd, I'm not sure what will happen, but I wouldn't call it explicit. I don't know what happens if two adjacent f64s could somehow map to an invalid __m128d (constraint 4). I assume it's ok, Rust certainly isn't going to check for me. I don't have any visible indication that position_Deltas[m].0 is aligned like a __m128d (constraint 1), you have to know the Rust union rules to be certain. The author put a #[repr(C)] there, but then says that it's a red herring and the constraint will be satisfied anyway. Is that what we are calling explicit?

In fact most of the Rust safe code is just gumph.

impl Interactions {
    /// Returns a reference to the storage as `f64`s.
    pub fn as_scalars(&mut self) -> &mut [f64; ROUNDED_INTERACTIONS_COUNT] {
        // Safety: the in-memory representation of `f64` and `__m128d` is
        // compatible, so accesses to the union members is safe in any
        // order.
        unsafe {
            &mut self.scalars
        }
    }

    /// Returns a reference to the storage as `__m128d`s.
    pub fn as_vectors(&mut self)
        -> &mut [__m128d; ROUNDED_INTERACTIONS_COUNT/2]
    {
        // Safety: the in-memory representation of `f64` and `__m128d` is
        // compatible, so accesses to the union members is safe in any
        // order.
        unsafe {
            &mut self.vectors
        }
    }
}

i feel tired just reading it.

/r/programming Thread Parent Link - cliffle.com