Skip to content

Instantly share code, notes, and snippets.

@crazymonkyyy
Created April 1, 2023 14:02
Show Gist options
  • Save crazymonkyyy/b59569f665a4e7fc8948dfab906973f4 to your computer and use it in GitHub Desktop.
Save crazymonkyyy/b59569f665a4e7fc8948dfab906973f4 to your computer and use it in GitHub Desktop.
struct optassoarray(V, K) {
struct triple {
ulong index;
K key;
V value;
auto tuple(){
import std.typecons:t=tuple;
return t(index,key,value);
}
}
struct _pair {
V value;
K key;
}
_pair[] array;
triple opIndex(ulong index) {
return triple(index, array[index].key, array[index].value);
}
triple opIndex(K key) {
foreach (i, pair; array) {
if (pair.key == key) {
return triple(i, pair.key, pair.value);
}
}
return triple(-1, K.init, V.init);
}
ulong length() {
return array.length;
}
void opIndexAssign(V value, K key) {
foreach (i, pair; array) {
if (pair.key == key) {
array[i].value = value;
return;
}
}
array ~= _pair(value, key);
}
void opOpAssign(string s:"~")(V value){
array~=_pair(value,K.init);
}
auto torange(){
import std.range;
alias T=typeof(&this);
alias Iota=typeof(iota(0,ulong(10)));
struct range{
T parent;
Iota i;
triple front(){
return (*parent)[i.front];
}
void popFront(){
i.popFront;
}
bool empty(){
return i.empty;
}
}
return range(&this,iota(0,length));
}
}
unittest {
optassoarray!(int, string) foo;
foo ~= 1;
foo["foo"] = 2;
foo ~= 3;
assert(foo[0].value == 1);
assert(foo[0].key == string.init);
assert(foo[2].value == 3);
assert(foo[2].key == string.init);
assert(foo["foo"].index == 1);
assert(foo["foo"].value == 2);
import std;
foreach(index,key,value; foo.torange.map!(a=>a.tuple)) {
writeln(index,"(",key,"):",value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment