Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(80)

Side by Side Diff: pkg/collection_helpers/lib/equality.dart

Issue 23567044: Add collection-helpers library. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Changing ~/ 2 to >> 1. Created 7 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 /**
6 * Defines equality relations on collections.
7 */
8 library dart.collection_helper.equality;
9
10 import "dart:collection";
11
12 const int _HASH_MASK = 0x7fffffff;
13
14 /**
15 * A generic equality relation on objects.
16 */
17 abstract class Equality<E> {
18 const factory Equality() = DefaultEquality;
19
20 /**
21 * Compare two elements for being equal.
22 *
23 * This should be a proper equality relation.
24 */
25 bool equals(E e1, E e2);
26
27 /**
28 * Get a hashcode of an element.
29 *
30 * The hashcode should be compatible with [equals], so that if
31 * `equals(a, b)` then `hash(a) == hash(b)`.
32 */
33 int hash(E e);
34
35 /**
36 * Test whether an object is a valid argument to [equals] and [hash].
37 *
38 * Some implementations may be restricted to only work on specific types
39 * of objects.
40 */
41 bool isValidKey(Object o);
42 }
43
44 /**
45 * Equality of objects that compares only the natural equality of the objects.
46 *
47 * This equality uses the objects' own [Object.==] and [Object.hashCode] for
48 * the equality.
49 */
50 class DefaultEquality implements Equality<Object> {
51 const DefaultEquality();
52 bool equals(Object e1, Object e2) => e1 == e2;
53 int hash(Object e) => e.hashCode;
54 bool isValidKey(Object o) => true;
55 }
56
57 /**
58 * Equality of objects that compares only the identity of the objects.
59 *
60 * This equality uses the objects' own [Object.hashCode] for the equality.
floitsch 2013/10/17 12:17:53 not true anymore. Looks like you switched to ident
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Good catch, removed.
61 * Any hashcode is compatible with identity, so there is no need for a
62 * custom hashcode computation.
63 */
64 class IdentityEquality implements Equality<Object> {
65 const IdentityEquality();
66 bool equals(Object e1, Object e2) => identical(e1, e2);
67 int hash(Object e) => identityHashCode(e);
68 bool isValidKey(Object o) => true;
69 }
70
71 /**
72 * Equality on iterables.
73 *
74 * Two iterables are equal if they have the same elements in the same order.
75 */
76 class IterableEquality<E> implements Equality<Iterable<E>> {
77 final Equality<E> _elementEquality;
78 const IterableEquality([Equality<E> elementEquality =
79 const DefaultEquality()])
floitsch 2013/10/17 12:17:53 weird indentation.
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Indented for from the start of "elementEquality".
80 : _elementEquality = elementEquality;
81
82 bool equals(Iterable<E> elements1, Iterable<E> elements2) {
83 if (identical(elements1, elements2)) return true;
84 if (elements1 == null || elements2 == null) return false;
85 Iterator it1 = elements1.iterator;
86 Iterator it2 = elements2.iterator;
87 while (true) {
88 bool hasNext = it1.moveNext();
89 if (hasNext != it2.moveNext()) return false;
90 if (!hasNext) return true;
91 if (!_elementEquality.equals(it1.current, it2.current)) return false;
92 }
93 }
94
95 int hash(Iterable<E> elements) {
96 // Jenkins's one-at-a-time hash function.
97 int hash = 0;
98 for (E element in elements) {
99 int c = _elementEquality.hash(element);
100 hash = (hash + c) & _HASH_MASK;
101 hash = (hash + (hash << 10)) & _HASH_MASK;
102 hash ^= (hash >> 6);
103 }
104 hash = (hash + (hash << 3)) & _HASH_MASK;
105 hash ^= (hash >> 11);
106 hash = (hash + (hash << 15)) & _HASH_MASK;
107 return hash;
108 }
109
110 bool isValidKey(Object o) => o is Iterable<E>;
111 }
112
113 /**
114 * Equality on lists.
115 *
116 * Two lists are equal if they have the same length and their elements
117 * at each index are equal.
118 *
119 * This is effectively the same as [IterableEquality] except that it
120 * accesses elements by index instead of through iteration.
121 */
122 class ListEquality<E> implements Equality<List<E>> {
123 final Equality<E> _elementEquality;
124 const ListEquality([Equality<E> elementEquality = const DefaultEquality()])
125 : _elementEquality = elementEquality;
126
127 bool equals(List<E> e1, List<E> e2) {
128 if (identical(e1, e2)) return true;
129 if (e1 == null || e2 == null) return false;
130 int length = e1.length;
131 if (length != e2.length) return false;
132 for (int i = 0; i < length; i++) {
133 if (!_elementEquality.equals(e1[i], e2[i])) return false;
134 }
135 return true;
136 }
137
138 int hash(List<E> e) {
139 // Jenkins's one-at-a-time hash function.
floitsch 2013/10/17 12:17:53 at least add a TODO that there is duplicated code.
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Added a comment.
140 int hash = 0;
141 for (int i = 0; i < e.length; i++) {
142 int c = _elementEquality.hash(e[i]);
143 hash = (hash + c) & _HASH_MASK;
144 hash = (hash + (hash << 10)) & _HASH_MASK;
145 hash ^= (hash >> 6);
146 }
147 hash = (hash + (hash << 3)) & _HASH_MASK;
148 hash ^= (hash >> 11);
149 hash = (hash + (hash << 15)) & _HASH_MASK;
150 return hash;
151 }
152
153 bool isValidKey(Object o) => o is List<E>;
154 }
155
156 /**
157 * Equality of the elements of two iterables without considering order.
158 *
159 * Two iterables are considered equal if they have the same number of elements,
160 * and the elements of one set can be paired with the elements
floitsch 2013/10/17 12:17:53 no sets here.
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Done.
161 * of the other set, so that each pair are equal.
162 */
163 class UnorderedIterableEquality<E> implements Equality<Iterable<E>> {
164 final Equality<E> _elementEquality;
165
166 const UnorderedIterableEquality(
167 [Equality<E> elementEquality = const DefaultEquality()])
168 : _elementEquality = elementEquality;
169
170 bool equals(Iterable<E> e1, Iterable<E> e2) {
171 if (identical(e1, e2)) return true;
172 if (e1 == null || e2 == null) return false;
173 HashMap<E, int> counts = new HashMap(
174 equals: _elementEquality.equals,
175 hashCode: _elementEquality.hash,
176 isValidKey: _elementEquality.isValidKey);
177 int length = 0;
178 for (E e in e1) {
179 int count = counts[e];
180 if (count == null) count = 0;
181 counts[e] = count + 1;
182 length++;
183 }
184 for (E e in e2) {
185 int count = counts[e];
186 if (count == null || count == 0) return false;
187 counts[e] = count - 1;
188 length--;
189 }
190 return length == 0;
191 }
192
193 int hash(Iterable<E> e) {
194 int hash = 0;
195 for (E element in e) {
196 int c = _elementEquality.hash(element);
197 hash = (hash + c) & _HASH_MASK;
198 }
199 hash = (hash + (hash << 3)) & _HASH_MASK;
200 hash ^= (hash >> 11);
201 hash = (hash + (hash << 15)) & _HASH_MASK;
202 return hash;
203 }
204
205 bool isValidKey(Object o) => o is Iterable<E>;
206 }
207
208 /**
209 * Equality of sets.
210 *
211 * Two sets are considered equal if they have the same number of elements,
212 * and the elements of one set can be paired with the elements
213 * of the other set, so that each pair are equal.
214 *
215 * This equality behaves the same as [UnorderedIterableEquality] except that
216 * it expects sets instead of iterables as arguments.
217 */
218 class SetEquality<E> extends UnorderedIterableEquality<E>
219 implements Equality<Set<E>> {
220 const SetEquality(
221 [Equality<E> elementEquality = const DefaultEquality()])
222 : super(elementEquality);
223
224 bool equals(Set<E> e1, Set<E> e2) => super.equals(e1, e2);
225
226 int hash(Set<E> e) => super.hash(e);
227
228 bool isValidKey(Object o) => o is Set<E>;
229 }
230
231 /**
232 * Internal class used by [MapEquality].
233 *
234 * The class represents a map entry as a single object,
235 * using a combined hashCode and equality of the key and value.
236 */
237 class _MapEntry {
238 final MapEquality equality;
239 final key;
240 final value;
241 _MapEntry(this.equality, this.key, this.value);
242
243 int get hashCode =>
244 (3 * equality._keyEquality.hash(key) +
245 7 * equality._valueEquality.hash(value)) & _HASH_MASK;
246
247 bool operator==(Object other) {
248 if (other is! _MapEntry) return false;
249 _MapEntry otherEntry = other;
250 return equality._keyEquality.equals(key, otherEntry.key) &&
251 equality._valueEquality.equals(value, otherEntry.value);
252
253 }
254 }
255
256 /**
257 * Equality on maps.
258 *
259 * Two maps are equal if they have the same number of entries, and if the
260 * entries of the two maps are pairwise equal on both key and value.
261 */
262 class MapEquality<K, V> implements Equality<Map<K, V>> {
263 final Equality<K> _keyEquality;
264 final Equality<V> _valueEquality;
265 const MapEquality({ Equality<K> keys : const DefaultEquality(),
266 Equality<K> values : const DefaultEquality() })
267 : _keyEquality = keys, _valueEquality = values;
268 bool equals(Map<K, V> e1, Map<K, V> e2) {
floitsch 2013/10/17 12:17:53 new line before.
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Done.
269 if (identical(e1, e2)) return true;
270 if (e1 == null || e2 == null) return false;
271 int length = e1.length;
272 if (length != e2.length) return false;
273 Map<_MapEntry, int> counts = new HashMap();
floitsch 2013/10/17 12:17:53 Add comment or rename variable.
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Done.
274 for (K key in e1.keys) {
275 _MapEntry entry = new _MapEntry(this, key, e1[key]);
276 int count = counts[entry];
277 if (count == null) count = 0;
278 counts[entry] = count + 1;
279 }
280 for (K key in e2.keys) {
281 _MapEntry entry = new _MapEntry(this, key, e2[key]);
282 int count = counts[entry];
283 if (count == null || count == 0) return false;
284 counts[entry] = count - 1;
285 }
286 return true;
287 }
288
289 int hash(Map<K, V> map) {
290 int hash = 0;
291 for (K key in map.keys) {
292 int keyHash = _keyEquality.hash(key);
293 int valueHash = _valueEquality.hash(map[key]);
294 hash = (hash + 3 * keyHash + 7 * valueHash) & _HASH_MASK;
295 }
296 hash = (hash + (hash << 3)) & _HASH_MASK;
297 hash ^= (hash >> 11);
298 hash = (hash + (hash << 15)) & _HASH_MASK;
299 return hash;
300 }
301
302 bool isValidKey(Object o) => o is Map<K, V>;
303 }
304
305 /**
306 * Combines several equalities into a single equality.
307 *
308 * Tries each equality in order, using [Equality.isValidKey], and returns
309 * the result of the first equality that applies to the argument or arguments.
310 *
311 * For `equals`, the first equality that maches the first argument is used,
floitsch 2013/10/17 12:17:53 matches
Lasse Reichstein Nielsen 2013/10/23 11:42:40 Done.
312 * and if the second argument of `equals` is not valid for that equality,
313 * it returns false.
314 *
315 * The equalities should generally work on disjoint types, otherwise it may
floitsch 2013/10/17 12:17:53 not clear. I guess it refers to line 327 where we
Lasse Reichstein Nielsen 2013/10/23 11:42:40 reworded.
316 * give inconsistent results for `equals(e1, e2)` and `equals(e2, e1)` if an
317 * equality allows `e1` and not `e2`, but another allows both.
318 */
319 class MultiEquality<E> implements Equality<E> {
320 final Iterable<Equality<E>> _equalities;
321
322 const MultiEquality(Iterable<Equality<E>> equalities)
323 : _equalities = equalities;
324
325 bool equals(E e1, E e2) {
326 for (Equality<E> eq in _equalities) {
327 if (eq.isValidKey(e1)) return eq.isValidKey(e2) && eq.equals(e1, e2);
328 }
329 return false;
330 }
331
332 int hash(E e) {
333 for (Equality<E> eq in _equalities) {
334 if (eq.isValidKey(e)) return eq.hash(e);
335 }
336 return -1;
337 }
338
339 bool isValidKey(Object o) {
340 for (Equality<E> eq in _equalities) {
341 if (eq.isValidKey(o)) return true;
342 }
343 return false;
344 }
345 }
346
347 /**
348 * Deep equality on collections.
349 *
350 * Recognizes lists, sets, iterables and maps and compares their elements using
351 * deep equality as well.
352 *
353 * Non-iterable/map objects are compared using a configurable base equality.
354 *
355 * Works in one of two modes: ordered or unordered.
356 *
357 * In ordered mode, lists and iterables are required to have equal elements
358 * in the same order. In unordered mode, the order of elements in iterables
359 * and lists are not importan.
360 *
361 * A list is only equal to another list, likewise for sets and maps. All other
362 * iterables are compared as iterables only.
363 */
364 class DeepCollectionEquality implements Equality {
365 final Equality _base;
366 final bool _unordered;
367 const DeepCollectionEquality([Equality base = const DefaultEquality()])
368 : _base = base, _unordered = false;
369
370 /**
371 * Creates a deep equality on collections where the order of lists and
372 * iterables are not considered important. That is, lists and iterables are
373 * treated as unordered iterables.
374 */
375 const DeepCollectionEquality.unordered(
376 [Equality base = const DefaultEquality()])
377 : _base = base, _unordered = true;
378
379 bool equals(e1, e2) {
380 if (e1 is Set) {
381 if (e2 is! Set) return false;
382 return new SetEquality(this).equals(e1, e2);
383 }
384 if (e1 is Map) {
385 if (e2 is! Map) return false;
386 return new MapEquality(keys: this, values: this).equals(e1, e2);
387 }
388 if (!_unordered) {
389 if (e1 is List) {
390 if (e2 is! List) return false;
391 return new ListEquality(this).equals(e1, e2);
392 }
393 if (e1 is Iterable) {
394 if (e2 is! Iterable) return false;
395 return new IterableEquality(this).equals(e1, e2);
396 }
397 } else if (e1 is Iterable) {
398 if (e2 is! Iterable) return false;
399 if (e1 is List != e2 is List) return false;
400 return new UnorderedIterableEquality(this).equals(e1, e2);
401 }
402 return _base.equals(e1, e2);
403 }
404
405 int hash(Object o) {
406 if (o is Set) return new SetEquality(this).hash(o);
407 if (o is Map) return new MapEquality(keys: this, values: this).hash(o);
408 if (!_unordered) {
409 if (o is List) return new ListEquality(this).hash(o);
410 if (o is Iterable) return new IterableEquality(this).hash(o);
411 } else if (o is Iterable) {
412 return new UnorderedIterableEquality(this).hash(o);
413 }
414 return _base.hash(o);
415 }
416
417 bool isValidKey(Object o) => o is Iterable || o is Map || _base.isValidKey(o);
418 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698