vlang / rfcs

RFCs for changes to V
MIT License
43 stars 16 forks source link

Wrapping Arithmetic Operators for Integers: +~, -~, *~ or /~ #10

Open igotfr opened 3 years ago

igotfr commented 3 years ago

Wrapping Operations for Integers These operations have guaranteed wraparound semantics. Failing when the result cause overflow

Example:

u8(129) +~ u8(129) // error
igotfr commented 3 years ago

@Cons-Cat says: Imho, the use case for guaranteed wrap-around semantics is niche and it could be simpler to handle this with special structs in the standard library named something like math.WrapI32, math.WrapU32, etc. (or possibly a generic struct, although I'm not sure how to make that work for this case off the top of my head). The operator overloading rules of V might make this cumbersome, since you wouldn't be able to compile val := math.WrapI32(1) + 1, though, because you can only + a non-primitive type (like a struct) with a value of the same type. Nevertheless, I feel like that approach is most in line with the current direction of the language, personally.

igotfr commented 2 years ago

Rust has the checked trait: https://docs.rs/num-traits/0.2.6/num_traits/ops/checked/index.html

igotfr commented 2 years ago

related: https://github.com/vlang/v/discussions/11921