Skip to content

Instantly share code, notes, and snippets.

@tatumizer
Created March 4, 2015 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatumizer/89f721bd9878c6048c71 to your computer and use it in GitHub Desktop.
Save tatumizer/89f721bd9878c6048c71 to your computer and use it in GitHub Desktop.
var typeToNameSetMap=new Map<String,NameSet>();
class NameSet {
static const int MAX_ENTRIES=16;
var keys=new List(MAX_ENTRIES);
var hashCodes=new Int32List(MAX_ENTRIES);
var currentSize=0;
int getIndex(key) {
int hashCode=key.hashCode;
int index=-1;
for (int i=0, j=currentSize-1; j>=i; i++, j--) {
if (hashCodes[i]==hashCode) {index = i; break; }
if (hashCodes[j]==hashCode) {index = j; break; };
}
if (index>=0) {
return keys[index]==key ? index :-1;
} else if (currentSize<MAX_ENTRIES) {
keys[currentSize]=key;
hashCodes[currentSize]=hashCode;
return currentSize++;
} else {
return -1;
}
}
}
class TypedMap {
NameSet nameSet;
var values=new List(NameSet.MAX_ENTRIES);
var fallbackMap;
TypedMap(String type) { // "type" is a string that identifies named set
nameSet=typeToNameSetMap.putIfAbsent(type,()=>new NameSet());
}
operator [](key) {
if (fallbackMap!=null) {
return fallbackMap[key];
}
int index=nameSet.getIndex(key);
return index>=0 ? values[index] : null;
}
operator []=(key,value) {
if (fallbackMap!=null) {
fallbackMap[key]=value;
return;
}
int index=nameSet.getIndex(key);
if (index>=0) {
values[index]=value;
} else {
_createFallback();
fallbackMap[key]=value;
}
}
_createFallback() {
print ("creating fallback!");
fallbackMap=new Map();
for (int i=0; i<nameSet.currentSize; i++) {
fallbackMap[nameSet.keys[i]]=values[i];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment