Skip to content

Commit

Permalink
fix: use SplayTreeSet to resolve inconsistent hashCodes (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
devmil committed Aug 19, 2022
1 parent dfffe62 commit eb18291
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/src/equatable_utils.dart
@@ -1,3 +1,5 @@
import 'dart:collection';

import 'package:collection/collection.dart';
import 'package:equatable/equatable.dart';

Expand Down Expand Up @@ -46,6 +48,11 @@ int _combine(int hash, dynamic object) {
});
return hash;
}
if (object is Set && object is! SplayTreeSet) {
// this is needed to have a consistent iteration order so that the produced
// hash is consistent independently of the Set insertion order
object = SplayTreeSet<dynamic>.from(object);
}
if (object is Iterable) {
for (final value in object) {
hash = hash ^ _combine(hash, value);
Expand Down
11 changes: 11 additions & 0 deletions test/equatable_test.dart
Expand Up @@ -968,6 +968,17 @@ void main() {
expect(instanceA.hashCode == instanceB.hashCode, true);
});

test('should return when Set values are same but in different order', () {
final instanceA = SimpleEquatable<Set<String>>(
Set.from(<String>['A', 'B']),
);
final instanceB = SimpleEquatable<Set<String>>(
Set.from(<String>['B', 'A']),
);
expect(instanceA == instanceB, true);
expect(instanceA.hashCode == instanceB.hashCode, true);
});

test('should return when values are different', () {
final instanceA = SimpleEquatable<Set<String>>(
Set.from(<String>['A', 'B']),
Expand Down

0 comments on commit eb18291

Please sign in to comment.