Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2020 Google Inc. All rights reserved. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 17 | import Foundation |
| 18 | |
| 19 | public struct ByteBuffer { |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 20 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 21 | /// Storage is a container that would hold the memory pointer to solve the issue of |
| 22 | /// deallocating the memory that was held by (memory: UnsafeMutableRawPointer) |
| 23 | @usableFromInline |
| 24 | final class Storage { |
| 25 | // This storage doesn't own the memory, therefore, we won't deallocate on deinit. |
| 26 | private let unowned: Bool |
| 27 | /// pointer to the start of the buffer object in memory |
| 28 | var memory: UnsafeMutableRawPointer |
| 29 | /// Capacity of UInt8 the buffer can hold |
| 30 | var capacity: Int |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 31 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 32 | init(count: Int, alignment: Int) { |
| 33 | memory = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: alignment) |
| 34 | capacity = count |
| 35 | unowned = false |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 36 | } |
| 37 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 38 | init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) { |
| 39 | self.memory = memory |
| 40 | self.capacity = capacity |
| 41 | self.unowned = unowned |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 42 | } |
| 43 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 44 | deinit { |
| 45 | if !unowned { |
| 46 | memory.deallocate() |
| 47 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 48 | } |
| 49 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 50 | func copy(from ptr: UnsafeRawPointer, count: Int) { |
| 51 | assert( |
| 52 | !unowned, |
| 53 | "copy should NOT be called on a buffer that is built by assumingMemoryBound") |
| 54 | memory.copyMemory(from: ptr, byteCount: count) |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 55 | } |
| 56 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 57 | func initialize(for size: Int) { |
| 58 | assert( |
| 59 | !unowned, |
| 60 | "initalize should NOT be called on a buffer that is built by assumingMemoryBound") |
| 61 | memset(memory, 0, size) |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 62 | } |
| 63 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 64 | /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer |
| 65 | /// - Parameter size: Size of the current object |
| 66 | @usableFromInline |
| 67 | internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) { |
| 68 | let currentWritingIndex = capacity &- writerSize |
| 69 | while capacity <= writerSize &+ size { |
| 70 | capacity = capacity << 1 |
| 71 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 72 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 73 | /// solution take from Apple-NIO |
| 74 | capacity = capacity.convertToPowerofTwo |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 75 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 76 | let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment) |
| 77 | memset(newData, 0, capacity &- writerSize) |
| 78 | memcpy( |
| 79 | newData.advanced(by: capacity &- writerSize), |
| 80 | memory.advanced(by: currentWritingIndex), |
| 81 | writerSize) |
| 82 | memory.deallocate() |
| 83 | memory = newData |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 84 | } |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 85 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 86 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 87 | @usableFromInline var _storage: Storage |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 88 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 89 | /// The size of the elements written to the buffer + their paddings |
| 90 | private var _writerSize: Int = 0 |
| 91 | /// Aliginment of the current memory being written to the buffer |
| 92 | internal var alignment = 1 |
| 93 | /// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer |
| 94 | internal var writerIndex: Int { _storage.capacity &- _writerSize } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 95 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 96 | /// Reader is the position of the current Writer Index (capacity - size) |
| 97 | public var reader: Int { writerIndex } |
| 98 | /// Current size of the buffer |
| 99 | public var size: UOffset { UOffset(_writerSize) } |
| 100 | /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason |
| 101 | public var memory: UnsafeMutableRawPointer { _storage.memory } |
| 102 | /// Current capacity for the buffer |
| 103 | public var capacity: Int { _storage.capacity } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 104 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 105 | /// Constructor that creates a Flatbuffer object from a UInt8 |
| 106 | /// - Parameter bytes: Array of UInt8 |
| 107 | public init(bytes: [UInt8]) { |
| 108 | var b = bytes |
| 109 | _storage = Storage(count: bytes.count, alignment: alignment) |
| 110 | _writerSize = _storage.capacity |
| 111 | b.withUnsafeMutableBytes { bufferPointer in |
| 112 | self._storage.copy(from: bufferPointer.baseAddress!, count: bytes.count) |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 113 | } |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 114 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 115 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 116 | /// Constructor that creates a Flatbuffer from the Swift Data type object |
| 117 | /// - Parameter data: Swift data Object |
| 118 | public init(data: Data) { |
| 119 | var b = data |
| 120 | _storage = Storage(count: data.count, alignment: alignment) |
| 121 | _writerSize = _storage.capacity |
| 122 | b.withUnsafeMutableBytes { bufferPointer in |
| 123 | self._storage.copy(from: bufferPointer.baseAddress!, count: data.count) |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 124 | } |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 125 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 126 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 127 | /// Constructor that creates a Flatbuffer instance with a size |
| 128 | /// - Parameter size: Length of the buffer |
| 129 | init(initialSize size: Int) { |
| 130 | let size = size.convertToPowerofTwo |
| 131 | _storage = Storage(count: size, alignment: alignment) |
| 132 | _storage.initialize(for: size) |
| 133 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 134 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 135 | #if swift(>=5.0) |
| 136 | /// Constructor that creates a Flatbuffer object from a ContiguousBytes |
| 137 | /// - Parameters: |
| 138 | /// - contiguousBytes: Binary stripe to use as the buffer |
| 139 | /// - count: amount of readable bytes |
| 140 | public init<Bytes: ContiguousBytes>( |
| 141 | contiguousBytes: Bytes, |
| 142 | count: Int) |
| 143 | { |
| 144 | _storage = Storage(count: count, alignment: alignment) |
| 145 | _writerSize = _storage.capacity |
| 146 | contiguousBytes.withUnsafeBytes { buf in |
| 147 | _storage.copy(from: buf.baseAddress!, count: buf.count) |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 148 | } |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 149 | } |
| 150 | #endif |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 151 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 152 | /// Constructor that creates a Flatbuffer from unsafe memory region without copying |
| 153 | /// - Parameter assumingMemoryBound: The unsafe memory region |
| 154 | /// - Parameter capacity: The size of the given memory region |
| 155 | public init(assumingMemoryBound memory: UnsafeMutableRawPointer, capacity: Int) { |
| 156 | _storage = Storage(memory: memory, capacity: capacity, unowned: true) |
| 157 | _writerSize = capacity |
| 158 | } |
| 159 | |
| 160 | /// Creates a copy of the buffer that's being built by calling sizedBuffer |
| 161 | /// - Parameters: |
| 162 | /// - memory: Current memory of the buffer |
| 163 | /// - count: count of bytes |
| 164 | internal init(memory: UnsafeMutableRawPointer, count: Int) { |
| 165 | _storage = Storage(count: count, alignment: alignment) |
| 166 | _storage.copy(from: memory, count: count) |
| 167 | _writerSize = _storage.capacity |
| 168 | } |
| 169 | |
| 170 | /// Creates a copy of the existing flatbuffer, by copying it to a different memory. |
| 171 | /// - Parameters: |
| 172 | /// - memory: Current memory of the buffer |
| 173 | /// - count: count of bytes |
| 174 | /// - removeBytes: Removes a number of bytes from the current size |
| 175 | internal init(memory: UnsafeMutableRawPointer, count: Int, removing removeBytes: Int) { |
| 176 | _storage = Storage(count: count, alignment: alignment) |
| 177 | _storage.copy(from: memory, count: count) |
| 178 | _writerSize = removeBytes |
| 179 | } |
| 180 | |
| 181 | /// Fills the buffer with padding by adding to the writersize |
| 182 | /// - Parameter padding: Amount of padding between two to be serialized objects |
| 183 | @usableFromInline |
| 184 | mutating func fill(padding: Int) { |
| 185 | assert(padding >= 0, "Fill should be larger than or equal to zero") |
| 186 | ensureSpace(size: padding) |
| 187 | _writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding) |
| 188 | } |
| 189 | |
| 190 | ///Adds an array of type Scalar to the buffer memory |
| 191 | /// - Parameter elements: An array of Scalars |
| 192 | @usableFromInline |
| 193 | mutating func push<T: Scalar>(elements: [T]) { |
| 194 | let size = elements.count &* MemoryLayout<T>.size |
| 195 | ensureSpace(size: size) |
| 196 | elements.reversed().forEach { s in |
| 197 | push(value: s, len: MemoryLayout.size(ofValue: s)) |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 198 | } |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 199 | } |
| 200 | |
| 201 | /// A custom type of structs that are padded according to the flatbuffer padding, |
| 202 | /// - Parameters: |
| 203 | /// - value: Pointer to the object in memory |
| 204 | /// - size: Size of Value being written to the buffer |
| 205 | @available( |
| 206 | *, |
| 207 | deprecated, |
| 208 | message: "0.9.0 will be removing the following method. Regenerate the code") |
| 209 | @usableFromInline |
| 210 | mutating func push(struct value: UnsafeMutableRawPointer, size: Int) { |
| 211 | ensureSpace(size: size) |
| 212 | memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size) |
| 213 | defer { value.deallocate() } |
| 214 | _writerSize = _writerSize &+ size |
| 215 | } |
| 216 | |
| 217 | /// Prepares the buffer to receive a struct of certian size. |
| 218 | /// The alignment of the memory is already handled since we already called preAlign |
| 219 | /// - Parameter size: size of the struct |
| 220 | @usableFromInline |
| 221 | mutating func prepareBufferToReceiveStruct(of size: Int) { |
| 222 | ensureSpace(size: size) |
| 223 | _writerSize = _writerSize &+ size |
| 224 | } |
| 225 | |
| 226 | /// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex` |
| 227 | /// and writes front to back into the buffer, respecting the padding & the alignment |
| 228 | /// - Parameters: |
| 229 | /// - value: value of type Scalar |
| 230 | /// - position: position relative to the `writerIndex` |
| 231 | /// - len: length of the value in terms of bytes |
| 232 | @usableFromInline |
| 233 | mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) { |
| 234 | var v = value |
| 235 | memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len) |
| 236 | } |
| 237 | |
| 238 | /// Adds an object of type Scalar into the buffer |
| 239 | /// - Parameters: |
| 240 | /// - value: Object that will be written to the buffer |
| 241 | /// - len: Offset to subtract from the WriterIndex |
| 242 | @usableFromInline |
| 243 | mutating func push<T: Scalar>(value: T, len: Int) { |
| 244 | ensureSpace(size: len) |
| 245 | var v = value |
| 246 | memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len) |
| 247 | _writerSize = _writerSize &+ len |
| 248 | } |
| 249 | |
| 250 | /// Adds a string to the buffer using swift.utf8 object |
| 251 | /// - Parameter str: String that will be added to the buffer |
| 252 | /// - Parameter len: length of the string |
| 253 | @usableFromInline |
| 254 | mutating func push(string str: String, len: Int) { |
| 255 | ensureSpace(size: len) |
| 256 | if str.utf8.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != nil { |
| 257 | } else { |
| 258 | let utf8View = str.utf8 |
| 259 | for c in utf8View.reversed() { |
| 260 | push(value: c, len: 1) |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// Writes a string to Bytebuffer using UTF8View |
| 266 | /// - Parameters: |
| 267 | /// - bytes: Pointer to the view |
| 268 | /// - len: Size of string |
| 269 | @usableFromInline |
| 270 | mutating internal func push( |
| 271 | bytes: UnsafeBufferPointer<String.UTF8View.Element>, |
| 272 | len: Int) -> Bool |
| 273 | { |
| 274 | memcpy( |
| 275 | _storage.memory.advanced(by: writerIndex &- len), |
| 276 | UnsafeRawPointer(bytes.baseAddress!), |
| 277 | len) |
| 278 | _writerSize = _writerSize &+ len |
| 279 | return true |
| 280 | } |
| 281 | |
| 282 | /// Write stores an object into the buffer directly or indirectly. |
| 283 | /// |
| 284 | /// Direct: ignores the capacity of buffer which would mean we are referring to the direct point in memory |
| 285 | /// indirect: takes into respect the current capacity of the buffer (capacity - index), writing to the buffer from the end |
| 286 | /// - Parameters: |
| 287 | /// - value: Value that needs to be written to the buffer |
| 288 | /// - index: index to write to |
| 289 | /// - direct: Should take into consideration the capacity of the buffer |
| 290 | func write<T>(value: T, index: Int, direct: Bool = false) { |
| 291 | var index = index |
| 292 | if !direct { |
| 293 | index = _storage.capacity &- index |
| 294 | } |
| 295 | assert(index < _storage.capacity, "Write index is out of writing bound") |
| 296 | assert(index >= 0, "Writer index should be above zero") |
| 297 | _storage.memory.storeBytes(of: value, toByteOffset: index, as: T.self) |
| 298 | } |
| 299 | |
| 300 | /// Makes sure that buffer has enouch space for each of the objects that will be written into it |
| 301 | /// - Parameter size: size of object |
| 302 | @discardableResult |
| 303 | @usableFromInline |
| 304 | mutating func ensureSpace(size: Int) -> Int { |
| 305 | if size &+ _writerSize > _storage.capacity { |
| 306 | _storage.reallocate(size, writerSize: _writerSize, alignment: alignment) |
| 307 | } |
| 308 | assert(size < FlatBufferMaxSize, "Buffer can't grow beyond 2 Gigabytes") |
| 309 | return size |
| 310 | } |
| 311 | |
| 312 | /// pops the written VTable if it's already written into the buffer |
| 313 | /// - Parameter size: size of the `VTable` |
| 314 | @usableFromInline |
| 315 | mutating internal func pop(_ size: Int) { |
| 316 | assert((_writerSize &- size) > 0, "New size should NOT be a negative number") |
| 317 | memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size) |
| 318 | _writerSize = size |
| 319 | } |
| 320 | |
| 321 | /// Clears the current size of the buffer |
| 322 | mutating public func clearSize() { |
| 323 | _writerSize = 0 |
| 324 | } |
| 325 | |
| 326 | /// Clears the current instance of the buffer, replacing it with new memory |
| 327 | mutating public func clear() { |
| 328 | _writerSize = 0 |
| 329 | alignment = 1 |
| 330 | _storage.initialize(for: _storage.capacity) |
| 331 | } |
| 332 | |
| 333 | /// Reads an object from the buffer |
| 334 | /// - Parameters: |
| 335 | /// - def: Type of the object |
| 336 | /// - position: the index of the object in the buffer |
| 337 | public func read<T>(def: T.Type, position: Int) -> T { |
| 338 | assert( |
| 339 | position + MemoryLayout<T>.size <= _storage.capacity, |
| 340 | "Reading out of bounds is illegal") |
| 341 | return _storage.memory.advanced(by: position).load(as: T.self) |
| 342 | } |
| 343 | |
| 344 | /// Reads a slice from the memory assuming a type of T |
| 345 | /// - Parameters: |
| 346 | /// - index: index of the object to be read from the buffer |
| 347 | /// - count: count of bytes in memory |
| 348 | public func readSlice<T>( |
| 349 | index: Int32, |
| 350 | count: Int32) -> [T] |
| 351 | { |
| 352 | let _index = Int(index) |
| 353 | let _count = Int(count) |
| 354 | assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal") |
| 355 | let start = _storage.memory.advanced(by: _index).assumingMemoryBound(to: T.self) |
| 356 | let array = UnsafeBufferPointer(start: start, count: _count) |
| 357 | return Array(array) |
| 358 | } |
| 359 | |
| 360 | /// Reads a string from the buffer and encodes it to a swift string |
| 361 | /// - Parameters: |
| 362 | /// - index: index of the string in the buffer |
| 363 | /// - count: length of the string |
| 364 | /// - type: Encoding of the string |
| 365 | public func readString( |
| 366 | at index: Int32, |
| 367 | count: Int32, |
| 368 | type: String.Encoding = .utf8) -> String? |
| 369 | { |
| 370 | let _index = Int(index) |
| 371 | let _count = Int(count) |
| 372 | assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal") |
| 373 | let start = _storage.memory.advanced(by: _index).assumingMemoryBound(to: UInt8.self) |
| 374 | let bufprt = UnsafeBufferPointer(start: start, count: _count) |
| 375 | return String(bytes: Array(bufprt), encoding: type) |
| 376 | } |
| 377 | |
| 378 | /// Creates a new Flatbuffer object that's duplicated from the current one |
| 379 | /// - Parameter removeBytes: the amount of bytes to remove from the current Size |
| 380 | public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer { |
| 381 | assert(removeBytes > 0, "Can NOT remove negative bytes") |
| 382 | assert(removeBytes < _storage.capacity, "Can NOT remove more bytes than the ones allocated") |
| 383 | return ByteBuffer( |
| 384 | memory: _storage.memory, |
| 385 | count: _storage.capacity, |
| 386 | removing: _writerSize &- removeBytes) |
| 387 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 388 | } |
| 389 | |
| 390 | extension ByteBuffer: CustomDebugStringConvertible { |
| 391 | |
Austin Schuh | 58b9b47 | 2020-11-25 19:12:44 -0800 | [diff] [blame^] | 392 | public var debugDescription: String { |
| 393 | """ |
| 394 | buffer located at: \(_storage.memory), with capacity of \(_storage.capacity) |
| 395 | { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) } |
| 396 | """ |
| 397 | } |
Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame] | 398 | } |