Skip to content

Commit

Permalink
Replaces assumingMemoryBinding with bindMemory which is safer
Browse files Browse the repository at this point in the history
  • Loading branch information
mustiikhalil committed Jan 13, 2025
1 parent 8b96c52 commit 665319c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
10 changes: 6 additions & 4 deletions swift/Sources/FlatBuffers/ByteBuffer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,9 @@ public struct ByteBuffer {
/// - position: the index of the object in the buffer
@inline(__always)
public func read<T>(def: T.Type, position: Int) -> T {
_storage.memory.advanced(by: position).assumingMemoryBound(to: T.self)
_storage.memory
.advanced(by: position)
.bindMemory(to: T.self, capacity: 1)
.pointee
}

Expand All @@ -462,7 +464,7 @@ public struct ByteBuffer {
index + count <= _storage.capacity,
"Reading out of bounds is illegal")
let start = _storage.memory.advanced(by: index)
.assumingMemoryBound(to: T.self)
.bindMemory(to: T.self, capacity: count)
let array = UnsafeBufferPointer(start: start, count: count)
return Array(array)
}
Expand All @@ -483,7 +485,7 @@ public struct ByteBuffer {
index + count <= _storage.capacity,
"Reading out of bounds is illegal")
let start = _storage.memory.advanced(by: index)
.assumingMemoryBound(to: UInt8.self)
.bindMemory(to: UInt8.self, capacity: count)
let bufprt = UnsafeBufferPointer(start: start, count: count)
return String(bytes: Array(bufprt), encoding: type)
}
Expand All @@ -501,7 +503,7 @@ public struct ByteBuffer {
index + count <= _storage.capacity,
"Reading out of bounds is illegal")
let start = _storage.memory.advanced(by: index)
.assumingMemoryBound(to: UInt8.self)
.bindMemory(to: UInt8.self, capacity: count)
let bufprt = UnsafeBufferPointer(start: start, count: count)
return String(cString: bufprt.baseAddress!)
}
Expand Down
7 changes: 5 additions & 2 deletions swift/Sources/FlatBuffers/FlatBufferBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ public struct FlatBufferBuilder {
/// Note: This should be used with caution.
public var fullSizedByteArray: [UInt8] {
let ptr = UnsafeBufferPointer(
start: _bb.memory.assumingMemoryBound(to: UInt8.self),
start: _bb.memory.bindMemory(
to: UInt8.self,
capacity: _bb.capacity
),
count: _bb.capacity)
return Array(ptr)
}
Expand Down Expand Up @@ -283,7 +286,7 @@ public struct FlatBufferBuilder {
var isAlreadyAdded: Int?

let vt2 = _bb.memory.advanced(by: _bb.writerIndex)
let len2 = vt2.load(fromByteOffset: 0, as: Int16.self)
let len2 = vt2.bindMemory(to: Int16.self, capacity: 1).pointee

for index in stride(from: 0, to: _vtables.count, by: 1) {
let position = _bb.capacity &- Int(_vtables[index])
Expand Down

0 comments on commit 665319c

Please sign in to comment.