3 Replies
      Latest reply: Feb 10, 2017 3:18 PM by eskimo RSS
      granada29 Level 1 Level 1 (0 points)

        I have a C struct that stores a MAC address as an array of 6 unsigned characters (u_char) i.e.

         

        u_char mac[6];
        

         

        In swift this array is seen as a tuple (UInt8,UInt8,UInt8,UInt8,UInt8,UInt8)

         

        I want to store this tuple into a Swift array in the fastest way possible. Currently I am using memcpy but wondered if there is a more Swiftified way of doing this without sacrificing speed.

         

          var dst_mac: [u_char] {
               var a = [u_char](repeating: 0, count: 6)
               var mac = m_flow.dst_mac
               memcpy(&a, &mac, 6)
               return a
          }
        
        • Re: convert tuple to swift array
          eskimo Apple Staff Apple Staff (6,055 points)

          I usually do this via UnsafeBufferPointer.  For example:

          struct Foo {
              var tuple: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
              var array: [UInt8] {
                  var tmp = self.tuple
                  return [UInt8](UnsafeBufferPointer(start: &tmp.0, count: MemoryLayout.size(ofValue: tmp)))
              }
          }
          
          let f = Foo(tuple: (1, 2, 3, 4, 5, 6))
          print(f.array)  // prints: [1, 2, 3, 4, 5, 6]
          

          I think that code is clearer.  Whether it’s faster is hard to say.  You’d have to profile it, which is tricky when you’re dealing with tiny code snippets like this.

          Share and Enjoy

          Quinn “The Eskimo!”
          Apple Developer Relations, Developer Technical Support, Core OS/Hardware
          let myEmail = "eskimo" + "1" + "@apple.com"

            • Re: convert tuple to swift array
              granada29 Level 1 Level 1 (0 points)

              Thank you Quinn

               

              Just I what I was looking for. I'm not convinced about clearer (too many years of C/C++ and memxxx have always been my friends) but I was concerned about my assumptions involving the number of bytes in the tuple and its alignment.

               

              Bryan

                • Re: convert tuple to swift array
                  eskimo Apple Staff Apple Staff (6,055 points)

                  I was concerned about my assumptions involving the number of bytes in the tuple and its alignment.

                  Yeah, I was concerned about that too.  A while back I talked this over with one of the Swift engineers, and they assured me that homogeneous tuple elements would be laid out in a way that’s compatible with UnsafeBufferPointer, and thus the &tmp.0 trick that I used on line 5 is fine.

                  Share and Enjoy

                  Quinn “The Eskimo!”
                  Apple Developer Relations, Developer Technical Support, Core OS/Hardware
                  let myEmail = "eskimo" + "1" + "@apple.com"