Anatoli P
Anatoli P

Reputation: 4891

Determine if a Data instance is contiguous

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?

Upvotes: 3

Views: 575

Answers (1)

Hamish
Hamish

Reputation: 80851

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.

Upvotes: 10

Related Questions