Skip to content

Commit a62f45f

Browse files
authored
Improves the performance of the string imp (#8772)
Improves the performance of the implementation in Swift by using withCString instead of the contigiousString
1 parent 5998472 commit a62f45f

File tree

2 files changed

+11
-32
lines changed

2 files changed

+11
-32
lines changed

swift/Sources/FlatBuffers/FlatBufferBuilder.swift

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,9 @@ public struct FlatBufferBuilder {
207207
len: size &+ (prefix ? size : 0) &+ FileIdLength,
208208
alignment: _minAlignment)
209209
assert(fileId.count == FileIdLength, "Flatbuffers requires file id to be 4")
210-
_bb.push(string: fileId, len: 4)
210+
fileId.withCString { ptr in
211+
_bb.writeBytes(ptr, len: 4)
212+
}
211213
finish(offset: offset, addPrefix: prefix)
212214
}
213215

@@ -706,8 +708,9 @@ public struct FlatBufferBuilder {
706708
let len = str.utf8.count
707709
notNested()
708710
preAlign(len: len &+ 1, type: UOffset.self)
709-
_bb.fill(padding: 1)
710-
_bb.push(string: str, len: len)
711+
str.withCString { ptr in
712+
_bb.writeBytes(ptr, len: len &+ 1)
713+
}
711714
push(element: UOffset(len))
712715
return Offset(offset: _bb.size)
713716
}

swift/Sources/FlatBuffers/_InternalByteBuffer.swift

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -192,41 +192,17 @@ struct _InternalByteBuffer {
192192
}
193193
}
194194

195-
/// Adds a string to the buffer using swift.utf8 object
196-
/// - Parameter str: String that will be added to the buffer
197-
/// - Parameter len: length of the string
195+
/// Adds a RawPointer into the buffer
196+
/// - Parameter pointer: pointer to be copied into the buffer
197+
/// - Parameter len: length of the data
198198
@inline(__always)
199-
@usableFromInline
200-
mutating func push(string str: String, len: Int) {
199+
mutating func writeBytes(_ ptr: UnsafeRawPointer, len: Int) {
201200
ensureSpace(size: len)
202-
if str.utf8
203-
.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) !=
204-
nil
205-
{
206-
} else {
207-
let utf8View = str.utf8
208-
for c in utf8View.reversed() {
209-
push(value: c, len: 1)
210-
}
211-
}
212-
}
213-
214-
/// Writes a string to Bytebuffer using UTF8View
215-
/// - Parameters:
216-
/// - bytes: Pointer to the view
217-
/// - len: Size of string
218-
@usableFromInline
219-
@inline(__always)
220-
mutating func push(
221-
bytes: UnsafeBufferPointer<String.UTF8View.Element>,
222-
len: Int) -> Bool
223-
{
224201
memcpy(
225202
_storage.memory.advanced(by: writerIndex &- len),
226-
bytes.baseAddress!,
203+
ptr,
227204
len)
228205
_writerSize = _writerSize &+ len
229-
return true
230206
}
231207

232208
/// Write stores an object into the buffer directly or indirectly.

0 commit comments

Comments
 (0)