Skip to content

Commit 2e13c96

Browse files
committed
Ensure hashes of ranges are uniform to the expected hash for Data
1 parent 59ace60 commit 2e13c96

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

stdlib/public/SDK/Foundation/Data.swift

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -910,18 +910,6 @@ public final class _DataStorage {
910910
}
911911
}
912912

913-
public var hashValue: Int {
914-
switch _backing {
915-
case .customReference(let d):
916-
return d.hash
917-
case .customMutableReference(let d):
918-
return d.hash
919-
default:
920-
let len = _length
921-
return Int(bitPattern: CFHashBytes(_bytes?.assumingMemoryBound(to: UInt8.self).advanced(by: -_offset), Swift.min(len, 80)))
922-
}
923-
}
924-
925913
public func subdata(in range: Range<Data.Index>) -> Data {
926914
switch _backing {
927915
case .customReference(let d):
@@ -1625,7 +1613,15 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
16251613

16261614
/// The hash value for the data.
16271615
public var hashValue: Int {
1628-
return _backing.hashValue
1616+
var hashValue = 0
1617+
let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound)
1618+
_withStackOrHeapBuffer(hashRange.count) { buffer in
1619+
_backing.withUnsafeBytes(in: hashRange) {
1620+
memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count)
1621+
}
1622+
hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count))
1623+
}
1624+
return hashValue
16291625
}
16301626

16311627
@inline(__always)
@@ -1842,7 +1838,8 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
18421838
extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
18431839
/// A human-readable description for the data.
18441840
public var description: String {
1845-
return "\(self.count) bytes"
1841+
// return "\(self.count) bytes"
1842+
return "Data(bytes: [" + map { "0x\(String($0, radix: 16))" }.joined(separator: ", ") + "])"
18461843
}
18471844

18481845
/// A human-readable debug description for the data.

0 commit comments

Comments
 (0)