1 import Foundation 2 3 extension Int { 4 5 /// Moves the current int into the nearest power of two 6 /// 7 /// This is used since the UnsafeMutableRawPointer will face issues when writing/reading 8 /// if the buffer alignment exceeds that actual size of the buffer 9 var convertToPowerofTwo: Int { 10 guard self > 0 else { return 1 } 11 var n = UOffset(self) 12 13 #if arch(arm) || arch(i386) 14 let max = UInt32(Int.max) 15 #else 16 let max = UInt32.max 17 #endif 18 19 n -= 1 20 n |= n >> 1 21 n |= n >> 2 22 n |= n >> 4 23 n |= n >> 8 24 n |= n >> 16 25 if n != max { 26 n += 1 27 } 28 29 return Int(n) 30 } 31 } 32