Swift: how to disable integer overflow / overflow traps for a function

I am importing old C code into a quick project and porting it to clean fast code.

Some of them do "encryption" in which he does something like

let a = UInt8(x) // e.g. 30
let b = a - 237

In C, it just overflows and wraps around, which is great for this particular function.

In swift, this triggers fatalError and terminates my program with EXC_BAD_INSTRUCTION, because swift is by default intended to capture the integer over / underflow value.

I know that I can turn off this check at the whole project level by compiling it with -Ofast, but I would really like to just turn off the overflow check for this line of code (or perhaps only a specific function in itself).

Note. I specifically want to keep the behavior of the C function, and not just push things to Int32 or Int64

This particular term seems very difficult for Google.


Update: Answer Overflow Operators That

  • &- for subtraction
  • &+ for adding
  • &* for multiplication

I could not find them in my previous search. Unfortunately,

+4
source share
2 answers

You can use the class method addWithOverflow or subtractWithOverflow for types Int, UInt8, etc.

eg. let b = UInt8.subtractWithOverflow(a, 237)

+4
source

(, & +, & * ..), ( ), , , , :/p >

   let int1 : Int8 = Int8.max   //127
   let int2: Int8 = 50

 //this method provides a boolean flag 
  let (sum1,didOverflow ):(Int8,Bool) = int1.addingReportingOverflow(int2)

  print("sum is \(sum1) and isOverflowing = \(didOverflow)")
//sum is -79 and isOverflowing is true

  let sum = int1 &+ int2 //wont crash for overflows
  let unsafeSum = int1.unsafeAdding(int2) //crashes whenever overflow
0

Source: https://habr.com/ru/post/1629296/


All Articles