diff --git a/swift.swiftformat b/swift.swiftformat index e8b2c324b30..be8210238d6 100644 --- a/swift.swiftformat +++ b/swift.swiftformat @@ -17,7 +17,7 @@ --typeattributes prev-line # wrapAttributes # rules ---rules wrap,todos,anyObjectProtocol,redundantParens,redundantReturn,redundantSelf,sortImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader +--rules wrap,todos,anyObjectProtocol,redundantParens,redundantSelf,sortImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader --disable trailingclosures --exclude **/*_generated.swift diff --git a/swift/Sources/FlatBuffers/ByteBuffer.swift b/swift/Sources/FlatBuffers/ByteBuffer.swift index 9589f6614da..31485794e45 100644 --- a/swift/Sources/FlatBuffers/ByteBuffer.swift +++ b/swift/Sources/FlatBuffers/ByteBuffer.swift @@ -36,16 +36,10 @@ public struct ByteBuffer { case byteBuffer(_InternalByteBuffer) case array([UInt8]) case pointer(UnsafeMutableRawPointer) - case writePointer(UnsafeMutableRawPointer) - - var isOwned: Bool { - switch self { - case .writePointer: true - default: false - } - } } + /// This storage doesn't own the memory, therefore, we won't deallocate on deinit. + private let isOwned: Bool /// Retained blob of data that requires the storage to retain a pointer to. @usableFromInline var retainedBlob: Blob @@ -58,18 +52,21 @@ public struct ByteBuffer { byteCount: count, alignment: MemoryLayout.alignment) capacity = count - retainedBlob = .writePointer(memory) + retainedBlob = .pointer(memory) + isOwned = true } @usableFromInline init(blob: Blob, capacity count: Int) { capacity = count retainedBlob = blob + isOwned = false } deinit { + guard isOwned else { return } switch retainedBlob { - case .writePointer(let unsafeMutableRawPointer): + case .pointer(let unsafeMutableRawPointer): unsafeMutableRawPointer.deallocate() default: break } @@ -78,7 +75,7 @@ public struct ByteBuffer { @usableFromInline func copy(from ptr: UnsafeRawPointer, count: Int) { assert( - retainedBlob.isOwned, + isOwned, "copy should NOT be called on a buffer that is built by assumingMemoryBound") withUnsafeRawPointer { $0.copyMemory(from: ptr, byteCount: count) @@ -88,13 +85,14 @@ public struct ByteBuffer { @usableFromInline func initialize(for size: Int) { assert( - retainedBlob.isOwned, + isOwned, "initalize should NOT be called on a buffer that is built by assumingMemoryBound") withUnsafeRawPointer { memset($0, 0, size) } } + @discardableResult @inline(__always) func withUnsafeBytes( _ body: (UnsafeRawBufferPointer) throws @@ -102,20 +100,21 @@ public struct ByteBuffer { { switch retainedBlob { case .byteBuffer(let byteBuffer): - try byteBuffer.withUnsafeBytes(body) + return try byteBuffer.withUnsafeBytes(body) + #if !os(WASI) case .data(let data): - try data.withUnsafeBytes(body) + return try data.withUnsafeBytes(body) case .bytes(let contiguousBytes): - try contiguousBytes.withUnsafeBytes(body) + return try contiguousBytes.withUnsafeBytes(body) + #endif case .array(let array): - try array.withUnsafeBytes(body) + return try array.withUnsafeBytes(body) case .pointer(let ptr): - try body(UnsafeRawBufferPointer(start: ptr, count: capacity)) - case .writePointer(let ptr): - try body(UnsafeRawBufferPointer(start: ptr, count: capacity)) + return try body(UnsafeRawBufferPointer(start: ptr, count: capacity)) } } + @discardableResult @inline(__always) func withUnsafeRawPointer( _ body: (UnsafeMutableRawPointer) throws @@ -123,29 +122,30 @@ public struct ByteBuffer { { switch retainedBlob { case .byteBuffer(let byteBuffer): - try byteBuffer.withUnsafeRawPointer(body) + return try byteBuffer.withUnsafeRawPointer(body) + #if !os(WASI) case .data(let data): - try data + return try data .withUnsafeBytes { try body(UnsafeMutableRawPointer(mutating: $0.baseAddress!)) } case .bytes(let contiguousBytes): - try contiguousBytes + return try contiguousBytes .withUnsafeBytes { try body(UnsafeMutableRawPointer(mutating: $0.baseAddress!)) } + #endif case .array(let array): - try array + return try array .withUnsafeBytes { try body(UnsafeMutableRawPointer(mutating: $0.baseAddress!)) } case .pointer(let ptr): - try body(ptr) - case .writePointer(let ptr): - try body(ptr) + return try body(ptr) } } + @discardableResult @inline(__always) func readWithUnsafeRawPointer( position: Int, @@ -153,23 +153,23 @@ public struct ByteBuffer { { switch retainedBlob { case .byteBuffer(let byteBuffer): - try byteBuffer.readWithUnsafeRawPointer(position: position, body) + return try byteBuffer.readWithUnsafeRawPointer(position: position, body) + #if !os(WASI) case .data(let data): - try data.withUnsafeBytes { + return try data.withUnsafeBytes { try body($0.baseAddress!.advanced(by: position)) } case .bytes(let contiguousBytes): - try contiguousBytes.withUnsafeBytes { + return try contiguousBytes.withUnsafeBytes { try body($0.baseAddress!.advanced(by: position)) } + #endif case .array(let array): - try array.withUnsafeBytes { + return try array.withUnsafeBytes { try body($0.baseAddress!.advanced(by: position)) } case .pointer(let ptr): - try body(ptr.advanced(by: position)) - case .writePointer(let ptr): - try body(ptr.advanced(by: position)) + return try body(ptr.advanced(by: position)) } } } @@ -178,10 +178,8 @@ public struct ByteBuffer { /// The size of the elements written to the buffer + their paddings private var _readerIndex: Int = 0 - /// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer - var writerIndex: Int { _storage.capacity &- _readerIndex } /// Reader is the position of the current Writer Index (capacity - size) - public var reader: Int { writerIndex } + public var reader: Int { _storage.capacity &- _readerIndex } /// Current size of the buffer public var size: UOffset { UOffset(_readerIndex) } /// Current capacity for the buffer @@ -192,7 +190,9 @@ public struct ByteBuffer { /// - bytes: Array of UInt8 @inline(__always) init(byteBuffer: _InternalByteBuffer) { - _storage = Storage(blob: .byteBuffer(byteBuffer), capacity: byteBuffer.capacity) + _storage = Storage( + blob: .byteBuffer(byteBuffer), + capacity: byteBuffer.capacity) _readerIndex = Int(byteBuffer.size) } @@ -293,7 +293,7 @@ public struct ByteBuffer { } assert(index < _storage.capacity, "Write index is out of writing bound") assert(index >= 0, "Writer index should be above zero") - withUnsafePointer(to: value) { ptr in + _ = withUnsafePointer(to: value) { ptr in _storage.withUnsafeRawPointer { memcpy( $0.advanced(by: index), @@ -392,7 +392,7 @@ public struct ByteBuffer { assert( index + count <= _storage.capacity, "Reading out of bounds is illegal") - return _storage.retainedBlob.readWithUnsafeRawPointer(position: index) { + return _storage.readWithUnsafeRawPointer(position: index) { String(cString: $0.bindMemory(to: UInt8.self, capacity: count)) } } @@ -433,7 +433,6 @@ public struct ByteBuffer { } @discardableResult - @usableFromInline @inline(__always) func withUnsafeMutableRawPointer( body: (UnsafeMutableRawPointer) throws @@ -441,6 +440,15 @@ public struct ByteBuffer { { try _storage.withUnsafeRawPointer(body) } + + @discardableResult + @inline(__always) + func readWithUnsafeRawPointer( + position: Int, + _ body: (UnsafeRawPointer) throws -> T) rethrows -> T + { + try _storage.readWithUnsafeRawPointer(position: position, body) + } } extension ByteBuffer: CustomDebugStringConvertible { @@ -449,7 +457,8 @@ extension ByteBuffer: CustomDebugStringConvertible { """ buffer located at: \(_storage.retainedBlob), with capacity of \(_storage.capacity), - { writerSize: \(_readerIndex), readerSize: \(reader), writerIndex: \(writerIndex) } + { writtenSize: \(_readerIndex), readerSize: \(reader), + size: \(size) } """ } } diff --git a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift index bc571233bc6..c96f24cde90 100644 --- a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift +++ b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift @@ -59,21 +59,21 @@ public struct FlatBufferBuilder { public var capacity: Int { _bb.capacity } #if !os(WASI) - /// Data representation of the buffer - /// - /// Should only be used after ``finish(offset:addPrefix:)`` is called - public var data: Data { - assert(finished, "Data shouldn't be called before finish()") - return _bb.withUnsafeSlicedBytes { ptr in - var data = Data() - data.append( - ptr.baseAddress!.bindMemory( - to: UInt8.self, - capacity: _bb.capacity), - count: _bb.capacity) - return data - } + /// Data representation of the buffer + /// + /// Should only be used after ``finish(offset:addPrefix:)`` is called + public var data: Data { + assert(finished, "Data shouldn't be called before finish()") + return _bb.withUnsafeSlicedBytes { ptr in + var data = Data() + data.append( + ptr.baseAddress!.bindMemory( + to: UInt8.self, + capacity: _bb.capacity), + count: _bb.capacity) + return data } + } #endif /// Returns the underlying bytes in the ``ByteBuffer`` @@ -110,7 +110,7 @@ public struct FlatBufferBuilder { public var sizedBuffer: ByteBuffer { assert(finished, "Data shouldn't be called before finish()") return _bb.withUnsafeSlicedBytes { ptr in - return ByteBuffer( + ByteBuffer( copyingMemoryBound: ptr.baseAddress!, capacity: ptr.count) } @@ -128,8 +128,8 @@ public struct FlatBufferBuilder { /// however the builder can be force by passing true for `serializeDefaults` public init( initialSize: Int32 = 1024, - serializeDefaults force: Bool = false - ) { + serializeDefaults force: Bool = false) + { assert(initialSize > 0, "Size should be greater than zero!") guard isLitteEndian else { fatalError( @@ -196,8 +196,8 @@ public struct FlatBufferBuilder { mutating public func finish( offset: Offset, fileId: String, - addPrefix prefix: Bool = false - ) { + addPrefix prefix: Bool = false) + { let size = MemoryLayout.size preAlign( len: size &+ (prefix ? size : 0) &+ FileIdLength, @@ -226,8 +226,8 @@ public struct FlatBufferBuilder { /// include the size of the current buffer. mutating public func finish( offset: Offset, - addPrefix prefix: Bool = false - ) { + addPrefix prefix: Bool = false) + { notNested() let size = MemoryLayout.size preAlign(len: size &+ (prefix ? size : 0), alignment: _minAlignment) @@ -351,8 +351,8 @@ public struct FlatBufferBuilder { @usableFromInline mutating internal func padding( bufSize: UInt32, - elementSize: UInt32 - ) -> UInt32 { + elementSize: UInt32) -> UInt32 + { ((~bufSize) &+ 1) & (elementSize &- 1) } @@ -479,8 +479,8 @@ public struct FlatBufferBuilder { @inline(__always) mutating public func createVector( _ elements: [T], - size: Int - ) -> Offset { + size: Int) -> Offset + { let size = size startVector(size, elementSize: MemoryLayout.size) _bb.push(elements: elements) @@ -488,20 +488,20 @@ public struct FlatBufferBuilder { } #if swift(>=5.0) && !os(WASI) - @inline(__always) - /// Creates a vector of bytes in the buffer. - /// - /// Allows creating a vector from `Data` without copying to a `[UInt8]` - /// - /// - Parameter bytes: bytes to be written into the buffer - /// - Returns: ``Offset`` of the vector - mutating public func createVector(bytes: ContiguousBytes) -> Offset { - bytes.withUnsafeBytes { - startVector($0.count, elementSize: MemoryLayout.size) - _bb.push(bytes: $0) - return endVector(len: $0.count) - } + @inline(__always) + /// Creates a vector of bytes in the buffer. + /// + /// Allows creating a vector from `Data` without copying to a `[UInt8]` + /// + /// - Parameter bytes: bytes to be written into the buffer + /// - Returns: ``Offset`` of the vector + mutating public func createVector(bytes: ContiguousBytes) -> Offset { + bytes.withUnsafeBytes { + startVector($0.count, elementSize: MemoryLayout.size) + _bb.push(bytes: $0) + return endVector(len: $0.count) } + } #endif /// Creates a vector of type ``Enum`` into the ``ByteBuffer`` @@ -539,8 +539,8 @@ public struct FlatBufferBuilder { @inline(__always) mutating public func createVector( _ elements: [T], - size: Int - ) -> Offset { + size: Int) -> Offset + { let size = size startVector(size, elementSize: T.byteSize) for index in stride(from: elements.count, to: 0, by: -1) { @@ -585,8 +585,8 @@ public struct FlatBufferBuilder { @inline(__always) mutating public func createVector( ofOffsets offsets: [Offset], - len: Int - ) -> Offset { + len: Int) -> Offset + { startVector(len, elementSize: MemoryLayout.size) for index in stride(from: offsets.count, to: 0, by: -1) { push(element: offsets[index &- 1]) @@ -662,8 +662,8 @@ public struct FlatBufferBuilder { @inline(__always) @discardableResult mutating public func create( - struct s: T, position: VOffset - ) -> Offset { + struct s: T, position: VOffset) -> Offset + { let offset = create(struct: s) _vtableStorage.add( loc: (offset: _bb.size, position: VOffset(position))) @@ -687,8 +687,8 @@ public struct FlatBufferBuilder { @inline(__always) @discardableResult mutating public func create( - struct s: T - ) -> Offset { + struct s: T) -> Offset + { let size = MemoryLayout.size preAlign(len: size, alignment: MemoryLayout.alignment) _bb.push(struct: s, size: size) @@ -803,8 +803,8 @@ public struct FlatBufferBuilder { mutating public func add( element: T, def: T, - at position: VOffset - ) { + at position: VOffset) + { if element == def && !serializeDefaults { return } track(offset: push(element: element), at: position) } diff --git a/swift/Sources/FlatBuffers/Message.swift b/swift/Sources/FlatBuffers/Message.swift index 506cbea66c4..28436a2be83 100644 --- a/swift/Sources/FlatBuffers/Message.swift +++ b/swift/Sources/FlatBuffers/Message.swift @@ -40,7 +40,7 @@ public struct Message: FlatBufferGRPCMessage { public var object: T { T.init( buffer, - o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) + + o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) &+ Int32(buffer.reader)) } @@ -64,10 +64,12 @@ public struct Message: FlatBufferGRPCMessage { @discardableResult @inline(__always) - public func withUnsafeReadableBytes( + public func withUnsafeReadableBytes( _ body: (UnsafeRawBufferPointer) throws - -> T) rethrows -> T + -> Data) rethrows -> Data { - try buffer.withUnsafeBytes { try body($0) } + return try buffer.readWithUnsafeRawPointer(position: buffer.reader) { + try body(UnsafeRawBufferPointer(start: $0, count: size)) + } } } diff --git a/swift/Sources/FlatBuffers/Root.swift b/swift/Sources/FlatBuffers/Root.swift index 8e606e6ccf4..a725f1eb700 100644 --- a/swift/Sources/FlatBuffers/Root.swift +++ b/swift/Sources/FlatBuffers/Root.swift @@ -101,7 +101,7 @@ public func getCheckedRoot( try ForwardOffset.verify(&verifier, at: 0, of: T.self) return T.init( byteBuffer, - o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) + + o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) &+ Int32(byteBuffer.reader)) } @@ -111,6 +111,6 @@ public func getCheckedRoot( public func getRoot(byteBuffer: inout ByteBuffer) -> T { T.init( byteBuffer, - o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) + + o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) &+ Int32(byteBuffer.reader)) } diff --git a/swift/Sources/FlatBuffers/String+extension.swift b/swift/Sources/FlatBuffers/String+extension.swift index de4f5f91f0f..1a2df142ca6 100644 --- a/swift/Sources/FlatBuffers/String+extension.swift +++ b/swift/Sources/FlatBuffers/String+extension.swift @@ -64,7 +64,7 @@ extension String: FlatbuffersInitializable { let v = Int(o) let count = bb.read(def: Int32.self, position: v) self = bb.readString( - at: MemoryLayout.size + v, + at: MemoryLayout.size &+ v, count: Int(count)) ?? "" } } diff --git a/swift/Sources/FlatBuffers/Table.swift b/swift/Sources/FlatBuffers/Table.swift index 90feb2b2904..b3be4d1737e 100644 --- a/swift/Sources/FlatBuffers/Table.swift +++ b/swift/Sources/FlatBuffers/Table.swift @@ -46,11 +46,11 @@ public struct Table { /// - Parameter o: current offset /// - Returns: offset of field within buffer public func offset(_ o: Int32) -> Int32 { - let vtable = position - bb.read(def: Int32.self, position: Int(position)) + let vtable = position &- bb.read(def: Int32.self, position: Int(position)) return o < bb .read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read( def: Int16.self, - position: Int(vtable + o))) : 0 + position: Int(vtable &+ o))) : 0 } /// Gets the indirect offset of the current stored object @@ -58,13 +58,13 @@ public struct Table { /// - Parameter o: current offset /// - Returns: offset of field within buffer public func indirect(_ o: Int32) -> Int32 { - o + bb.read(def: Int32.self, position: Int(o)) + o &+ bb.read(def: Int32.self, position: Int(o)) } /// String reads from the buffer with respect to position of the current table. /// - Parameter offset: Offset of the string public func string(at offset: Int32) -> String? { - directString(at: offset + position) + directString(at: offset &+ position) } /// Direct string reads from the buffer disregarding the position of the table. @@ -73,9 +73,9 @@ public struct Table { /// - Parameter offset: Offset of the string public func directString(at offset: Int32) -> String? { var offset = offset - offset += bb.read(def: Int32.self, position: Int(offset)) + offset &+= bb.read(def: Int32.self, position: Int(offset)) let count = bb.read(def: Int32.self, position: Int(offset)) - let position = Int(offset) + MemoryLayout.size + let position = Int(offset) &+ MemoryLayout.size return bb.readString(at: position, count: Int(count)) } @@ -84,7 +84,7 @@ public struct Table { /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func readBuffer(of type: T.Type, at o: Int32) -> T { - directRead(of: T.self, offset: o + position) + directRead(of: T.self, offset: o &+ position) } /// Reads from the buffer disregarding the position of the table. @@ -109,7 +109,7 @@ public struct Table { /// - Parameter o: offset /// - Returns: A flatbuffers object public func union(_ o: Int32) -> T { - let o = o + position + let o = o &+ position return directUnion(o) } @@ -117,7 +117,7 @@ public struct Table { /// - Parameter o: offset /// - Returns: A flatbuffers object public func directUnion(_ o: Int32) -> T { - T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) + T.init(bb, o: o &+ bb.read(def: Int32.self, position: Int(o))) } /// Returns a vector of type T at a specific offset @@ -152,8 +152,8 @@ public struct Table { /// - returns: Count of elements public func vector(count o: Int32) -> Int32 { var o = o - o += position - o += bb.read(def: Int32.self, position: Int(o)) + o &+= position + o &+= bb.read(def: Int32.self, position: Int(o)) return bb.read(def: Int32.self, position: Int(o)) } @@ -162,8 +162,8 @@ public struct Table { /// - returns: the start index of the vector public func vector(at o: Int32) -> Int32 { var o = o - o += position - return o + bb.read(def: Int32.self, position: Int(o)) + 4 + o &+= position + return o &+ bb.read(def: Int32.self, position: Int(o)) + 4 } /// Reading an indirect offset of a table. @@ -187,10 +187,10 @@ public struct Table { vOffset: Int32, fbb: inout FlatBufferBuilder) -> Int32 { - let vTable = Int32(fbb.capacity) - o - return vTable + Int32(fbb.read( + let vTable = Int32(fbb.capacity) &- o + return vTable &+ Int32(fbb.read( def: Int16.self, - position: Int(vTable + vOffset - fbb.read( + position: Int(vTable &+ vOffset &- fbb.read( def: Int32.self, position: Int(vTable))))) } @@ -208,21 +208,21 @@ public struct Table { fbb: inout FlatBufferBuilder) -> Int32 { let memorySize = Int32(MemoryLayout.size) - let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) - let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) + let _off1 = off1 &+ fbb.read(def: Int32.self, position: Int(off1)) + let _off2 = off2 &+ fbb.read(def: Int32.self, position: Int(off2)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = fbb.read(def: Int32.self, position: Int(_off2)) - let startPos1 = _off1 + memorySize - let startPos2 = _off2 + memorySize + let startPos1 = _off1 &+ memorySize + let startPos2 = _off2 &+ memorySize let minValue = min(len1, len2) for i in 0...minValue { - let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) - let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) + let b1 = fbb.read(def: Int8.self, position: Int(i &+ startPos1)) + let b2 = fbb.read(def: Int8.self, position: Int(i &+ startPos2)) if b1 != b2 { - return Int32(b2 - b1) + return Int32(b2 &- b1) } } - return len1 - len2 + return len1 &- len2 } /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer @@ -238,19 +238,19 @@ public struct Table { fbb: inout FlatBufferBuilder) -> Int32 { let memorySize = Int32(MemoryLayout.size) - let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) + let _off1 = off1 &+ fbb.read(def: Int32.self, position: Int(off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = Int32(key.count) - let startPos1 = _off1 + memorySize + let startPos1 = _off1 &+ memorySize let minValue = min(len1, len2) for i in 0.. Int32 { - let vTable = Int32(fbb.capacity) - o - return vTable + Int32(fbb.read( + let vTable = Int32(fbb.capacity) &- o + return vTable &+ Int32(fbb.read( def: Int16.self, - position: Int(vTable + vOffset - fbb.read( + position: Int(vTable &+ vOffset &- fbb.read( def: Int32.self, position: Int(vTable))))) } @@ -286,21 +286,21 @@ public struct Table { fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout.size) - let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) - let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) + let _off1 = off1 &+ fbb.read(def: Int32.self, position: Int(off1)) + let _off2 = off2 &+ fbb.read(def: Int32.self, position: Int(off2)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = fbb.read(def: Int32.self, position: Int(_off2)) - let startPos1 = _off1 + memorySize - let startPos2 = _off2 + memorySize + let startPos1 = _off1 &+ memorySize + let startPos2 = _off2 &+ memorySize let minValue = min(len1, len2) for i in 0...minValue { - let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) - let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) + let b1 = fbb.read(def: Int8.self, position: Int(i &+ startPos1)) + let b2 = fbb.read(def: Int8.self, position: Int(i &+ startPos2)) if b1 != b2 { - return Int32(b2 - b1) + return Int32(b2 &- b1) } } - return len1 - len2 + return len1 &- len2 } /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer @@ -316,18 +316,18 @@ public struct Table { fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout.size) - let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) + let _off1 = off1 &+ fbb.read(def: Int32.self, position: Int(off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = Int32(key.count) - let startPos1 = _off1 + memorySize + let startPos1 = _off1 &+ memorySize let minValue = min(len1, len2) for i in 0.. where S: UnionEnum { while count < keysRange.count { /// index of readable enum value in array - let keysIndex = MemoryLayout.size * count + let keysIndex = MemoryLayout.size &* count guard let _enum = try S.init(value: verifier._buffer.read( def: S.T.self, - position: keysRange.start + keysIndex)) else + position: keysRange.start &+ keysIndex)) else { throw FlatbuffersErrors.unknownUnionCase } /// index of readable offset value in array - let fieldIndex = MemoryLayout.size * count - try completion(&verifier, _enum, offsetsRange.start + fieldIndex) - count += 1 + let fieldIndex = MemoryLayout.size &* count + try completion(&verifier, _enum, offsetsRange.start &+ fieldIndex) + count &+= 1 } } } diff --git a/swift/Sources/FlatBuffers/Verifier.swift b/swift/Sources/FlatBuffers/Verifier.swift index 7d51dd9e404..6f94f94c7f8 100644 --- a/swift/Sources/FlatBuffers/Verifier.swift +++ b/swift/Sources/FlatBuffers/Verifier.swift @@ -137,17 +137,17 @@ public struct Verifier { let length = Int(vtableLength) try isAligned( - position: Int(clamping: (vtablePosition + length).magnitude), + position: Int(clamping: (vtablePosition &+ length).magnitude), type: VOffset.self) try rangeInBuffer(position: vtablePosition, size: length) - storage.tableCount += 1 + storage.tableCount &+= 1 if storage.tableCount > _options._maxTableCount { throw FlatbuffersErrors.maximumTables } - storage.depth += 1 + storage.depth &+= 1 if storage.depth > _options._maxDepth { throw FlatbuffersErrors.maximumDepth @@ -214,7 +214,7 @@ public struct Verifier { @inline(__always) func verify(id: String) throws { let size = MemoryLayout.size - guard storage.capacity >= (size * 2) else { + guard storage.capacity >= (size &* 2) else { throw FlatbuffersErrors.bufferDoesntContainID } let str = _buffer.readString(at: size, count: size) diff --git a/swift/Sources/FlatBuffers/_InternalByteBuffer.swift b/swift/Sources/FlatBuffers/_InternalByteBuffer.swift index c6e3b3f85dc..74e828570b5 100644 --- a/swift/Sources/FlatBuffers/_InternalByteBuffer.swift +++ b/swift/Sources/FlatBuffers/_InternalByteBuffer.swift @@ -253,7 +253,7 @@ struct _InternalByteBuffer { } assert(index < _storage.capacity, "Write index is out of writing bound") assert(index >= 0, "Writer index should be above zero") - withUnsafePointer(to: value) { + _ = withUnsafePointer(to: value) { memcpy( _storage.memory.advanced(by: index), $0, diff --git a/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift b/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift index c9d48d5459b..a9e799f25cd 100644 --- a/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift +++ b/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift @@ -228,7 +228,7 @@ public struct Monster: FlatBufferObject, Verifiable { public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) } public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] } - public var inventoryPointer: UnsafeBufferPointer? { return _accessor.getBufferPointer(at: VTOFFSET.inventory.v) } + public func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.inventory.v, body: body) } public var color: Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 7) } public static func add(pos: Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) } @@ -261,7 +261,7 @@ public struct Monster: FlatBufferObject, Verifiable { } public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { var off = offsets - off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: &fbb), Table.offset(Int32($0.o), vOffset: 10, fbb: &fbb), fbb: &fbb) < 0 } return fbb.createVector(ofOffsets: off) } fileprivate static func lookupByKey(vector: Int32, key: String, fbb: ByteBuffer) -> Monster? { diff --git a/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift b/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift index 23cd3bfc3b9..65fce484081 100644 --- a/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift +++ b/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift @@ -213,6 +213,25 @@ class FlatBuffersMonsterWriterTests: XCTestCase { XCTAssertEqual(testUnaligned(), true) } + func testCreateMessage() { + let fbb = createMonster(withPrefix: false) + let byteBuffer = fbb.buffer + let firstMessage = Message(byteBuffer: byteBuffer) + firstMessage.withUnsafeReadableBytes { ptr in + var bytes = ByteBuffer(contiguousBytes: ptr, count: ptr.count) + var monster: Monster = getRoot(byteBuffer: &bytes) + self.readFlatbufferMonster(monster: &monster) + } + + let secondByteBuffer = fbb.sizedBuffer + let secondMessage = Message(byteBuffer: secondByteBuffer) + secondMessage.withUnsafeReadableBytes { ptr in + var bytes = ByteBuffer(contiguousBytes: ptr, count: ptr.count) + var monster: Monster = getRoot(byteBuffer: &bytes) + self.readFlatbufferMonster(monster: &monster) + } + } + func testForceRetainedObject() { let byteBuffer = { // swiftformat:disable all diff --git a/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift b/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift index 575340b40fb..c3a6a52c7c1 100644 --- a/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift +++ b/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift @@ -93,7 +93,8 @@ final class FlatBuffersUnionTests: XCTestCase { // swiftformat:disable all XCTAssertEqual(builder.sizedByteArray, [12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0]) // swiftformat:enable all - let monster = ColorsNameSpace.Monster.getRootAsMonster(bb: builder.sizedBuffer) + let monster = ColorsNameSpace.Monster + .getRootAsMonster(bb: builder.sizedBuffer) XCTAssertEqual(monster.colorsCount, 2) XCTAssertEqual(monster.colors(at: 0), .blue) XCTAssertEqual(monster.colors(at: 1), .green)