Skip to content

Commit

Permalink
Address a bug where the bytebuffer starts a memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
mustiikhalil committed Jan 11, 2025
1 parent 161c6b2 commit 62f1d09
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ let benchmarks = {
}
}

Benchmark("Allocating ByteBuffer 1GB", configuration: singleConfiguration) { benchmark in
Benchmark(
"Allocating ByteBuffer 1GB",
configuration: singleConfiguration)
{ benchmark in
let memory = UnsafeMutableRawPointer.allocate(
byteCount: 1_024_000_000,
alignment: 1)
Expand Down
15 changes: 9 additions & 6 deletions swift/Sources/FlatBuffers/ByteBuffer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ public struct ByteBuffer {
case none
}

// This storage doesn't own the memory, therefore, we won't deallocate on deinit.
/// This storage doesn't own the memory, therefore, we won't deallocate on deinit.
private let unowned: Bool
private let retainedBlob: Blob
/// Retained blob of data that requires the storage to retain a pointer to.
let retainedBlob: Blob
/// pointer to the start of the buffer object in memory
var memory: UnsafeMutableRawPointer
/// Capacity of UInt8 the buffer can hold
Expand Down Expand Up @@ -200,7 +201,9 @@ public struct ByteBuffer {
#endif

/// Constructor that creates a Flatbuffer from unsafe memory region without copying
/// - Parameter:
/// **NOTE** Needs a call to `memory.deallocate()` later on to free the memory
///
/// - Parameters:
/// - assumingMemoryBound: The unsafe memory region
/// - capacity: The size of the given memory region
@inline(__always)
Expand All @@ -221,11 +224,11 @@ public struct ByteBuffer {
/// - removeBytes: Removes a number of bytes from the current size
@inline(__always)
init(
memory: UnsafeMutableRawPointer,
blob: Storage.Blob,
count: Int,
removing removeBytes: Int)
{
_storage = Storage(blob: .pointer(memory), capacity: count)
_storage = Storage(blob: blob, capacity: count)
_writerSize = removeBytes
}

Expand Down Expand Up @@ -497,7 +500,7 @@ public struct ByteBuffer {
removeBytes < _storage.capacity,
"Can NOT remove more bytes than the ones allocated")
return ByteBuffer(
memory: _storage.memory,
blob: _storage.retainedBlob,
count: _storage.capacity,
removing: _writerSize &- removeBytes)
}
Expand Down

0 comments on commit 62f1d09

Please sign in to comment.