OLD | NEW |
---|---|
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | 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 | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 library utils; | 5 library yaml.utils; |
6 | 6 |
7 /// Returns the hash code for [obj]. This includes null, true, false, maps, and | 7 import 'package:collection/collection.dart'; |
8 /// lists. Also handles self-referential structures. | 8 |
9 int hashCodeFor(obj, [List parents]) { | 9 /// Returns the hash code for [obj]. |
Bob Nystrom
2014/05/09 00:18:56
The intent behind this isn't clear. Why is this be
nweiz
2014/05/20 00:15:07
Done.
| |
10 if (parents == null) { | 10 /// |
11 parents = []; | 11 /// This supports deep equality for maps and lists, including those with |
12 } else if (parents.any((p) => identical(p, obj))) { | 12 /// self-referential structures. |
13 return -1; | 13 int hashCodeFor(obj) { |
14 var parents = []; | |
15 | |
16 _hashCodeFor(value) { | |
17 if (parents.any((parent) => identical(parent, value))) return -1; | |
18 | |
19 parents.add(value); | |
20 try { | |
21 if (value is Map) { | |
22 return _hashCodeFor(value.keys) ^ _hashCodeFor(value.values); | |
23 } else if (value is Iterable) { | |
24 return const IterableEquality().hash(value.map(hashCodeFor)); | |
25 } | |
26 return value.hashCode; | |
27 } finally { | |
28 parents.removeLast(); | |
29 } | |
14 } | 30 } |
15 | 31 |
16 parents.add(obj); | 32 return _hashCodeFor(obj); |
17 try { | |
18 if (obj == null) return 0; | |
19 if (obj == true) return 1; | |
20 if (obj == false) return 2; | |
21 if (obj is Map) { | |
22 return hashCodeFor(obj.keys, parents) ^ | |
23 hashCodeFor(obj.values, parents); | |
24 } | |
25 if (obj is Iterable) { | |
26 // This is probably a really bad hash function, but presumably we'll get | |
27 // this in the standard library before it actually matters. | |
28 int hash = 0; | |
29 for (var e in obj) { | |
30 hash ^= hashCodeFor(e, parents); | |
31 } | |
32 return hash; | |
33 } | |
34 return obj.hashCode; | |
35 } finally { | |
36 parents.removeLast(); | |
37 } | |
38 } | 33 } |
39 | |
OLD | NEW |