Why doesn't Array use a ManagedBuffer?

I've been snooping around the standard library implementations of Array and ContiguousArray<Element>. So far I gather that:

Everything so far matches my expectations from the Swift Array design document:

This leaves me with a few questions:

  1. Where is __ContiguousArrayStorageBase defined?
  2. Why does _ArrayBody wrap _SwiftArrayBodyStorage? Why not use _SwiftArrayBodyStorage directly?
  3. Why doesn't any of this use ManagedBuffer? The bottom of the diagram above mentioned "Handled by ManagedBufferPointer<_ArrayBody, T>, but that doesn't seem to be the case. ManagedBuffer seems to be the Swift primitive for "A heap object with some fixed layout (a header), followed by tail allocated elements". I would have expected it to be used profusely by all of these data structures, yet it doesn't seem to be. What gives?
  4. Why do we use up a word per buffer just to store the capacity, when it could be implemented as a computed property that derives the value from _swift_stdlib_malloc_size (just like how the initializer already does it)? Is _swift_stdlib_malloc_size slow enough that this "caching" is required?
1 Like

Here's the implementation of __ContiguousArrayStorageBase. I'll leave the rest of those questions to the experts.