Skip to content

Commit

Permalink
Merge pull request #347 from argentlabs/improve-ethereum-address-matc…
Browse files Browse the repository at this point in the history
…hing

Match against strings to improve performance
  • Loading branch information
DarthMike authored Dec 13, 2023
2 parents 4953e98 + 2eb6469 commit f996438
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions web3swift/src/Client/Models/EthereumAddress.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,21 @@ public struct EthereumAddress: Codable, Hashable {

private let raw: String
private let numberRepresentation: BigUInt?
private let numberRepresentationAsString: String?
public static let zero: Self = "0x0000000000000000000000000000000000000000"

public init(_ value: String) {
self.raw = value.lowercased()
self.numberRepresentation = BigUInt(hex: raw)
self.numberRepresentationAsString = self.numberRepresentation.map(String.init(describing:))
}

public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(String.self).lowercased()
self.raw = raw
self.numberRepresentation = BigUInt(hex: raw)
self.numberRepresentationAsString = self.numberRepresentation.map(String.init(describing:))
}

public func encode(to encoder: Encoder) throws {
Expand All @@ -33,19 +36,19 @@ public struct EthereumAddress: Codable, Hashable {
}

public func hash(into hasher: inout Hasher) {
if let number = asNumber() {
hasher.combine(number)
if let numberAsString = numberRepresentationAsString {
hasher.combine(numberAsString)
} else {
hasher.combine(asString())
}
}

public static func == (lhs: EthereumAddress, rhs: EthereumAddress) -> Bool {
guard let lhsInt = lhs.asNumber(), let rhsInt = rhs.asNumber() else {
guard let lhs = lhs.numberRepresentationAsString, let rhs = rhs.numberRepresentationAsString else {
return false
}
// Comparing Number representation avoids issues with lowercase and 0-padding
return lhsInt == rhsInt
return lhs == rhs
}
}

Expand Down

0 comments on commit f996438

Please sign in to comment.