Path: blob/main/sys/contrib/openzfs/module/lua/ltable.c
48383 views
// SPDX-License-Identifier: MIT1/*2** $Id: ltable.c,v 2.72.1.1 2013/04/12 18:48:47 roberto Exp $3** Lua tables (hash)4** See Copyright Notice in lua.h5*/678/*9** Implementation of tables (aka arrays, objects, or hash tables).10** Tables keep its elements in two parts: an array part and a hash part.11** Non-negative integer keys are all candidates to be kept in the array12** part. The actual size of the array is the largest `n' such that at13** least half the slots between 0 and n are in use.14** Hash uses a mix of chained scatter table with Brent's variation.15** A main invariant of these tables is that, if an element is not16** in its main position (i.e. the `original' position that its hash gives17** to it), then the colliding element is in its own main position.18** Hence even when the load factor reaches 100%, performance remains good.19*/202122#define ltable_c23#define LUA_CORE2425#include <sys/lua/lua.h>2627#include "ldebug.h"28#include "ldo.h"29#include "lgc.h"30#include "lmem.h"31#include "lobject.h"32#include "lstate.h"33#include "lstring.h"34#include "ltable.h"35#include "lvm.h"363738/*39** max size of array part is 2^MAXBITS40*/41#if LUAI_BITSINT >= 3242#define MAXBITS 3043#else44#define MAXBITS (LUAI_BITSINT-2)45#endif4647#define MAXASIZE (1 << MAXBITS)484950#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))5152#define hashstr(t,str) hashpow2(t, (str)->tsv.hash)53#define hashboolean(t,p) hashpow2(t, p)545556/*57** for some types, it is better to avoid modulus by power of 2, as58** they tend to have many 2 factors.59*/60#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))616263#define hashpointer(t,p) hashmod(t, IntPoint(p))646566#define dummynode (&dummynode_)6768#define isdummy(n) ((n) == dummynode)6970static const Node dummynode_ = {71{NILCONSTANT}, /* value */72{{NILCONSTANT, NULL}} /* key */73};747576/*77** hash for lua_Numbers78*/79static Node *hashnum (const Table *t, lua_Number n) {80int i;81luai_hashnum(i, n);82if (i < 0) {83if (cast(unsigned int, i) == 0u - i) /* use unsigned to avoid overflows */84i = 0; /* handle INT_MIN */85i = -i; /* must be a positive value */86}87return hashmod(t, i);88}89909192/*93** returns the `main' position of an element in a table (that is, the index94** of its hash value)95*/96static Node *mainposition (const Table *t, const TValue *key) {97switch (ttype(key)) {98case LUA_TNUMBER:99return hashnum(t, nvalue(key));100case LUA_TLNGSTR: {101TString *s = rawtsvalue(key);102if (s->tsv.extra == 0) { /* no hash? */103s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash);104s->tsv.extra = 1; /* now it has its hash */105}106return hashstr(t, rawtsvalue(key));107}108case LUA_TSHRSTR:109return hashstr(t, rawtsvalue(key));110case LUA_TBOOLEAN:111return hashboolean(t, bvalue(key));112case LUA_TLIGHTUSERDATA:113return hashpointer(t, pvalue(key));114case LUA_TLCF:115return hashpointer(t, fvalue(key));116default:117return hashpointer(t, gcvalue(key));118}119}120121122/*123** returns the index for `key' if `key' is an appropriate key to live in124** the array part of the table, -1 otherwise.125*/126static int arrayindex (const TValue *key) {127if (ttisnumber(key)) {128lua_Number n = nvalue(key);129int k;130lua_number2int(k, n);131if (luai_numeq(cast_num(k), n))132return k;133}134return -1; /* `key' did not match some condition */135}136137138/*139** returns the index of a `key' for table traversals. First goes all140** elements in the array part, then elements in the hash part. The141** beginning of a traversal is signaled by -1.142*/143static int findindex (lua_State *L, Table *t, StkId key) {144int i;145if (ttisnil(key)) return -1; /* first iteration */146i = arrayindex(key);147if (0 < i && i <= t->sizearray) /* is `key' inside array part? */148return i-1; /* yes; that's the index (corrected to C) */149else {150Node *n = mainposition(t, key);151for (;;) { /* check whether `key' is somewhere in the chain */152/* key may be dead already, but it is ok to use it in `next' */153if (luaV_rawequalobj(gkey(n), key) ||154(ttisdeadkey(gkey(n)) && iscollectable(key) &&155deadvalue(gkey(n)) == gcvalue(key))) {156i = cast_int(n - gnode(t, 0)); /* key index in hash table */157/* hash elements are numbered after array ones */158return i + t->sizearray;159}160else n = gnext(n);161if (n == NULL)162luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */163}164}165}166167168int luaH_next (lua_State *L, Table *t, StkId key) {169int i = findindex(L, t, key); /* find original element */170for (i++; i < t->sizearray; i++) { /* try first array part */171if (!ttisnil(&t->array[i])) { /* a non-nil value? */172setnvalue(key, cast_num(i+1));173setobj2s(L, key+1, &t->array[i]);174return 1;175}176}177for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */178if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */179setobj2s(L, key, gkey(gnode(t, i)));180setobj2s(L, key+1, gval(gnode(t, i)));181return 1;182}183}184return 0; /* no more elements */185}186187188/*189** {=============================================================190** Rehash191** ==============================================================192*/193194195static int computesizes (int nums[], int *narray) {196int i;197int twotoi; /* 2^i */198int a = 0; /* number of elements smaller than 2^i */199int na = 0; /* number of elements to go to array part */200int n = 0; /* optimal size for array part */201for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {202if (nums[i] > 0) {203a += nums[i];204if (a > twotoi/2) { /* more than half elements present? */205n = twotoi; /* optimal size (till now) */206na = a; /* all elements smaller than n will go to array part */207}208}209if (a == *narray) break; /* all elements already counted */210}211*narray = n;212lua_assert(*narray/2 <= na && na <= *narray);213return na;214}215216217static int countint (const TValue *key, int *nums) {218int k = arrayindex(key);219if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */220nums[luaO_ceillog2(k)]++; /* count as such */221return 1;222}223else224return 0;225}226227228static int numusearray (const Table *t, int *nums) {229int lg;230int ttlg; /* 2^lg */231int ause = 0; /* summation of `nums' */232int i = 1; /* count to traverse all array keys */233for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */234int lc = 0; /* counter */235int lim = ttlg;236if (lim > t->sizearray) {237lim = t->sizearray; /* adjust upper limit */238if (i > lim)239break; /* no more elements to count */240}241/* count elements in range (2^(lg-1), 2^lg] */242for (; i <= lim; i++) {243if (!ttisnil(&t->array[i-1]))244lc++;245}246nums[lg] += lc;247ause += lc;248}249return ause;250}251252253static int numusehash (const Table *t, int *nums, int *pnasize) {254int totaluse = 0; /* total number of elements */255int ause = 0; /* summation of `nums' */256int i = sizenode(t);257while (i--) {258Node *n = &t->node[i];259if (!ttisnil(gval(n))) {260ause += countint(gkey(n), nums);261totaluse++;262}263}264*pnasize += ause;265return totaluse;266}267268269static void setarrayvector (lua_State *L, Table *t, int size) {270int i;271luaM_reallocvector(L, t->array, t->sizearray, size, TValue);272for (i=t->sizearray; i<size; i++)273setnilvalue(&t->array[i]);274t->sizearray = size;275}276277278static void setnodevector (lua_State *L, Table *t, int size) {279int lsize;280if (size == 0) { /* no elements to hash part? */281t->node = cast(Node *, dummynode); /* use common `dummynode' */282lsize = 0;283}284else {285int i;286lsize = luaO_ceillog2(size);287if (lsize > MAXBITS)288luaG_runerror(L, "table overflow");289size = twoto(lsize);290t->node = luaM_newvector(L, size, Node);291for (i=0; i<size; i++) {292Node *n = gnode(t, i);293gnext(n) = NULL;294setnilvalue(gkey(n));295setnilvalue(gval(n));296}297}298t->lsizenode = cast_byte(lsize);299t->lastfree = gnode(t, size); /* all positions are free */300}301302303void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {304int i;305int oldasize = t->sizearray;306int oldhsize = t->lsizenode;307Node *nold = t->node; /* save old hash ... */308if (nasize > oldasize) /* array part must grow? */309setarrayvector(L, t, nasize);310/* create new hash part with appropriate size */311setnodevector(L, t, nhsize);312if (nasize < oldasize) { /* array part must shrink? */313t->sizearray = nasize;314/* re-insert elements from vanishing slice */315for (i=nasize; i<oldasize; i++) {316if (!ttisnil(&t->array[i]))317luaH_setint(L, t, i + 1, &t->array[i]);318}319/* shrink array */320luaM_reallocvector(L, t->array, oldasize, nasize, TValue);321}322/* re-insert elements from hash part */323for (i = twoto(oldhsize) - 1; i >= 0; i--) {324Node *old = nold+i;325if (!ttisnil(gval(old))) {326/* doesn't need barrier/invalidate cache, as entry was327already present in the table */328setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));329}330}331if (!isdummy(nold))332luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */333}334335336void luaH_resizearray (lua_State *L, Table *t, int nasize) {337int nsize = isdummy(t->node) ? 0 : sizenode(t);338luaH_resize(L, t, nasize, nsize);339}340341342static void rehash (lua_State *L, Table *t, const TValue *ek) {343int nasize, na;344int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */345int i;346int totaluse;347for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */348nasize = numusearray(t, nums); /* count keys in array part */349totaluse = nasize; /* all those keys are integer keys */350totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */351/* count extra key */352nasize += countint(ek, nums);353totaluse++;354/* compute new size for array part */355na = computesizes(nums, &nasize);356/* resize the table to new computed sizes */357luaH_resize(L, t, nasize, totaluse - na);358}359360361362/*363** }=============================================================364*/365366367Table *luaH_new (lua_State *L) {368Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;369t->metatable = NULL;370t->flags = cast_byte(~0);371t->array = NULL;372t->sizearray = 0;373setnodevector(L, t, 0);374return t;375}376377378void luaH_free (lua_State *L, Table *t) {379if (!isdummy(t->node))380luaM_freearray(L, t->node, cast(size_t, sizenode(t)));381luaM_freearray(L, t->array, t->sizearray);382luaM_free(L, t);383}384385386static Node *getfreepos (Table *t) {387while (t->lastfree > t->node) {388t->lastfree--;389if (ttisnil(gkey(t->lastfree)))390return t->lastfree;391}392return NULL; /* could not find a free place */393}394395396397/*398** inserts a new key into a hash table; first, check whether key's main399** position is free. If not, check whether colliding node is in its main400** position or not: if it is not, move colliding node to an empty place and401** put new key in its main position; otherwise (colliding node is in its main402** position), new key goes to an empty position.403*/404TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {405Node *mp;406if (ttisnil(key)) luaG_runerror(L, "table index is nil");407#if defined LUA_HAS_FLOAT_NUMBERS408else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))409luaG_runerror(L, "table index is NaN");410#endif411mp = mainposition(t, key);412if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */413Node *othern;414Node *n = getfreepos(t); /* get a free place */415if (n == NULL) { /* cannot find a free place? */416rehash(L, t, key); /* grow table */417/* whatever called 'newkey' take care of TM cache and GC barrier */418return luaH_set(L, t, key); /* insert key into grown table */419}420lua_assert(!isdummy(n));421othern = mainposition(t, gkey(mp));422if (othern != mp) { /* is colliding node out of its main position? */423/* yes; move colliding node into free position */424while (gnext(othern) != mp) othern = gnext(othern); /* find previous */425gnext(othern) = n; /* redo the chain with `n' in place of `mp' */426*n = *mp; /* copy colliding node into free pos. (mp->next also goes) */427gnext(mp) = NULL; /* now `mp' is free */428setnilvalue(gval(mp));429}430else { /* colliding node is in its own main position */431/* new node will go into free position */432gnext(n) = gnext(mp); /* chain new position */433gnext(mp) = n;434mp = n;435}436}437setobj2t(L, gkey(mp), key);438luaC_barrierback(L, obj2gco(t), key);439lua_assert(ttisnil(gval(mp)));440return gval(mp);441}442443444/*445** search function for integers446*/447const TValue *luaH_getint (Table *t, int key) {448/* (1 <= key && key <= t->sizearray) */449if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))450return &t->array[key-1];451else {452lua_Number nk = cast_num(key);453Node *n = hashnum(t, nk);454do { /* check whether `key' is somewhere in the chain */455if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))456return gval(n); /* that's it */457else n = gnext(n);458} while (n);459return luaO_nilobject;460}461}462463464/*465** search function for short strings466*/467const TValue *luaH_getstr (Table *t, TString *key) {468Node *n = hashstr(t, key);469lua_assert(key->tsv.tt == LUA_TSHRSTR);470do { /* check whether `key' is somewhere in the chain */471if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))472return gval(n); /* that's it */473else n = gnext(n);474} while (n);475return luaO_nilobject;476}477478479/*480** main search function481*/482const TValue *luaH_get (Table *t, const TValue *key) {483switch (ttype(key)) {484case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));485case LUA_TNIL: return luaO_nilobject;486case LUA_TNUMBER: {487int k;488lua_Number n = nvalue(key);489lua_number2int(k, n);490if (luai_numeq(cast_num(k), n)) /* index is int? */491return luaH_getint(t, k); /* use specialized version */492/* else go through */493}494zfs_fallthrough;495default: {496Node *n = mainposition(t, key);497do { /* check whether `key' is somewhere in the chain */498if (luaV_rawequalobj(gkey(n), key))499return gval(n); /* that's it */500else n = gnext(n);501} while (n);502return luaO_nilobject;503}504}505}506507508/*509** beware: when using this function you probably need to check a GC510** barrier and invalidate the TM cache.511*/512TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {513const TValue *p = luaH_get(t, key);514if (p != luaO_nilobject)515return cast(TValue *, p);516else return luaH_newkey(L, t, key);517}518519520void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {521const TValue *p = luaH_getint(t, key);522TValue *cell;523if (p != luaO_nilobject)524cell = cast(TValue *, p);525else {526TValue k;527setnvalue(&k, cast_num(key));528cell = luaH_newkey(L, t, &k);529}530setobj2t(L, cell, value);531}532533534static int unbound_search (Table *t, unsigned int j) {535unsigned int i = j; /* i is zero or a present index */536j++;537/* find `i' and `j' such that i is present and j is not */538while (!ttisnil(luaH_getint(t, j))) {539i = j;540j *= 2;541if (j > cast(unsigned int, MAX_INT)) { /* overflow? */542/* table was built with bad purposes: resort to linear search */543i = 1;544while (!ttisnil(luaH_getint(t, i))) i++;545return i - 1;546}547}548/* now do a binary search between them */549while (j - i > 1) {550unsigned int m = (i+j)/2;551if (ttisnil(luaH_getint(t, m))) j = m;552else i = m;553}554return i;555}556557558/*559** Try to find a boundary in table `t'. A `boundary' is an integer index560** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).561*/562int luaH_getn (Table *t) {563unsigned int j = t->sizearray;564if (j > 0 && ttisnil(&t->array[j - 1])) {565/* there is a boundary in the array part: (binary) search for it */566unsigned int i = 0;567while (j - i > 1) {568unsigned int m = (i+j)/2;569if (ttisnil(&t->array[m - 1])) j = m;570else i = m;571}572return i;573}574/* else must find a boundary in hash part */575else if (isdummy(t->node)) /* hash part is empty? */576return j; /* that is easy... */577else return unbound_search(t, j);578}579580581582#if defined(LUA_DEBUG)583584Node *luaH_mainposition (const Table *t, const TValue *key) {585return mainposition(t, key);586}587588int luaH_isdummy (Node *n) { return isdummy(n); }589590#endif591592593