Skip to content

Commit f0450fc

Browse files
committed
improve calculations for memory allocations
1 parent 11a23df commit f0450fc

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

Sources/ReactiveStreams/stream-post.swift

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,21 @@ private let headOffset = MemoryLayout.offset(of: \PostBoxState.head)!
145145
private let tailOffset = MemoryLayout.offset(of: \PostBoxState.tail)!
146146
private let lastOffset = MemoryLayout.offset(of: \PostBoxState.last)!
147147

148-
private let nextOffset = 0
149-
private let dataOffset = (MemoryLayout<AtomicOptionalMutableRawPointer>.stride + 15) & ~15
148+
private struct NodePrefix
149+
{
150+
var next: UnsafeMutableRawPointer?
151+
}
152+
private let nextOffset = MemoryLayout.offset(of: \NodePrefix.next)!
150153

151154
private struct BufferNode<Element>: Equatable
152155
{
153156
let storage: UnsafeMutableRawPointer
154157

158+
private var dataOffset: Int {
159+
let dataMask = MemoryLayout<Element>.alignment - 1
160+
return (MemoryLayout<NodePrefix>.size + dataMask) & ~dataMask
161+
}
162+
155163
init(storage: UnsafeMutableRawPointer)
156164
{
157165
self.storage = storage
@@ -165,8 +173,11 @@ private struct BufferNode<Element>: Equatable
165173

166174
private init()
167175
{
176+
let alignment = max(MemoryLayout<NodePrefix>.alignment, MemoryLayout<Element>.alignment)
177+
let dataMask = MemoryLayout<Element>.alignment - 1
178+
let dataOffset = (MemoryLayout<NodePrefix>.size + dataMask) & ~dataMask
168179
let size = dataOffset + MemoryLayout<Element>.size
169-
storage = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 16)
180+
storage = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
170181
(storage+nextOffset).bindMemory(to: AtomicOptionalMutableRawPointer.self, capacity: 1)
171182
CAtomicsInitialize(next, nil)
172183
(storage+dataOffset).bindMemory(to: Element.self, capacity: 1)

0 commit comments

Comments
 (0)