From 82701850275a86743c02a9a82b8535affd84ff0b Mon Sep 17 00:00:00 2001 From: "Alexander \"PapaTutuWawa" Date: Sat, 3 Jun 2023 00:41:23 +0200 Subject: [PATCH] feat(core): Implement a typed map --- packages/moxxmpp/lib/src/util/typed_map.dart | 13 ++++++++++ packages/moxxmpp/test/type_map_test.dart | 25 ++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 packages/moxxmpp/lib/src/util/typed_map.dart create mode 100644 packages/moxxmpp/test/type_map_test.dart diff --git a/packages/moxxmpp/lib/src/util/typed_map.dart b/packages/moxxmpp/lib/src/util/typed_map.dart new file mode 100644 index 0000000..f06f4cf --- /dev/null +++ b/packages/moxxmpp/lib/src/util/typed_map.dart @@ -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 _data = {}; + + /// Associate the type of [value] with [value] in the map. + void set(T value) { + _data[T] = value; + } + + /// Return the object of type [T] from the map, if it has been stored. + T? get() => _data[T] as T?; +} diff --git a/packages/moxxmpp/test/type_map_test.dart b/packages/moxxmpp/test/type_map_test.dart new file mode 100644 index 0000000..651c0c2 --- /dev/null +++ b/packages/moxxmpp/test/type_map_test.dart @@ -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()?.i, 1); + expect(map.get()?.j, false); + }); +}