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

Xiaodi Wu xiaodi.wu at gmail.com
Sun Aug 7 23:57:36 CDT 2016


I should add, it serves to clarify intention to the reader as well. Take,
for instance:

let array = [0, 1, 2]
let x = strideofValue(array[0]) // using the Swift 2 name
// stdlib testing code actually does something like this at one point

A reader can see on inspection that x is the correct increment for
advancing through the raw bytes of the array. If I edit the first line to
`let array = [0, 1.5, 2]`, x is still appropriate for that use on 32-bit
systems. And if I tried to use x to advance through the bytes of a
different array2, it would definitely prompt a reader to take a second look
at the code.

Of course, it is trivial to rewrite the second line as `let x =
MemoryLayout<Int>.stride` and to adjust if the type of array changes. But
combine that with a scenario such as Dave's, and it can be much more
difficult for a reader to discern whether the code is asking for the memory
layout properties of the right type.

On Sun, Aug 7, 2016 at 10:21 PM Dave Abrahams <dabrahams at apple.com> wrote:

>
> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160808/5c69a4b3/attachment.html>


More information about the swift-evolution mailing list