2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "common_logic.h"
34 #include <am-moveable.h>
35 #include <am-refcounting.h>
36 #include <sm_stringhashmap.h>
37 #include "sm_memtable.h"
39 HandleType_t htCellTrie;
40 HandleType_t htSnapshot;
66 Entry(ke::Moveable<Entry> other)
68 control_ = other->control_;
78 void setCell(cell_t value) {
79 setType(EntryType_Cell);
82 void setArray(cell_t *cells, size_t length) {
83 ArrayInfo *array = ensureArray(length * sizeof(cell_t));
84 array->length = length;
85 memcpy(array->base(), cells, length * sizeof(cell_t));
86 setTypeAndPointer(EntryType_CellArray, array);
88 void setString(const char *str) {
89 size_t length = strlen(str);
90 ArrayInfo *array = ensureArray(length + 1);
91 array->length = length;
92 strcpy((char *)array->base(), str);
93 setTypeAndPointer(EntryType_String, array);
96 size_t arrayLength() const {
100 cell_t *array() const {
102 return reinterpret_cast<cell_t *>(raw()->base());
104 char *chars() const {
106 return reinterpret_cast<char *>(raw()->base());
108 cell_t cell() const {
113 bool isCell() const {
114 return type() == EntryType_Cell;
116 bool isArray() const {
117 return type() == EntryType_CellArray;
119 bool isString() const {
120 return type() == EntryType_String;
124 Entry(const Entry &other) KE_DELETE;
126 ArrayInfo *ensureArray(size_t bytes) {
127 ArrayInfo *array = raw();
128 if (array && array->maxbytes >= bytes)
130 array = (ArrayInfo *)realloc(array, bytes + sizeof(ArrayInfo));
133 fprintf(stderr, "Out of memory!\n");
136 array->maxbytes = bytes;
140 // Pointer and type are overlaid, so we have some accessors.
141 ArrayInfo *raw() const {
142 return reinterpret_cast<ArrayInfo *>(control_ & ~uintptr_t(0x3));
144 void setType(EntryType aType) {
145 control_ = uintptr_t(raw()) | uintptr_t(aType);
146 assert(type() == aType);
148 void setTypeAndPointer(EntryType aType, ArrayInfo *ptr) {
149 // malloc() should guarantee 8-byte alignment at worst
150 assert((uintptr_t(ptr) & 0x3) == 0);
151 control_ = uintptr_t(ptr) | uintptr_t(aType);
152 assert(type() == aType);
154 EntryType type() const {
155 return (EntryType)(control_ & 0x3);
159 // Contains the bits for the type, and an array pointer, if one is set.
162 // Contains data for cell-only entries.
166 struct CellTrie : public ke::Refcounted<CellTrie>
168 StringHashMap<Entry> map;
179 return length * sizeof(int) + strings.GetMemTable()->GetMemUsage();
183 ke::AutoArray<int> keys;
184 BaseStringTable strings;
188 public SMGlobalClass,
189 public IHandleTypeDispatch
191 public: //SMGlobalClass
192 void OnSourceModAllInitialized()
194 htCellTrie = handlesys->CreateType("Trie", this, 0, NULL, NULL, g_pCoreIdent, NULL);
195 htSnapshot = handlesys->CreateType("TrieSnapshot", this, 0, NULL, NULL, g_pCoreIdent, NULL);
197 void OnSourceModShutdown()
199 handlesys->RemoveType(htSnapshot, g_pCoreIdent);
200 handlesys->RemoveType(htCellTrie, g_pCoreIdent);
202 public: //IHandleTypeDispatch
203 void OnHandleDestroy(HandleType_t type, void *object)
205 if (type == htCellTrie)
207 CellTrie *pTrie = (CellTrie *)object;
210 TrieSnapshot *snapshot = (TrieSnapshot *)object;
214 bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
216 if (type == htCellTrie)
218 CellTrie *pArray = (CellTrie *)object;
219 *pSize = sizeof(CellTrie) + pArray->map.mem_usage();
221 TrieSnapshot *snapshot = (TrieSnapshot *)object;
222 *pSize = sizeof(TrieSnapshot) + snapshot->mem_usage();
228 static cell_t CreateTrie(IPluginContext *pContext, const cell_t *params)
230 CellTrie *pTrie = new CellTrie;
233 if ((hndl = handlesys->CreateHandle(htCellTrie, pTrie, pContext->GetIdentity(), g_pCoreIdent, NULL))
243 static cell_t SetTrieValue(IPluginContext *pContext, const cell_t *params)
247 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
249 Handle_t hndl = params[1];
251 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
254 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
258 pContext->LocalToString(params[2], &key);
260 StringHashMap<Entry>::Insert i = pTrie->map.findForAdd(key);
263 if (!pTrie->map.add(i, key))
265 i->value.setCell(params[3]);
272 i->value.setCell(params[3]);
276 static cell_t SetTrieArray(IPluginContext *pContext, const cell_t *params)
280 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
282 Handle_t hndl = params[1];
284 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
287 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
292 return pContext->ThrowNativeError("Invalid array size: %d", params[4]);
297 pContext->LocalToString(params[2], &key);
298 pContext->LocalToPhysAddr(params[3], &array);
300 StringHashMap<Entry>::Insert i = pTrie->map.findForAdd(key);
303 if (!pTrie->map.add(i, key))
306 i->value.setArray(array, params[4]);
313 i->value.setArray(array, params[4]);
317 static cell_t SetTrieString(IPluginContext *pContext, const cell_t *params)
321 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
323 Handle_t hndl = params[1];
325 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
328 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
332 pContext->LocalToString(params[2], &key);
333 pContext->LocalToString(params[3], &val);
335 StringHashMap<Entry>::Insert i = pTrie->map.findForAdd(key);
338 if (!pTrie->map.add(i, key))
340 i->value.setString(val);
347 i->value.setString(val);
351 static cell_t RemoveFromTrie(IPluginContext *pContext, const cell_t *params)
355 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
357 Handle_t hndl = params[1];
359 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
362 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
366 pContext->LocalToString(params[2], &key);
368 StringHashMap<Entry>::Result r = pTrie->map.find(key);
372 pTrie->map.remove(r);
376 static cell_t ClearTrie(IPluginContext *pContext, const cell_t *params)
381 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
385 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
388 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
395 static cell_t GetTrieValue(IPluginContext *pContext, const cell_t *params)
400 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
404 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
407 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
412 pContext->LocalToString(params[2], &key);
413 pContext->LocalToPhysAddr(params[3], &pValue);
415 StringHashMap<Entry>::Result r = pTrie->map.find(key);
419 if (r->value.isCell())
421 *pValue = r->value.cell();
425 // Maintain compatibility with an old bug. If an array was set with one
426 // cell, it was stored internally as a single cell. We now store as an
427 // actual array, but we make GetTrieValue() still work for this case.
428 if (r->value.isArray() && r->value.arrayLength() == 1)
430 *pValue = r->value.array()[0];
437 static cell_t GetTrieArray(IPluginContext *pContext, const cell_t *params)
442 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
446 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
449 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
454 return pContext->ThrowNativeError("Invalid array size: %d", params[4]);
458 cell_t *pValue, *pSize;
459 pContext->LocalToString(params[2], &key);
460 pContext->LocalToPhysAddr(params[3], &pValue);
461 pContext->LocalToPhysAddr(params[5], &pSize);
464 StringHashMap<Entry>::Result r = pTrie->map.find(key);
465 if (!r.found() || !r->value.isArray())
468 if (!r->value.array())
477 size_t length = r->value.arrayLength();
478 cell_t *base = r->value.array();
480 if (length > size_t(params[4]))
485 memcpy(pValue, base, sizeof(cell_t) * pSize[0]);
489 static cell_t GetTrieString(IPluginContext *pContext, const cell_t *params)
494 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
498 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
501 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
506 return pContext->ThrowNativeError("Invalid buffer size: %d", params[4]);
511 pContext->LocalToString(params[2], &key);
512 pContext->LocalToPhysAddr(params[5], &pSize);
514 StringHashMap<Entry>::Result r = pTrie->map.find(key);
515 if (!r.found() || !r->value.isString())
519 pContext->StringToLocalUTF8(params[3], params[4], r->value.chars(), &written);
521 *pSize = (cell_t)written;
525 static cell_t GetTrieSize(IPluginContext *pContext, const cell_t *params)
530 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
534 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
537 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
540 return pTrie->map.elements();
543 static cell_t CreateTrieSnapshot(IPluginContext *pContext, const cell_t *params)
546 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
548 Handle_t hndl = params[1];
551 if ((err = handlesys->ReadHandle(hndl, htCellTrie, &sec, (void **)&pTrie))
554 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
557 TrieSnapshot *snapshot = new TrieSnapshot;
558 snapshot->length = pTrie->map.elements();
559 snapshot->keys = new int[snapshot->length];
561 for (StringHashMap<Entry>::iterator iter = pTrie->map.iter(); !iter.empty(); iter.next(), i++)
562 snapshot->keys[i] = snapshot->strings.AddString(iter->key.chars(), iter->key.length());
563 assert(i == snapshot->length);
565 if ((hndl = handlesys->CreateHandle(htSnapshot, snapshot, pContext->GetIdentity(), g_pCoreIdent, NULL))
575 static cell_t TrieSnapshotLength(IPluginContext *pContext, const cell_t *params)
578 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
580 Handle_t hndl = params[1];
582 TrieSnapshot *snapshot;
583 if ((err = handlesys->ReadHandle(hndl, htSnapshot, &sec, (void **)&snapshot))
586 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
589 return snapshot->length;
592 static cell_t TrieSnapshotKeyBufferSize(IPluginContext *pContext, const cell_t *params)
595 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
597 Handle_t hndl = params[1];
599 TrieSnapshot *snapshot;
600 if ((err = handlesys->ReadHandle(hndl, htSnapshot, &sec, (void **)&snapshot))
603 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
606 unsigned index = params[2];
607 if (index >= snapshot->length)
608 return pContext->ThrowNativeError("Invalid index %d", index);
610 return strlen(snapshot->strings.GetString(snapshot->keys[index])) + 1;
613 static cell_t GetTrieSnapshotKey(IPluginContext *pContext, const cell_t *params)
616 HandleSecurity sec = HandleSecurity(pContext->GetIdentity(), g_pCoreIdent);
618 Handle_t hndl = params[1];
620 TrieSnapshot *snapshot;
621 if ((err = handlesys->ReadHandle(hndl, htSnapshot, &sec, (void **)&snapshot))
624 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
627 unsigned index = params[2];
628 if (index >= snapshot->length)
629 return pContext->ThrowNativeError("Invalid index %d", index);
632 const char *str = snapshot->strings.GetString(snapshot->keys[index]);
633 pContext->StringToLocalUTF8(params[3], params[4], str, &written);
637 REGISTER_NATIVES(trieNatives)
639 {"ClearTrie", ClearTrie},
640 {"CreateTrie", CreateTrie},
641 {"GetTrieArray", GetTrieArray},
642 {"GetTrieString", GetTrieString},
643 {"GetTrieValue", GetTrieValue},
644 {"RemoveFromTrie", RemoveFromTrie},
645 {"SetTrieArray", SetTrieArray},
646 {"SetTrieString", SetTrieString},
647 {"SetTrieValue", SetTrieValue},
648 {"GetTrieSize", GetTrieSize},
649 {"CreateTrieSnapshot", CreateTrieSnapshot},
650 {"TrieSnapshotLength", TrieSnapshotLength},
651 {"TrieSnapshotKeyBufferSize", TrieSnapshotKeyBufferSize},
652 {"GetTrieSnapshotKey", GetTrieSnapshotKey},