Could we have `fetch_not` for `AtomicBool`s?

Recently I've discovered that there isn't any method in std that negates an AtomicBool. Given that users can just implement a polyfill themselves like this:

use std::sync::atomic::{AtomicBool, Ordering};

pub fn fetch_not(b: &AtomicBool, order: Ordering) -> bool {
    b.fetch_xor(true, order)
}

I would love to see an official helper method, implemented just like this or better with a new intrinsic.

Note that LLVM doesn't have an atomic not instruction (see https://llvm.org/docs/LangRef.html#atomicrmw-instruction for the things that exist) and thus there'd be no value in a new intrinsic -- it'd have to emit the same things as the fetch_xor does.

(In fact, LLVM only has one unary instruction, fneg, so it doesn't have a logical-not nor a bitwise-not. It just has xor, with 1 or -1 depending which one you want.)

So if you want it, send a PR and see what libs-api has to say about it!


Oh, and for completeness, Cranelift's AtomicRmwOp in cranelift_codegen::ir - Rust doesn't include not either.

1 Like

That's unfortunate; I will open a PR with the implementation with fetch_xor. Thanks for the input!

It doesn't need one. It can trivially pattern-match "xor with -1" during codegen to emit a NOT instruction when it seems that pattern. Demo: https://rust.godbolt.org/z/q88vTWf64

But, of course, the x86 NOT instruction isn't useful for not on booleans anyway, since Rust stores them as 0/1, not as 0/-1.

4 Likes