Skip to content

Commit c94082e

Browse files
committed
data identical
1 parent eb084da commit c94082e

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Sources/FoundationEssentials/Data/Data.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3020,3 +3020,52 @@ internal func _overrideLifetime<
30203020
) -> T {
30213021
dependent
30223022
}
3023+
3024+
extension Data {
3025+
/// Returns a boolean value indicating whether this data is identical to
3026+
/// `other`.
3027+
///
3028+
/// Two data values are identical if there is no way to distinguish between
3029+
/// them.
3030+
///
3031+
/// Comparing data this way includes comparing (normally) hidden
3032+
/// implementation details such as the memory location of any underlying
3033+
/// data storage object. Therefore, identical data are guaranteed to
3034+
/// compare equal with `==`, but not all equal data are considered
3035+
/// identical.
3036+
///
3037+
/// - Performance: O(1)
3038+
@_alwaysEmitIntoClient
3039+
public func isIdentical(to other: Self) -> Bool {
3040+
switch (self._representation, other._representation) {
3041+
case (.empty, .empty):
3042+
return true
3043+
case (.inline, .inline), (.slice, .slice), (.large, .large):
3044+
// Continue on to checks below
3045+
break
3046+
default:
3047+
return false
3048+
}
3049+
3050+
let length1 = self.count
3051+
let length2 = other.count
3052+
3053+
// Unequal length data can never be equal
3054+
guard length1 == length2 else {
3055+
return false
3056+
}
3057+
3058+
if length1 > 0 {
3059+
return self.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in
3060+
return other.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in
3061+
// If they have the same base address and same count, it is equal
3062+
let b1Address = b1.baseAddress!
3063+
let b2Address = b2.baseAddress!
3064+
3065+
return b1Address == b2Address
3066+
}
3067+
}
3068+
}
3069+
return true
3070+
}
3071+
}

0 commit comments

Comments
 (0)