[swift-evolution] MemoryLayout for a value

Dave Abrahams dabrahams at apple.com
Wed Aug 3 15:43:26 CDT 2016


Having seen the effects in the standard library and in other
code, I'm concerned that we may have made a mistake in removing
`sizeofValue` et al without providing a replacement.  In the standard
library, we ended up adding an underscored API that allows

  MemoryLayout._ofInstance(someExpression).size

Where someExpression is an autoclosure, and thus not evaluated.  I
wanted to bring up the possibility of introducing a replacement as a
bufix.

I propose that the way to express the above should be:

  MemoryLayout.of(type(of: someExpression)).size

implementable as:

  extension MemoryLayout {
    @_transparent
    public
    static func of(_: T.Type) -> MemoryLayout<T>.Type {
      return MemoryLayout<T>.self
    }
  }

I think this API would solve the concerns I had about confusability that
led me to advocate dropping the ability to ask for the size of a value.
The only way to use it is to pass a type and these two expressions have
equivalent meaning:

    MemoryLayout<Int>
    MemoryLayout.of(Int.self)

It also has the benefit of isolating the autoclosure magic to type(of:).

,----[ Aside ]
| A slightly cleaner use site is possible with a larger API change:
| 
|   MemoryLayout(type(of: someExpression)).size
| 
| Which would involve changing MemoryLayout from an `enum` to
| a `struct` and adding the following:
| 
|   extension MemoryLayout {
|     public init(_: T.Type) {}
| 
|     public var size: Int { return MemoryLayout.size }
|     public var stride: Int { return MemoryLayout.stride }
|     public var alignment: Int { return MemoryLayout.alignment }
|   }
| 
| However I am concerned that dropping ".of" at the use site is worth the
| added API complexity.
`----

Thoughts?
-- 
-Dave



More information about the swift-evolution mailing list