feat: allow fibers as map keys by adding unique fiber IDs and hash support

Add a unique numeric ID to each fiber allocation, enabling fibers to be used as map keys. This includes updating the hash function for OBJ_FIBER to return the fiber's ID, modifying key validation to accept fibers, updating documentation to describe the new capability, and adjusting all relevant test expectations and error messages.
This commit is contained in:
Bob Nystrom
2015-05-03 18:10:31 +00:00
parent 332f570a1a
commit cd1cc07c6f
10 changed files with 60 additions and 20 deletions
+2 -2
View File
@@ -53,13 +53,13 @@ uint32_t validateIndexValue(WrenVM* vm, Value* args, uint32_t count,
bool validateKey(WrenVM* vm, Value* args, int index)
{
Value arg = args[index];
if (IS_BOOL(arg) || IS_CLASS(arg) || IS_NULL(arg) ||
if (IS_BOOL(arg) || IS_CLASS(arg) || IS_FIBER(arg) || IS_NULL(arg) ||
IS_NUM(arg) || IS_RANGE(arg) || IS_STRING(arg))
{
return true;
}
args[0] = CONST_STRING(vm, "Key must be a value type.");
args[0] = CONST_STRING(vm, "Key must be a value type or fiber.");
return false;
}
+4
View File
@@ -136,6 +136,7 @@ ObjFiber* wrenNewFiber(WrenVM* vm, Obj* fn)
{
ObjFiber* fiber = ALLOCATE(vm, ObjFiber);
initObj(vm, &fiber->obj, OBJ_FIBER, vm->fiberClass);
fiber->id = vm->nextFiberId++;
wrenResetFiber(fiber, fn);
@@ -322,6 +323,9 @@ static uint32_t hashObject(Obj* object)
// Classes just use their name.
return hashObject((Obj*)((ObjClass*)object)->name);
case OBJ_FIBER:
return ((ObjFiber*)object)->id;
case OBJ_RANGE:
{
ObjRange* range = (ObjRange*)object;
+6 -1
View File
@@ -133,7 +133,8 @@ typedef enum
typedef struct
{
ValueType type;
union {
union
{
double num;
Obj* obj;
} as;
@@ -226,6 +227,10 @@ typedef struct sObjFiber
// error message. Otherwise, it will be NULL.
ObjString* error;
// A unique-ish numeric ID for the fiber. Lets fibers be used as map keys.
// Unique-ish since IDs may overflow and wrap around.
uint16_t id;
// This will be true if the caller that called this fiber did so using "try".
// In that case, if this fiber fails with an error, the error will be given
// to the caller.
+5
View File
@@ -50,6 +50,11 @@ struct WrenVM
// for the module.
ObjMap* modules;
// The ID that will be assigned to the next fiber that is allocated. Fibers
// are given unique-ish (not completely unique since this can overflow) IDs
// so that they can be used as map keys.
uint16_t nextFiberId;
// Memory management data:
// The externally-provided function used to allocate memory.