How to get the base array from an `ArraySlice`?

Slice and Substring have a convenient base property, which is useful for getting access to the whole collection, but ArraySlice seems to have this functionality omitted. Is this intentional? Is it possible to get the whole array from an ArraySlice?

7 Likes
extension ArraySlice {
    var horribleBase: Array<Element> { 
        unsafeBitCast(_owner!, to: Array<Element>.self) 
    }
}

:sweat_smile:

6 Likes

A suggestion:

extension ArraySlice {
-    var horribleBase: Array<Element> { 
+    var b͇͇ͭͥă̻̭̺͚̝̿̂ͦ́s̮̫ͪ̈e̎̾ͨ̂ͧ̓͑: Array<Element> {
        unsafeBitCast(_owner!, to: Array<Element>.self) 
    }
}
15 Likes

is the unsafeBitCast needed? _owner is AnyObject? so can we just use as!?

let xs = [1, 2, 3]
let ys = xs[...]
let zs = ys._owner as? [Int] // 🛑 EXC_BAD_ACCESS

:sweat_smile:

1 Like

It's an instance of _ContiguousArrayStorage<Int>.

The unsafeBitCast only works because it happens that Array is just a struct wrapper around a _ContiguousArrayStorage or one of the other storage back ends (IIRC, don't quote me, check the source for yourself)

1 Like

Is this useful?
If it is useful should it be public API?

@tera I believe it is, which is why I asked. I'm working on code that generically uses a subsequence to "frame" it in its broader collection. It works great for strings via Substring, and other sequences that use Slice, but no such love for ArraySlice.

2 Likes