blob: a07f66ae39e66396563dfb89b7237d47eb7f9653 [file] [log] [blame]
Austin Schuh58b9b472020-11-25 19:12:44 -08001/*
James Kuszmaul8e62b022022-03-22 09:33:25 -07002 * Copyright 2021 Google Inc. All rights reserved.
Austin Schuh58b9b472020-11-25 19:12:44 -08003 *
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 Schuh272c6132020-11-14 16:37:52 -080017import Foundation
18
James Kuszmaul8e62b022022-03-22 09:33:25 -070019/// `ByteBuffer` is the interface that stores the data for a `Flatbuffers` object
20/// it allows users to write and read data directly from memory thus the use of its
21/// functions should be used
22@frozen
Austin Schuh272c6132020-11-14 16:37:52 -080023public struct ByteBuffer {
Austin Schuh272c6132020-11-14 16:37:52 -080024
Austin Schuh58b9b472020-11-25 19:12:44 -080025 /// Storage is a container that would hold the memory pointer to solve the issue of
26 /// deallocating the memory that was held by (memory: UnsafeMutableRawPointer)
27 @usableFromInline
28 final class Storage {
29 // This storage doesn't own the memory, therefore, we won't deallocate on deinit.
30 private let unowned: Bool
31 /// pointer to the start of the buffer object in memory
32 var memory: UnsafeMutableRawPointer
33 /// Capacity of UInt8 the buffer can hold
34 var capacity: Int
Austin Schuh272c6132020-11-14 16:37:52 -080035
James Kuszmaul8e62b022022-03-22 09:33:25 -070036 @usableFromInline
Austin Schuh58b9b472020-11-25 19:12:44 -080037 init(count: Int, alignment: Int) {
James Kuszmaul8e62b022022-03-22 09:33:25 -070038 memory = UnsafeMutableRawPointer.allocate(
39 byteCount: count,
40 alignment: alignment)
Austin Schuh58b9b472020-11-25 19:12:44 -080041 capacity = count
42 unowned = false
Austin Schuh272c6132020-11-14 16:37:52 -080043 }
44
James Kuszmaul8e62b022022-03-22 09:33:25 -070045 @usableFromInline
Austin Schuh58b9b472020-11-25 19:12:44 -080046 init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) {
47 self.memory = memory
48 self.capacity = capacity
49 self.unowned = unowned
Austin Schuh272c6132020-11-14 16:37:52 -080050 }
51
Austin Schuh58b9b472020-11-25 19:12:44 -080052 deinit {
53 if !unowned {
54 memory.deallocate()
55 }
Austin Schuh272c6132020-11-14 16:37:52 -080056 }
57
James Kuszmaul8e62b022022-03-22 09:33:25 -070058 @usableFromInline
Austin Schuh58b9b472020-11-25 19:12:44 -080059 func copy(from ptr: UnsafeRawPointer, count: Int) {
60 assert(
61 !unowned,
62 "copy should NOT be called on a buffer that is built by assumingMemoryBound")
63 memory.copyMemory(from: ptr, byteCount: count)
Austin Schuh272c6132020-11-14 16:37:52 -080064 }
65
James Kuszmaul8e62b022022-03-22 09:33:25 -070066 @usableFromInline
Austin Schuh58b9b472020-11-25 19:12:44 -080067 func initialize(for size: Int) {
68 assert(
69 !unowned,
70 "initalize should NOT be called on a buffer that is built by assumingMemoryBound")
71 memset(memory, 0, size)
Austin Schuh272c6132020-11-14 16:37:52 -080072 }
73
Austin Schuh58b9b472020-11-25 19:12:44 -080074 /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer
75 /// - Parameter size: Size of the current object
76 @usableFromInline
James Kuszmaul8e62b022022-03-22 09:33:25 -070077 func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
Austin Schuh58b9b472020-11-25 19:12:44 -080078 let currentWritingIndex = capacity &- writerSize
79 while capacity <= writerSize &+ size {
80 capacity = capacity << 1
81 }
Austin Schuh272c6132020-11-14 16:37:52 -080082
Austin Schuh58b9b472020-11-25 19:12:44 -080083 /// solution take from Apple-NIO
84 capacity = capacity.convertToPowerofTwo
Austin Schuh272c6132020-11-14 16:37:52 -080085
James Kuszmaul8e62b022022-03-22 09:33:25 -070086 let newData = UnsafeMutableRawPointer.allocate(
87 byteCount: capacity,
88 alignment: alignment)
Austin Schuh58b9b472020-11-25 19:12:44 -080089 memset(newData, 0, capacity &- writerSize)
90 memcpy(
91 newData.advanced(by: capacity &- writerSize),
92 memory.advanced(by: currentWritingIndex),
93 writerSize)
94 memory.deallocate()
95 memory = newData
Austin Schuh272c6132020-11-14 16:37:52 -080096 }
Austin Schuh58b9b472020-11-25 19:12:44 -080097 }
Austin Schuh272c6132020-11-14 16:37:52 -080098
Austin Schuh58b9b472020-11-25 19:12:44 -080099 @usableFromInline var _storage: Storage
Austin Schuh272c6132020-11-14 16:37:52 -0800100
Austin Schuh58b9b472020-11-25 19:12:44 -0800101 /// The size of the elements written to the buffer + their paddings
102 private var _writerSize: Int = 0
103 /// Aliginment of the current memory being written to the buffer
James Kuszmaul8e62b022022-03-22 09:33:25 -0700104 var alignment = 1
Austin Schuh58b9b472020-11-25 19:12:44 -0800105 /// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer
James Kuszmaul8e62b022022-03-22 09:33:25 -0700106 var writerIndex: Int { _storage.capacity &- _writerSize }
Austin Schuh272c6132020-11-14 16:37:52 -0800107
Austin Schuh58b9b472020-11-25 19:12:44 -0800108 /// Reader is the position of the current Writer Index (capacity - size)
109 public var reader: Int { writerIndex }
110 /// Current size of the buffer
111 public var size: UOffset { UOffset(_writerSize) }
112 /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason
113 public var memory: UnsafeMutableRawPointer { _storage.memory }
114 /// Current capacity for the buffer
115 public var capacity: Int { _storage.capacity }
Austin Schuh272c6132020-11-14 16:37:52 -0800116
Austin Schuh58b9b472020-11-25 19:12:44 -0800117 /// Constructor that creates a Flatbuffer object from a UInt8
118 /// - Parameter bytes: Array of UInt8
119 public init(bytes: [UInt8]) {
120 var b = bytes
121 _storage = Storage(count: bytes.count, alignment: alignment)
122 _writerSize = _storage.capacity
123 b.withUnsafeMutableBytes { bufferPointer in
124 self._storage.copy(from: bufferPointer.baseAddress!, count: bytes.count)
Austin Schuh272c6132020-11-14 16:37:52 -0800125 }
Austin Schuh58b9b472020-11-25 19:12:44 -0800126 }
Austin Schuh272c6132020-11-14 16:37:52 -0800127
Austin Schuh58b9b472020-11-25 19:12:44 -0800128 /// Constructor that creates a Flatbuffer from the Swift Data type object
129 /// - Parameter data: Swift data Object
130 public init(data: Data) {
131 var b = data
132 _storage = Storage(count: data.count, alignment: alignment)
133 _writerSize = _storage.capacity
134 b.withUnsafeMutableBytes { bufferPointer in
135 self._storage.copy(from: bufferPointer.baseAddress!, count: data.count)
Austin Schuh272c6132020-11-14 16:37:52 -0800136 }
Austin Schuh58b9b472020-11-25 19:12:44 -0800137 }
Austin Schuh272c6132020-11-14 16:37:52 -0800138
Austin Schuh58b9b472020-11-25 19:12:44 -0800139 /// Constructor that creates a Flatbuffer instance with a size
140 /// - Parameter size: Length of the buffer
141 init(initialSize size: Int) {
142 let size = size.convertToPowerofTwo
143 _storage = Storage(count: size, alignment: alignment)
144 _storage.initialize(for: size)
145 }
Austin Schuh272c6132020-11-14 16:37:52 -0800146
Austin Schuh58b9b472020-11-25 19:12:44 -0800147 #if swift(>=5.0)
148 /// Constructor that creates a Flatbuffer object from a ContiguousBytes
149 /// - Parameters:
150 /// - contiguousBytes: Binary stripe to use as the buffer
151 /// - count: amount of readable bytes
152 public init<Bytes: ContiguousBytes>(
153 contiguousBytes: Bytes,
154 count: Int)
155 {
156 _storage = Storage(count: count, alignment: alignment)
157 _writerSize = _storage.capacity
158 contiguousBytes.withUnsafeBytes { buf in
159 _storage.copy(from: buf.baseAddress!, count: buf.count)
Austin Schuh272c6132020-11-14 16:37:52 -0800160 }
Austin Schuh58b9b472020-11-25 19:12:44 -0800161 }
162 #endif
Austin Schuh272c6132020-11-14 16:37:52 -0800163
Austin Schuh58b9b472020-11-25 19:12:44 -0800164 /// Constructor that creates a Flatbuffer from unsafe memory region without copying
165 /// - Parameter assumingMemoryBound: The unsafe memory region
166 /// - Parameter capacity: The size of the given memory region
James Kuszmaul8e62b022022-03-22 09:33:25 -0700167 public init(
168 assumingMemoryBound memory: UnsafeMutableRawPointer,
169 capacity: Int)
170 {
Austin Schuh58b9b472020-11-25 19:12:44 -0800171 _storage = Storage(memory: memory, capacity: capacity, unowned: true)
172 _writerSize = capacity
173 }
174
175 /// Creates a copy of the buffer that's being built by calling sizedBuffer
176 /// - Parameters:
177 /// - memory: Current memory of the buffer
178 /// - count: count of bytes
James Kuszmaul8e62b022022-03-22 09:33:25 -0700179 init(memory: UnsafeMutableRawPointer, count: Int) {
Austin Schuh58b9b472020-11-25 19:12:44 -0800180 _storage = Storage(count: count, alignment: alignment)
181 _storage.copy(from: memory, count: count)
182 _writerSize = _storage.capacity
183 }
184
185 /// Creates a copy of the existing flatbuffer, by copying it to a different memory.
186 /// - Parameters:
187 /// - memory: Current memory of the buffer
188 /// - count: count of bytes
189 /// - removeBytes: Removes a number of bytes from the current size
James Kuszmaul8e62b022022-03-22 09:33:25 -0700190 init(
191 memory: UnsafeMutableRawPointer,
192 count: Int,
193 removing removeBytes: Int)
194 {
Austin Schuh58b9b472020-11-25 19:12:44 -0800195 _storage = Storage(count: count, alignment: alignment)
196 _storage.copy(from: memory, count: count)
197 _writerSize = removeBytes
198 }
199
200 /// Fills the buffer with padding by adding to the writersize
201 /// - Parameter padding: Amount of padding between two to be serialized objects
202 @usableFromInline
203 mutating func fill(padding: Int) {
204 assert(padding >= 0, "Fill should be larger than or equal to zero")
205 ensureSpace(size: padding)
206 _writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding)
207 }
208
James Kuszmaul8e62b022022-03-22 09:33:25 -0700209 /// Adds an array of type Scalar to the buffer memory
Austin Schuh58b9b472020-11-25 19:12:44 -0800210 /// - Parameter elements: An array of Scalars
211 @usableFromInline
212 mutating func push<T: Scalar>(elements: [T]) {
213 let size = elements.count &* MemoryLayout<T>.size
214 ensureSpace(size: size)
215 elements.reversed().forEach { s in
216 push(value: s, len: MemoryLayout.size(ofValue: s))
Austin Schuh272c6132020-11-14 16:37:52 -0800217 }
Austin Schuh58b9b472020-11-25 19:12:44 -0800218 }
219
James Kuszmaul8e62b022022-03-22 09:33:25 -0700220 /// Adds an object of type NativeStruct into the buffer
Austin Schuh58b9b472020-11-25 19:12:44 -0800221 /// - Parameters:
James Kuszmaul8e62b022022-03-22 09:33:25 -0700222 /// - value: Object that will be written to the buffer
223 /// - size: size to subtract from the WriterIndex
224 @inline(__always)
225 mutating func push<T: NativeStruct>(struct value: T, size: Int) {
Austin Schuh58b9b472020-11-25 19:12:44 -0800226 ensureSpace(size: size)
Austin Schuh58b9b472020-11-25 19:12:44 -0800227 var v = value
James Kuszmaul8e62b022022-03-22 09:33:25 -0700228 memcpy(_storage.memory.advanced(by: writerIndex &- size), &v, size)
229 _writerSize = _writerSize &+ size
Austin Schuh58b9b472020-11-25 19:12:44 -0800230 }
231
232 /// Adds an object of type Scalar into the buffer
233 /// - Parameters:
234 /// - value: Object that will be written to the buffer
235 /// - len: Offset to subtract from the WriterIndex
236 @usableFromInline
237 mutating func push<T: Scalar>(value: T, len: Int) {
238 ensureSpace(size: len)
239 var v = value
240 memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len)
241 _writerSize = _writerSize &+ len
242 }
243
244 /// Adds a string to the buffer using swift.utf8 object
245 /// - Parameter str: String that will be added to the buffer
246 /// - Parameter len: length of the string
247 @usableFromInline
248 mutating func push(string str: String, len: Int) {
249 ensureSpace(size: len)
James Kuszmaul8e62b022022-03-22 09:33:25 -0700250 if str.utf8
251 .withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) !=
252 nil
253 {
Austin Schuh58b9b472020-11-25 19:12:44 -0800254 } else {
255 let utf8View = str.utf8
256 for c in utf8View.reversed() {
257 push(value: c, len: 1)
258 }
259 }
260 }
261
262 /// Writes a string to Bytebuffer using UTF8View
263 /// - Parameters:
264 /// - bytes: Pointer to the view
265 /// - len: Size of string
James Kuszmaul8e62b022022-03-22 09:33:25 -0700266 @inline(__always)
267 mutating func push(
Austin Schuh58b9b472020-11-25 19:12:44 -0800268 bytes: UnsafeBufferPointer<String.UTF8View.Element>,
269 len: Int) -> Bool
270 {
271 memcpy(
272 _storage.memory.advanced(by: writerIndex &- len),
273 UnsafeRawPointer(bytes.baseAddress!),
274 len)
275 _writerSize = _writerSize &+ len
276 return true
277 }
278
279 /// Write stores an object into the buffer directly or indirectly.
280 ///
281 /// Direct: ignores the capacity of buffer which would mean we are referring to the direct point in memory
282 /// indirect: takes into respect the current capacity of the buffer (capacity - index), writing to the buffer from the end
283 /// - Parameters:
284 /// - value: Value that needs to be written to the buffer
285 /// - index: index to write to
286 /// - direct: Should take into consideration the capacity of the buffer
287 func write<T>(value: T, index: Int, direct: Bool = false) {
288 var index = index
289 if !direct {
290 index = _storage.capacity &- index
291 }
292 assert(index < _storage.capacity, "Write index is out of writing bound")
293 assert(index >= 0, "Writer index should be above zero")
294 _storage.memory.storeBytes(of: value, toByteOffset: index, as: T.self)
295 }
296
297 /// Makes sure that buffer has enouch space for each of the objects that will be written into it
298 /// - Parameter size: size of object
299 @discardableResult
James Kuszmaul8e62b022022-03-22 09:33:25 -0700300 @inline(__always)
Austin Schuh58b9b472020-11-25 19:12:44 -0800301 mutating func ensureSpace(size: Int) -> Int {
302 if size &+ _writerSize > _storage.capacity {
303 _storage.reallocate(size, writerSize: _writerSize, alignment: alignment)
304 }
305 assert(size < FlatBufferMaxSize, "Buffer can't grow beyond 2 Gigabytes")
306 return size
307 }
308
309 /// pops the written VTable if it's already written into the buffer
310 /// - Parameter size: size of the `VTable`
James Kuszmaul8e62b022022-03-22 09:33:25 -0700311 @inline(__always)
312 mutating func pop(_ size: Int) {
313 assert(
314 (_writerSize &- size) > 0,
315 "New size should NOT be a negative number")
Austin Schuh58b9b472020-11-25 19:12:44 -0800316 memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size)
317 _writerSize = size
318 }
319
320 /// Clears the current size of the buffer
321 mutating public func clearSize() {
322 _writerSize = 0
323 }
324
325 /// Clears the current instance of the buffer, replacing it with new memory
326 mutating public func clear() {
327 _writerSize = 0
328 alignment = 1
329 _storage.initialize(for: _storage.capacity)
330 }
331
332 /// Reads an object from the buffer
333 /// - Parameters:
334 /// - def: Type of the object
335 /// - position: the index of the object in the buffer
336 public func read<T>(def: T.Type, position: Int) -> T {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700337 _storage.memory.advanced(by: position).load(as: T.self)
Austin Schuh58b9b472020-11-25 19:12:44 -0800338 }
339
340 /// Reads a slice from the memory assuming a type of T
341 /// - Parameters:
342 /// - index: index of the object to be read from the buffer
343 /// - count: count of bytes in memory
James Kuszmaul8e62b022022-03-22 09:33:25 -0700344 @inline(__always)
Austin Schuh58b9b472020-11-25 19:12:44 -0800345 public func readSlice<T>(
James Kuszmaul8e62b022022-03-22 09:33:25 -0700346 index: Int,
347 count: Int) -> [T]
Austin Schuh58b9b472020-11-25 19:12:44 -0800348 {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700349 assert(
350 index + count <= _storage.capacity,
351 "Reading out of bounds is illegal")
352 let start = _storage.memory.advanced(by: index)
353 .assumingMemoryBound(to: T.self)
354 let array = UnsafeBufferPointer(start: start, count: count)
Austin Schuh58b9b472020-11-25 19:12:44 -0800355 return Array(array)
356 }
357
358 /// Reads a string from the buffer and encodes it to a swift string
359 /// - Parameters:
360 /// - index: index of the string in the buffer
361 /// - count: length of the string
362 /// - type: Encoding of the string
363 public func readString(
James Kuszmaul8e62b022022-03-22 09:33:25 -0700364 at index: Int,
365 count: Int,
Austin Schuh58b9b472020-11-25 19:12:44 -0800366 type: String.Encoding = .utf8) -> String?
367 {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700368 assert(
369 index + count <= _storage.capacity,
370 "Reading out of bounds is illegal")
371 let start = _storage.memory.advanced(by: index)
372 .assumingMemoryBound(to: UInt8.self)
373 let bufprt = UnsafeBufferPointer(start: start, count: count)
Austin Schuh58b9b472020-11-25 19:12:44 -0800374 return String(bytes: Array(bufprt), encoding: type)
375 }
376
377 /// Creates a new Flatbuffer object that's duplicated from the current one
378 /// - Parameter removeBytes: the amount of bytes to remove from the current Size
379 public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer {
380 assert(removeBytes > 0, "Can NOT remove negative bytes")
James Kuszmaul8e62b022022-03-22 09:33:25 -0700381 assert(
382 removeBytes < _storage.capacity,
383 "Can NOT remove more bytes than the ones allocated")
Austin Schuh58b9b472020-11-25 19:12:44 -0800384 return ByteBuffer(
385 memory: _storage.memory,
386 count: _storage.capacity,
387 removing: _writerSize &- removeBytes)
388 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700389
390 /// Returns the written bytes into the ``ByteBuffer``
391 public var underlyingBytes: [UInt8] {
392 let cp = capacity &- writerIndex
393 let start = memory.advanced(by: writerIndex)
394 .bindMemory(to: UInt8.self, capacity: cp)
395
396 let ptr = UnsafeBufferPointer<UInt8>(start: start, count: cp)
397 return Array(ptr)
398 }
399
400 /// SkipPrefix Skips the first 4 bytes in case one of the following
401 /// functions are called `getPrefixedSizeCheckedRoot` & `getPrefixedSizeRoot`
402 /// which allows us to skip the first 4 bytes instead of recreating the buffer
403 @usableFromInline
404 mutating func skipPrefix() {
405 _writerSize = _writerSize &- MemoryLayout<Int32>.size
406 }
Austin Schuh272c6132020-11-14 16:37:52 -0800407}
408
409extension ByteBuffer: CustomDebugStringConvertible {
410
Austin Schuh58b9b472020-11-25 19:12:44 -0800411 public var debugDescription: String {
412 """
413 buffer located at: \(_storage.memory), with capacity of \(_storage.capacity)
414 { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) }
415 """
416 }
Austin Schuh272c6132020-11-14 16:37:52 -0800417}