Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add inequality operator ( != ) for digest and DataProtocol comparison #180

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions Sources/Crypto/Digests/Digest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation

#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation

/// A protocol defining requirements for digests
public protocol Digest: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
Expand Down Expand Up @@ -52,7 +53,7 @@ extension Digest {
extension Digest {
public static func == (lhs: Self, rhs: Self) -> Bool {
return safeCompare(lhs, rhs)
}
}

public static func == <D: DataProtocol>(lhs: Self, rhs: D) -> Bool {
if rhs.regions.count != 1 {
Expand All @@ -62,9 +63,24 @@ extension Digest {
return safeCompare(lhs, rhs.regions.first!)
}
}

public var description: String {
return "\(Self.self): \(Array(self).hexString)"
}
}
#endif // Linux or !SwiftPM

extension Digest {

/// Determines whether a digest is not equal to a collection of contiguous bytes.
///
/// - Parameters:
/// - lhs: A digest to compare.
/// - rhs: A collection of contiguous bytes to compare.
///
/// - Returns: A Boolean value that’s `true` if the digest is not equal to the collection of binary data.
public static func != <D: DataProtocol>(lhs: Self, rhs: D) -> Bool {
return !(lhs == rhs)
}

}
7 changes: 7 additions & 0 deletions Tests/CryptoTests/Digests/DigestsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,11 @@ class DigestsTests: XCTestCase {
XCTAssertEqual(SHA384.blockByteCount, 128)
XCTAssertEqual(SHA512.blockByteCount, 128)
}

func testComparisonOperators() {
XCTAssertTrue(SHA256.hash(data: [1, 2, 3, 4]) == SHA256.hash(data: [1, 2, 3, 4]))
XCTAssertTrue(SHA256.hash(data: [1, 2, 3, 4]) != SHA256.hash(data: [5, 6, 7, 8]))
XCTAssertTrue(SHA256.hash(data: [1, 2, 3, 4]) == Data(SHA256.hash(data: [1, 2, 3, 4])))
XCTAssertTrue(SHA256.hash(data: [1, 2, 3, 4]) != Data(SHA256.hash(data: [5, 6, 7, 8])))
}
}