3

Let d be an instance of Data. In earlier versions of Swift, I could test if it was contiguous in memory using code like

d.enumerateBytes{(pBuf: UnsafeBufferPointer<UInt8>, idx: Data.Index, flag: inout Bool) -> Void in
            if (pBuf.count == d.count) { print("Data is contiguous!") }
        }

However, in Swift 5 enumerateBytes() is deprecated, and I get a warning such as the following:

warning: 'enumerateBytes' is deprecated: use `regions` or `for-in` instead

I'm tempted to do something like

if d.regions.count == 1 { print("Contiguous!!!") }

Yet regions is of type CollectionOfOne<Data>, which by definition always contains one element.

Any suggestions?

Anatoli P
  • 4,791
  • 1
  • 18
  • 22
  • Looking at the corelibs-foundation implementation, I don't see anything to suggest that `Data` supports non-contiguous storage. https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Data.swift#L117-L122 The apple implementation in macOS might differ, however. – Alexander Oct 04 '19 at 03:09
  • @Alexander The macOS implementation is defined in the Swift overlay: https://github.com/apple/swift/blob/013c4f1540c86a40507c9d3f6670aa60254d4540/stdlib/public/Darwin/Foundation/Data.swift. – Hamish Oct 04 '19 at 03:17

1 Answers1

10

As of Swift 5, all Data values have contiguous storage, with the type conforming to the new ContiguousBytes protocol (implemented in #20225). As @matt points out, this change was highlighted in a recent WWDC talk:

So from Swift 5 and onwards, we promise that struct Data is a contiguous buffer type.

Hamish
  • 78,605
  • 19
  • 187
  • 280
  • It's officially documented in that it conforms to ContiguousBytes. And also because they said so: https://developer.apple.com/videos/play/wwdc2019/723/?time=121 – matt Oct 04 '19 at 03:18
  • @matt Ah thanks for the WWDC link! It would still be nice if it were mentioned in the doc comment for `Data` though. – Hamish Oct 04 '19 at 03:29
  • Thanks everyone for the feedback and links! – Anatoli P Oct 04 '19 at 11:13
  • Hi man, can you take a look here? https://stackoverflow.com/questions/58712685/why-does-the-compiler-not-see-the-default-code-in-a-protocol – mfaani Nov 05 '19 at 15:32
  • @Hamish , happy new year! there's a worthy question old chap: stackoverflow.com/questions/60062841 – Fattie Feb 04 '20 at 18:47
  • you too, @LeoDabus ! – Fattie Feb 04 '20 at 18:47