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

Use a private encoder to compare messages, if needed #21

Closed
wants to merge 2 commits into from
Closed
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
37 changes: 37 additions & 0 deletions Source/Message.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ public struct Message: Equatable {
self.metadata = metadata
self.jsonData = jsonData
}

/// Used to compare `jsonData` Strings.
private static let equalityJSONEncoder = JSONEncoder()
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be removed since it's unused.


extension Message {
Expand Down Expand Up @@ -94,3 +97,37 @@ extension Message {
}
}
}

extension Message {

/// Using `Equatable`'s default implementation is bound to give us false positives since two `Message`s may have semantically equal, but textually different, `jsonData`.
///
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since comparing messages is an implementation detail, I'd move this to its own extension file, Message+Equatable. This will also keep the Message interface clean.

/// For example, the following `jsonData` should be considered equal.
///
/// ```
/// lhs.jsonData = "{\"title\":\"Page-title\",\"subtitle\":\"Page-subtitle\",\"action_name\":\"go\"}")"
///
/// rhs.jsonData = "{\"action_name\":\"go\",\"title\":\"Page-title\",\"subtitle\":\"Page-subtitle\"}")"
/// ```
///
/// - Parameters:
/// - lhs: a message
/// - rhs: another message
/// - Returns: true if they're semantically equal
public static func == (lhs: Self, rhs: Self) -> Bool {

if lhs.jsonData != rhs.jsonData {
guard let lhsJSONData = lhs.jsonData.data(using: .utf8),
let rhsJSONData = rhs.jsonData.data(using: .utf8),
let lhsJSONObject = try? JSONSerialization.jsonObject(with: lhsJSONData, options: []) as? NSObject,
let rhsJSONObject = try? JSONSerialization.jsonObject(with: rhsJSONData, options: []) as? NSObject,
lhsJSONObject == rhsJSONObject
else { return false }
}

return lhs.id == rhs.id &&
lhs.component == rhs.component &&
lhs.event == rhs.event &&
lhs.metadata == rhs.metadata
}
}