feat(core): Implement a typed map

This commit is contained in:
PapaTutuWawa 2023-06-03 00:41:23 +02:00
parent 9e0f38154e
commit 8270185027
2 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,13 @@
/// A map, similar to Map, but always uses the type of the value as the key.
class TypedMap {
/// The internal mapping of type -> data
final Map<Object, Object> _data = {};
/// Associate the type of [value] with [value] in the map.
void set<T extends Object>(T value) {
_data[T] = value;
}
/// Return the object of type [T] from the map, if it has been stored.
T? get<T>() => _data[T] as T?;
}

View File

@ -0,0 +1,25 @@
import 'package:moxxmpp/src/util/typed_map.dart';
import 'package:test/test.dart';
class TestType1 {
const TestType1(this.i);
final int i;
}
class TestType2 {
const TestType2(this.j);
final bool j;
}
void main() {
test('Test storing data in the type map', () {
// Set
final map = TypedMap()
..set(const TestType1(1))
..set(const TestType2(false));
// And access
expect(map.get<TestType1>()?.i, 1);
expect(map.get<TestType2>()?.j, false);
});
}