Skip to content
This repository was archived by the owner on Feb 10, 2025. It is now read-only.

Commit 5137026

Browse files
authored
Preserve parsed key order in maps (#57)
Preserve key order in YamlMap when parsing YAML.
1 parent 4d016bc commit 5137026

File tree

4 files changed

+37
-2
lines changed

4 files changed

+37
-2
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
## 2.2.0
2+
3+
* POSSIBLY BREAKING CHANGE: Make `YamlMap` preserve parsed key order.
4+
This is breaking because some programs may rely on the
5+
`HashMap` sort order.
6+
17
## 2.1.16
28

39
* Fixed deprecated API usage in README.

lib/src/equality.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import 'yaml_node.dart';
1010

1111
/// Returns a [Map] that compares its keys based on [deepEquals].
1212
Map<K, V> deepEqualsMap<K, V>() =>
13-
HashMap(equals: deepEquals, hashCode: deepHashCode);
13+
LinkedHashMap(equals: deepEquals, hashCode: deepHashCode);
1414

1515
/// Returns whether two objects are structurally equivalent.
1616
///

pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
name: yaml
2-
version: 2.1.16
2+
version: 2.2.0
33

44
description: A parser for YAML, a human-friendly data serialization standard
55
author: Dart Team <misc@dartlang.org>

test/yaml_test.dart

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1806,4 +1806,33 @@ main() {
18061806
Also floats: [ .inf, -.Inf, +.INF, .NAN ]''');
18071807
});
18081808
});
1809+
1810+
test('preserves key order', () {
1811+
const keys = ['a', 'b', 'c', 'd', 'e', 'f'];
1812+
int sanityCheckCount = 0;
1813+
for (List<String> permutation in _generatePermutations(keys)) {
1814+
final yaml = permutation.map((key) => '$key: value').join('\n');
1815+
expect(loadYaml(yaml).keys.toList(), permutation);
1816+
sanityCheckCount++;
1817+
}
1818+
final expectedPermutationCount =
1819+
List.generate(keys.length, (i) => i + 1).reduce((n, i) => n * i);
1820+
expect(sanityCheckCount, expectedPermutationCount);
1821+
});
1822+
}
1823+
1824+
Iterable<List<String>> _generatePermutations(List<String> keys) sync* {
1825+
if (keys.length <= 1) {
1826+
yield keys;
1827+
return;
1828+
}
1829+
for (int i = 0; i < keys.length; i++) {
1830+
final first = keys[i];
1831+
final rest = <String>[]
1832+
..addAll(keys.sublist(0, i))
1833+
..addAll(keys.sublist(i + 1));
1834+
for (List<String> subPermutation in _generatePermutations(rest)) {
1835+
yield <String>[first]..addAll(subPermutation);
1836+
}
1837+
}
18091838
}

0 commit comments

Comments
 (0)