/* Copyright (c) 2014 Alex Diener This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Alex Diener alex@ludobloom.com */ #include "utilities/Atom.h" #include "utilities/HashTable.h" #include #include struct AtomEntry { Atom atom; uint32_t hash; }; struct AtomBucket { size_t count; size_t allocatedSize; struct AtomEntry * entries; }; static HashTable * atomHashTable; static MUTEX_TYPE mutex; static void (* lockMutex)(MUTEX_TYPE); static void (* unlockMutex)(MUTEX_TYPE); void Atom_initMutex(MUTEX_TYPE (* createMutexFunc)(void), void (* lockMutexFunc)(MUTEX_TYPE), void (* unlockMutexFunc)(MUTEX_TYPE)) { if (mutex == NULL) { mutex = createMutexFunc(); lockMutex = lockMutexFunc; unlockMutex = unlockMutexFunc; } } Atom Atom_fromString(const char * string) { if (string == NULL) { return NULL; } if (mutex != NULL) { lockMutex(mutex); } HashTable_key key = HashTable_stringKey(string); if (atomHashTable == NULL) { atomHashTable = HashTable_create(sizeof(Atom)); } Atom * atomEntry = HashTable_get(atomHashTable, key); Atom atom; if (atomEntry == NULL) { atom = strdup(string); HashTable_set(atomHashTable, key, &atom); } else { atom = *atomEntry; } if (mutex != NULL) { unlockMutex(mutex); } return atom; } Atom Atom_getExisting(const char * string) { if (string == NULL || atomHashTable == NULL) { return NULL; } if (mutex != NULL) { lockMutex(mutex); } Atom * atomEntry = HashTable_get(atomHashTable, HashTable_stringKey(string)); Atom atom = NULL; if (atomEntry != NULL) { atom = *atomEntry; } if (mutex != NULL) { unlockMutex(mutex); } return atom; } void Atom_registerStaticAddress(const char * staticAtom) { if (atomHashTable == NULL) { atomHashTable = HashTable_create(sizeof(Atom)); } HashTable_key key = HashTable_stringKey(staticAtom); Atom * atomEntry = HashTable_get(atomHashTable, key); if (atomEntry != NULL) { #ifdef DEBUG fprintf(stderr, "ERROR: Atom_registerStaticAddress called with string \"%s\" at address %p, which is already registered at address %p\n", staticAtom, staticAtom, *atomEntry); #endif abort(); } HashTable_set(atomHashTable, key, &staticAtom); }