From developer.apple.com/ManagedBufferPointer/Capacity:
This value may be nontrivial to compute; it is usually a good idea to store this information in the “header” area when an instance is created.
Under the hood
From ManagedBuffer.swift:
extension ManagedBufferPointer {
@inlinable
@available(OpenBSD, unavailable, message: "malloc_size is unavailable.")
public var capacity: Int {
return (
_capacityInBytes &- ManagedBufferPointer._elementOffset
) / MemoryLayout<Element>.stride
}
}
Where _capacityInBytes is defined as malloc_size:
static inline __swift_size_t _swift_stdlib_malloc_size(const void *ptr) {
extern __swift_size_t malloc_size(const void *);
return malloc_size(ptr);
}
Solutions
- Store additional member
capacity: Int in Header. Header size: 2 words.
- Pack
capacity inside existing header. Header size: 1 word. Layout [1bit - isNegative][31 bits - count][32 bits - capacity]
From developer.apple.com/ManagedBufferPointer/Capacity:
Under the hood
From ManagedBuffer.swift:
Where
_capacityInBytesis defined asmalloc_size:Solutions
capacity: IntinHeader. Header size: 2 words.capacityinside existing header. Header size: 1 word. Layout[1bit - isNegative][31 bits - count][32 bits - capacity]