[swift-evolution] [Review] SE-0136: Memory Layout of Values

Dave Abrahams dabrahams at apple.com
Sun Aug 7 22:21:15 CDT 2016


on Sun Aug 07 2016, Brandon Knope <bknope-AT-me.com> wrote:

> Yes but:
>
> extension MemoryLayout {
>   @_transparent
>   public static func size(ofValue _: T) -> Int {
>     return MemoryLayout.size
>   }
>   @_transparent
>   public static func stride(ofValue _: T) -> Int {
>     return MemoryLayout.stride
>   }
>   @_transparent
>   public static func alignment(ofValue _: T) -> Int {
>     return MemoryLayout.alignment
> Vs
>
> public struct MemoryLayout<T> { 
>      public static var size: Int { return _sizeof(T) } 
>      public static var stride: Int { return _strideof(T) } 
>      public static var alignment: Int { return _alignof(T) }
> }
>
> I see the obvious difference between the two in their names and signature, but what is the need for both?
>
> It looks duplicated for the most part, so some clarification would be nice. 

The use case is this: you have a value, but you don't have its type at
compile-time, and you want memory layout information.  For example, it
might be the result of

     let x = (0..<20).reversed().lazy.map { $0 * 3 }

(which has a horrible type you wouldn't want to spell out) and you want
to know the size of the instance x.

     MemoryLayout.size(ofValue: x)

will work here.  Getting a type to pass in the angle brackets requires
jumping through lots of hoops and is easy to get wrong.

-- 
-Dave


More information about the swift-evolution mailing list