lstring.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. ** $Id: lstring.c,v 1.62 2001/03/26 14:31:49 roberto Exp roberto $
  3. ** String table (keeps all strings handled by Lua)
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <string.h>
  7. #define LUA_PRIVATE
  8. #include "lua.h"
  9. #include "lmem.h"
  10. #include "lobject.h"
  11. #include "lstate.h"
  12. #include "lstring.h"
  13. void luaS_freeall (lua_State *L) {
  14. lua_assert(G(L)->strt.nuse==0);
  15. luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *);
  16. }
  17. void luaS_resize (lua_State *L, int newsize) {
  18. TString **newhash = luaM_newvector(L, newsize, TString *);
  19. stringtable *tb = &G(L)->strt;
  20. int i;
  21. for (i=0; i<newsize; i++) newhash[i] = NULL;
  22. /* rehash */
  23. for (i=0; i<tb->size; i++) {
  24. TString *p = tb->hash[i];
  25. while (p) { /* for each node in the list */
  26. TString *next = p->nexthash; /* save next */
  27. lu_hash h = p->hash;
  28. int h1 = lmod(h, newsize); /* new position */
  29. lua_assert((int)(h%newsize) == lmod(h, newsize));
  30. p->nexthash = newhash[h1]; /* chain it in new position */
  31. newhash[h1] = p;
  32. p = next;
  33. }
  34. }
  35. luaM_freearray(L, tb->hash, tb->size, TString *);
  36. tb->size = newsize;
  37. tb->hash = newhash;
  38. }
  39. TString *luaS_newlstr (lua_State *L, const l_char *str, size_t l) {
  40. TString *ts;
  41. lu_hash h = l; /* seed */
  42. size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */
  43. size_t l1;
  44. for (l1=l; l1>=step; l1-=step) /* compute hash */
  45. h = h ^ ((h<<5)+(h>>2)+uchar(str[l1-1]));
  46. for (ts = G(L)->strt.hash[lmod(h, G(L)->strt.size)]; ts; ts = ts->nexthash) {
  47. if (ts->len == l && (memcmp(str, getstr(ts), l) == 0))
  48. return ts;
  49. }
  50. /* not found */
  51. ts = (TString *)luaM_malloc(L, sizestring(l));
  52. ts->marked = 0;
  53. ts->nexthash = NULL;
  54. ts->len = l;
  55. ts->hash = h;
  56. ts->constindex = 0;
  57. memcpy(getstr(ts), str, l*sizeof(l_char));
  58. getstr(ts)[l] = 0; /* ending 0 */
  59. h = lmod(h, G(L)->strt.size);
  60. ts->nexthash = G(L)->strt.hash[h]; /* chain new entry */
  61. G(L)->strt.hash[h] = ts;
  62. G(L)->strt.nuse++;
  63. if (G(L)->strt.nuse > (ls_nstr)G(L)->strt.size &&
  64. G(L)->strt.size <= MAX_INT/2)
  65. luaS_resize(L, G(L)->strt.size*2); /* too crowded */
  66. return ts;
  67. }
  68. Udata *luaS_newudata (lua_State *L, size_t s) {
  69. Udata *u = (Udata *)luaM_malloc(L, sizeudata(s));
  70. u->marked = 0;
  71. u->len = s;
  72. u->tag = 0;
  73. u->value = ((union L_UUdata *)(u) + 1);
  74. /* chain it on udata list */
  75. u->next = G(L)->rootudata;
  76. G(L)->rootudata = u;
  77. return u;
  78. }