[stdlib] Add withContiguousStorageIfAvailable to SubString.UTF8View

Due to an oversight it seems that we never added a
withContigousStorageIfAvailable implementation to SubString.UTF8View,
which meant that if you sliced a String you lost the ability to get fast
access to the backing storage. There's no good reason for this
functionality to be missing, so this patch adds it in by delegating to
the Slice implementation.

Resolves SR-11999.
This commit is contained in:
Cory Benfield
2020-01-09 11:42:39 +00:00
parent 4a9fc98c8d
commit 68f0816daa
2 changed files with 27 additions and 0 deletions

View File

@@ -12,6 +12,19 @@ func checkMatch<S: Collection, T: Collection>(_ x: S, _ y: T, _ i: S.Index)
expectEqual(x[i], y[i])
}
func checkMatchContiguousStorage<S: Collection, T: Collection>(_ x: S, _ y: T)
where S.Element == T.Element, S.Element: Equatable
{
let xElement = x.withContiguousStorageIfAvailable { $0.first }
let yElement = y.withContiguousStorageIfAvailable { $0.first }
expectEqual(xElement, yElement)
}
func checkHasContiguousStorage<S: Collection>(_ x: S) {
let hasStorage = x.withContiguousStorageIfAvailable { _ in true } ?? false
expectTrue(hasStorage)
}
SubstringTests.test("Equality") {
let s = "abcdefg"
let s1 = s[s.index(s.startIndex, offsetBy: 2) ..<
@@ -228,6 +241,13 @@ SubstringTests.test("UTF8View") {
expectEqual("", String(t.dropLast(100))!)
expectEqual("", String(u.dropFirst(100))!)
expectEqual("", String(u.dropLast(100))!)
checkHasContiguousStorage(s.utf8)
checkHasContiguousStorage(t)
checkHasContiguousStorage(u)
checkMatchContiguousStorage(Array(s.utf8), s.utf8)
checkMatchContiguousStorage(Array(t), t)
checkMatchContiguousStorage(Array(u), u)
}
}