-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
62 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
module re.util.jar; | ||
|
||
import std.array; | ||
import std.typecons; | ||
|
||
/// a container for registered types | ||
class Jar { | ||
private Object[][TypeInfo] _instance_registry; | ||
|
||
/// register a type instance | ||
public T register(T)(T instance) { | ||
auto type = typeid(instance); | ||
if (type !in _instance_registry) { | ||
_instance_registry[type] = new Object[0]; | ||
} | ||
_instance_registry[type] ~= instance; | ||
return instance; | ||
} | ||
|
||
/// resolve all matching type instances | ||
public T[] resolve_all(T)() { | ||
auto type = typeid(T); | ||
if (type in _instance_registry) { | ||
Appender!(T[]) resolved; | ||
foreach (item; _instance_registry[type]) { | ||
resolved ~= cast(T) item; | ||
} | ||
return resolved.data; | ||
} | ||
return new T[0]; | ||
} | ||
|
||
/// resolve first matching type instance | ||
public Nullable!T resolve(T)() { | ||
auto items = resolve_all!T(); | ||
if (items.length > 0) { | ||
return Nullable!T(items[0]); | ||
} | ||
return Nullable!T.init; | ||
} | ||
} | ||
|
||
unittest { | ||
class Cookie { | ||
bool delicious = true; | ||
} | ||
|
||
auto jar = new Jar(); | ||
|
||
auto c1 = new Cookie(); | ||
jar.register(c1); | ||
auto r1 = jar.resolve!Cookie(); | ||
assert(!r1.isNull, "resolved item was null"); | ||
assert(r1.get() == c1, "resolved item did not match"); | ||
|
||
auto c2 = new Cookie(); | ||
jar.register(c2); | ||
|
||
const auto cookies = jar.resolve_all!Cookie(); | ||
assert(cookies.length == 2, "mismatch in number of registered items"); | ||
} |