| 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 a hash code for [obj] such that structurally equivalent objects |
| 10 if (parents == null) { | 10 /// will have the same hash code. |
| 11 parents = []; | 11 /// |
| 12 } else if (parents.any((p) => identical(p, obj))) { | 12 /// This supports deep equality for maps and lists, including those with |
| 13 return -1; | 13 /// self-referential structures. |
| 14 int hashCodeFor(obj) { |
| 15 var parents = []; |
| 16 |
| 17 _hashCodeFor(value) { |
| 18 if (parents.any((parent) => identical(parent, value))) return -1; |
| 19 |
| 20 parents.add(value); |
| 21 try { |
| 22 if (value is Map) { |
| 23 return _hashCodeFor(value.keys) ^ _hashCodeFor(value.values); |
| 24 } else if (value is Iterable) { |
| 25 return const IterableEquality().hash(value.map(hashCodeFor)); |
| 26 } |
| 27 return value.hashCode; |
| 28 } finally { |
| 29 parents.removeLast(); |
| 30 } |
| 14 } | 31 } |
| 15 | 32 |
| 16 parents.add(obj); | 33 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 } | 34 } |
| 39 | |
| OLD | NEW |