lua 5.2.3 source lstring.c function luaS_resize -
void luas_resize (lua_state *l, int newsize) { int i; stringtable *tb = &g(l)->strt; /* cannot resize while gc traversing strings */ luac_runtilstate(l, ~bitmask(gcssweepstring)); if (newsize > tb->size) { luam_reallocvector(l, tb->hash, tb->size, newsize, gcobject *); (i = tb->size; < newsize; i++) tb->hash[i] = null; } /* rehash */ (i=0; i<tb->size; i++) { gcobject *p = tb->hash[i]; tb->hash[i] = null; while (p) { /* each node in list */ gcobject *next = gch(p)->next; /* save next */ unsigned int h = lmod(gco2ts(p)->hash, newsize); /* new position */ gch(p)->next = tb->hash[h]; /* chain */ tb->hash[h] = p; resetoldbit(p); /* see move old rule */ p = next; } } if (newsize < tb->size) { /* shrinking slice must empty */ lua_assert(tb->hash[newsize] == null && tb->hash[tb->size - 1] == null); luam_reallocvector(l, tb->hash, tb->size, newsize, gcobject *); } tb->size = newsize; }
when table grows, rehashes. when table shrinks, realloc half size without rehash. can't understand it. how can work ?
well. answer question myself. code works because rehash operation not in first if(newsize > tb->size). works both (newsize > tb->size) , (newsize < tb->size). next time, read code more carefully.
Comments
Post a Comment