Created
November 17, 2015 02:02
-
-
Save atg/9813e93d7fe8b06b910f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#import "util.hpp" | |
namespace SH { | |
// A symbol represents a component of a scope e.g. "js" or "string" | |
// Symbols are stored in the SymbolRegistry in an array | |
// Components can never be removed, they last the life of the process. | |
using Symbol = uint32_t; | |
struct SymbolRecord { | |
Symbol key; | |
Str value; | |
SymbolRecord(Symbol key, Str value) : key(key), value(value) { } | |
}; | |
struct SymbolRegistry { | |
public: | |
using ReverseMapType = HashMap<Str, SymbolRecord*>; | |
using RecordsType = Arr<SymbolRecord*>; | |
static SymbolRegistry& shared() { | |
static SymbolRegistry _shared; | |
return _shared; | |
} | |
const RecordsType& getRecords() const { return records; }; | |
const ReverseMapType& getReverseMap() const { return reverseMap; }; | |
// This function is slow | |
Symbol addSymbol(const Str& str) { | |
const auto& it = reverseMap.find(str); | |
if (it != reverseMap.end()) | |
return it->second->key; | |
Symbol key = records.size(); | |
auto* record = new SymbolRecord(key, str); | |
records.push_back(record); | |
reverseMap[str] = record; | |
return key; | |
} | |
// Look up a symbol and return a temporary string for immediate consumption | |
const Str& lookupTemp(Symbol sym) { | |
return records[sym]->value; | |
} | |
const char* lookupTempCstr(Symbol sym) { | |
return records[sym]->value.c_str(); | |
} | |
// Look up a symbol and return an owned string | |
Str lookupOwned(Symbol sym) { | |
return records[sym]->value; | |
} | |
private: | |
SymbolRegistry() { } | |
RecordsType records; | |
ReverseMapType reverseMap; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment