Violet icon indicating copy to clipboard operation
Violet copied to clipboard

Store `BigIntStorage.capacity` in header

Open LiarPrincess opened this issue 3 years ago • 1 comments

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]

LiarPrincess avatar May 18 '22 08:05 LiarPrincess

Additional reference: loftwareArrayOfOptional (Dave Abrahams thingy).

LiarPrincess avatar Jun 08 '22 09:06 LiarPrincess