18

I'm importing some old C code into a swift project, and porting it across to pure swift code.

Some of it does "encryption" wherein it does something like

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

In C this just underflows and wraps around, which is fine for this particular function.

In swift this triggers a fatalError and terminates my program with EXC_BAD_INSTRUCTION because swift by default is designed to catch integer over/underflow.

I'm aware I can turn this checking off at the entire project level by compiling with -Ofast, but I'd really like to just turn off the overflow checking for this one line of code (or perhaps just the specific function itself).

Note: I specifically want to preserve the behaviour of the C function, not just promote things up to Int32 or Int64

This particular term seems really hard to google for.


Update: The answer is the Overflow operators, which are

  • &- for subtraction
  • &+ for addition
  • &* for multiply

I couldn't find them in my previous searching. Oops

Orion Edwards
  • 121,657
  • 64
  • 239
  • 328

2 Answers2

7

You can use addWithOverflow or subtractWithOverflow class method of Int, UInt8 etc types

E.g. let b = UInt8.subtractWithOverflow(a, 237)

Pradeep K
  • 3,671
  • 1
  • 11
  • 15
6

Apart from overflow operators (such as &+ , &* etc) you can make use of reporting overflow methods (available for integers) to know whether the arithmetic operation resulted in an overflow or not such as this example :

   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
akr ios
  • 611
  • 1
  • 7
  • 9