Skip to content

Commit ac34db0

Browse files
committed
Added generic MapDecoder.
1 parent c064f9b commit ac34db0

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed
Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
part of '../reader.dart';
22

3-
class ListDecoder<T> extends Decoder<List<T>> {
3+
class ListDecoder<E> extends Decoder<List<E>> {
44
const ListDecoder();
55

66
@override
7-
List<T> read(DartObject obj) =>
8-
switch (obj.toListValue()?.map((item) => item.read<T>())) {
9-
Iterable<T> iterable => iterable.toList(),
7+
List<E> read(DartObject obj) =>
8+
switch (obj.toListValue()?.map((item) => item.read<E>())) {
9+
Iterable<E> iterable => iterable.toList(),
1010
_ => throw readError(obj),
1111
};
1212
}
1313

1414
class SetDecoder<T> extends Decoder<Set<T>> {
15-
const SetDecoder({this.prototype = const {}});
16-
final Set<T> prototype;
15+
const SetDecoder();
1716

1817
@override
1918
Set<T> read(DartObject obj) =>
@@ -24,8 +23,7 @@ class SetDecoder<T> extends Decoder<Set<T>> {
2423
}
2524

2625
class IterableDecoder<T> extends Decoder<Iterable<T>> {
27-
const IterableDecoder({this.prototype = const {}});
28-
final Set<T> prototype;
26+
const IterableDecoder();
2927

3028
@override
3129
Set<T> read(DartObject obj) =>
@@ -34,3 +32,27 @@ class IterableDecoder<T> extends Decoder<Iterable<T>> {
3432
_ => throw readError(obj),
3533
};
3634
}
35+
36+
class MapDecoder<K, V> extends Decoder<Map<K, V>> {
37+
const MapDecoder();
38+
@override
39+
Map<K, V> read(DartObject obj) {
40+
final result = <K, V>{};
41+
42+
final mapObj = obj.toMapValue();
43+
if (mapObj == null) {
44+
throw readError(obj);
45+
} else {
46+
mapObj.forEach((keyObj, valueObj) {
47+
final key = keyObj?.read<K>();
48+
final value = valueObj?.read<V>();
49+
50+
if (key is K && value is V) {
51+
//TODO will this test ever fail? Should this method throw?
52+
result[key] = value;
53+
}
54+
});
55+
return result;
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)