Skip to content

Conversation

@qryxip
Copy link

@qryxip qryxip commented Jun 12, 2021

Semantically there are no equivalent Rust code to char *s = "…";.

On Rust, we cannot even attempt to modify string literals.

let mut s = b"byte string literal";

// error[E0594]: cannot assign to `s[_]` which is behind a `&` reference
//s[0] = b'B';

let s = &s[1..]; // this is OK
// equivalents to `char s[] = {…};`
let s = &mut { *b"byte string literal" };
s[0] = b'B'; // `s` is on the stack. so this is not UB
// equivalents to the wrong semantics of `char *s = "…";`
unsafe {
    // Safety:
    //
    // There is always at most 1 pointer to `S`. I promise.
    static mut S: [u8; 19] = *b"byte string literal";
    let s = &mut S;
    s[0] = b'B'; // also this is not UB as long as we obey the "Shared Xor Mutable" rule
}

@qryxip
Copy link
Author

qryxip commented Jun 13, 2021

I forgot this.

unsafe {
    // Yes, I know this is instant UB!
    #[allow(mutable_transmutes, clippy::transmute_ptr_to_ptr)]
    let s = std::mem::transmute::<_, &mut [u8]>(&b"text"[..]);

    s[0] = b'T';
}

Maybe should I change to "Enforceable by default"? But char *s = "…"; itself is not UB unlike std::mem::transmute::<_, &mut _> on Rust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant