aboutsummaryrefslogtreecommitdiff
path: root/swift/Sources/FlatBuffers/Int+extension.swift
diff options
context:
space:
mode:
Diffstat (limited to 'swift/Sources/FlatBuffers/Int+extension.swift')
-rw-r--r--swift/Sources/FlatBuffers/Int+extension.swift31
1 files changed, 31 insertions, 0 deletions
diff --git a/swift/Sources/FlatBuffers/Int+extension.swift b/swift/Sources/FlatBuffers/Int+extension.swift
new file mode 100644
index 00000000..e52bdab6
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Int+extension.swift
@@ -0,0 +1,31 @@
+import Foundation
+
+extension Int {
+
+ /// Moves the current int into the nearest power of two
+ ///
+ /// This is used since the UnsafeMutableRawPointer will face issues when writing/reading
+ /// if the buffer alignment exceeds that actual size of the buffer
+ var convertToPowerofTwo: Int {
+ guard self > 0 else { return 1 }
+ var n = UOffset(self)
+
+ #if arch(arm) || arch(i386)
+ let max = UInt32(Int.max)
+ #else
+ let max = UInt32.max
+ #endif
+
+ n -= 1
+ n |= n >> 1
+ n |= n >> 2
+ n |= n >> 4
+ n |= n >> 8
+ n |= n >> 16
+ if n != max {
+ n += 1
+ }
+
+ return Int(n)
+ }
+}