dfinity / motoko

Simple high-level language for writing Internet Computer canisters
Apache License 2.0
517 stars 97 forks source link

Implement bitops for Nat and Int #2799

Open crusso opened 3 years ago

crusso commented 3 years ago

A user has requested an infinite precision bitwise negation operator on Nat and Int.

https://forum.dfinity.org/t/how-motoko-uses-the-bitwise-negation-operator/7428/8

Should be easy to support, acc to @nomeata, pointing at:

https://github.com/libtom/libtommath/blob/develop/mp_complement.c

crusso commented 3 years ago

(don't forget to check the doc!)

crusso commented 3 years ago

@rossberg any reason not to?

nomeata commented 3 years ago

I think only Int.

Surely not ~ without all the other bitwise operations (category B in https://sdk.dfinity.org/docs/language-guide/language-manual.html#syntax-ops), right? (Although right rotation doesn’t make sense for Int)

rossberg commented 3 years ago

Agreed with @nomeata: only makes sense to do this if we do all the bitops – I changed the issue title accordingly. Also, FWIW, there is no ~ op in Motoko, it's called unary ^. ;)

So I'd expect:

^ : Int -> Int
&, |, >>, << : (Nat, Nat) -> Nat /\ (Int, Int) -> Int
^ : (Int, Int) -> Int

^= : (var Int, Int) -> ()
&=, |=, >>=, <<= : (var Nat, Nat) -> () /\ (var Int, Int) -> ()
^= : (var Int, Int) -> ()

The only ones that make sense for neither Nat nor Int are <<> and <>> (strictly speaking, you could define <<>, but it seems pretty pointless).

So, yes, all doable, but a non-trivial amount of work, and given everything else, not high priority.

ggreif commented 4 months ago

At least we have

shiftLeft : (Nat, Nat32) -> Nat;
shiftRight : (Nat, Nat32) -> Nat;

in the primitives now.