feat(core): Implement a typed map
This commit is contained in:
parent
9e0f38154e
commit
8270185027
13
packages/moxxmpp/lib/src/util/typed_map.dart
Normal file
13
packages/moxxmpp/lib/src/util/typed_map.dart
Normal 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?;
|
||||
}
|
25
packages/moxxmpp/test/type_map_test.dart
Normal file
25
packages/moxxmpp/test/type_map_test.dart
Normal 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);
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue
Block a user