When is `UnsafeMutableBufferPointer.baseAddress` `nil`?

A recent discussion (How can I call the specialized version of a generic function?) makes me wonder when UnsafeMutableBuffer.baseAddress can be nil. I just quickly checked:

Are these cases guaranteed to be non-nil? Is there a case that leads to nil other than manually assign nil to the pointer?

1 Like

SE–0055: Make unsafe pointer nullability explicit using Optional

The only time when the base address can be nil is if the buffer is empty. If the count is greater than zero, then the base address is guaranteed not to be nil.

5 Likes

Perhaps my actual question is where in the standard library are utilising this fact. Amongst the standard library functions that vent out UnsafeMutable<Raw>BufferPointer in one way or another:

  • UnsafeMutable<Raw><Buffer>.allocate
  • Array.init(unsafeUninitializedCapacity:initializingWith:)

None of them are using nil even if the the size is 0. It makes me wonder if I need to check for it at all.

There're also Unsafe<Raw>BufferPointer.init(start:count:) that can manually take nil. So I suppose I need to be wary of third-party initialising it that way, but such worry seems to be unneeded for standard library.

It's in Foundation, rather than the standard library, but EmptyCollection<T>.withUnsafeBytes:

1 Like

User code, including C code, is allowed to create buffers that use nil as the base address, regardless of whether the standard library utilizes the ability.

1 Like