deepHashCode function

int deepHashCode(
  1. Object? obj
)

Returns a hash code for obj such that structurally equivalent objects will have the same hash code.

This supports deep equality for maps and lists, including those with self-referential structures, and returns the same hash code for YamlScalars and their values.

Implementation

int deepHashCode(Object? obj) {
  var parents = <Object?>[];

  int deepHashCodeInner(Object? value) {
    if (parents.any((parent) => identical(parent, value))) return -1;

    parents.add(value);
    try {
      if (value is Map) {
        var equality = const UnorderedIterableEquality<Object?>();
        return equality.hash(value.keys.map(deepHashCodeInner)) ^ equality.hash(value.values.map(deepHashCodeInner));
      } else if (value is Iterable) {
        return const IterableEquality<Object?>().hash(value.map(deepHashCode));
      } else if (value is YamlScalar) {
        return (value.value as Object?).hashCode;
      } else {
        return value.hashCode;
      }
    } finally {
      parents.removeLast();
    }
  }

  return deepHashCodeInner(obj);
}