Skip to content

Commit 84f9934

Browse files
Added conditional Equatable and Hashable conformance to Slice
1 parent 4692242 commit 84f9934

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

stdlib/public/core/Slice.swift

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,42 @@ extension Slice: MutableCollection where Base: MutableCollection {
260260
}
261261
}
262262

263+
extension Slice : Equatable where Base.Element : Equatable {
264+
public static func == (lhs: Slice<Base>, rhs: Slice<Base>) -> Bool {
265+
let lhsCount = lhs.count
266+
if lhsCount != rhs.count {
267+
return false
268+
}
269+
// We know that lhs.count == rhs.count, compare element wise.
270+
271+
for idx in 0..<lhsCount {
272+
let lidx = lhs._base.index(lhs._base.startIndex, offsetBy: idx)
273+
let ridx = rhs._base.index(rhs._base.startIndex, offsetBy: idx)
274+
if lhs[lidx] != rhs[ridx] {
275+
return false
276+
}
277+
}
278+
return true
279+
}
280+
}
281+
282+
extension Slice : Hashable where Base.Element : Hashable {
283+
/// The hash value for the slice.
284+
///
285+
/// Two slices that are equal will always have equal hash values.
286+
///
287+
/// Hash values are not guaranteed to be equal across different executions of
288+
/// your program. Do not save hash values to use during a future execution.
289+
@_inlineable // FIXME(sil-serialize-all)
290+
public var hashValue: Int {
291+
// FIXME(ABI)#177: <rdar://problem/18915294> Issue applies to DictionaryLiteral too
292+
var result: Int = 0
293+
for element in self {
294+
result = _combineHashValues(result, element.hashValue)
295+
}
296+
return result
297+
}
298+
}
263299

264300
extension Slice: RandomAccessCollection where Base: RandomAccessCollection { }
265301

0 commit comments

Comments
 (0)