rfcs icon indicating copy to clipboard operation
rfcs copied to clipboard

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

Open igotfr opened this issue 4 years ago • 3 comments

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

  • +~ (wraparound addition)
  • -~ (wraparound subtraction)
  • *~ (wraparound negation)
  • /~ (wraparound multiplication)

Example:

u8(129) +~ u8(129) // error

igotfr avatar Aug 30 '21 17:08 igotfr

@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 avatar Oct 13 '21 17:10 igotfr

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

igotfr avatar Dec 10 '21 11:12 igotfr

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

igotfr avatar Mar 02 '22 08:03 igotfr