lstring.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008 #include <string.h>
00009
00010 #define lstring_c
00011 #define LUA_CORE
00012
00013 #include "lua.h"
00014
00015 #include "lmem.h"
00016 #include "lobject.h"
00017 #include "lstate.h"
00018 #include "lstring.h"
00019
00020
00021
00022 void luaS_resize (lua_State *L, int newsize) {
00023 GCObject **newhash;
00024 stringtable *tb;
00025 int i;
00026 if (G(L)->gcstate == GCSsweepstring)
00027 return;
00028 newhash = luaM_newvector(L, newsize, GCObject *);
00029 tb = &G(L)->strt;
00030 for (i=0; i<newsize; i++) newhash[i] = NULL;
00031
00032 for (i=0; i<tb->size; i++) {
00033 GCObject *p = tb->hash[i];
00034 while (p) {
00035 GCObject *next = p->gch.next;
00036 unsigned int h = gco2ts(p)->hash;
00037 int h1 = lmod(h, newsize);
00038 lua_assert(cast_int(h%newsize) == lmod(h, newsize));
00039 p->gch.next = newhash[h1];
00040 newhash[h1] = p;
00041 p = next;
00042 }
00043 }
00044 luaM_freearray(L, tb->hash, tb->size, TString *);
00045 tb->size = newsize;
00046 tb->hash = newhash;
00047 }
00048
00049
00050 static TString *newlstr (lua_State *L, const char *str, size_t l,
00051 unsigned int h) {
00052 TString *ts;
00053 stringtable *tb;
00054 if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char))
00055 luaM_toobig(L);
00056 ts = cast(TString *, luaM_malloc(L, (l+1)*sizeof(char)+sizeof(TString)));
00057 ts->tsv.len = l;
00058 ts->tsv.hash = h;
00059 ts->tsv.marked = luaC_white(G(L));
00060 ts->tsv.tt = LUA_TSTRING;
00061 ts->tsv.reserved = 0;
00062 memcpy(ts+1, str, l*sizeof(char));
00063 ((char *)(ts+1))[l] = '\0';
00064 tb = &G(L)->strt;
00065 h = lmod(h, tb->size);
00066 ts->tsv.next = tb->hash[h];
00067 tb->hash[h] = obj2gco(ts);
00068 tb->nuse++;
00069 if (tb->nuse > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
00070 luaS_resize(L, tb->size*2);
00071 return ts;
00072 }
00073
00074
00075 TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
00076 GCObject *o;
00077 unsigned int h = cast(unsigned int, l);
00078 size_t step = (l>>5)+1;
00079 size_t l1;
00080 for (l1=l; l1>=step; l1-=step)
00081 h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1]));
00082 for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)];
00083 o != NULL;
00084 o = o->gch.next) {
00085 TString *ts = rawgco2ts(o);
00086 if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0)) {
00087
00088 if (isdead(G(L), o)) changewhite(o);
00089 return ts;
00090 }
00091 }
00092 return newlstr(L, str, l, h);
00093 }
00094
00095
00096 Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
00097 Udata *u;
00098 if (s > MAX_SIZET - sizeof(Udata))
00099 luaM_toobig(L);
00100 u = cast(Udata *, luaM_malloc(L, s + sizeof(Udata)));
00101 u->uv.marked = luaC_white(G(L));
00102 u->uv.tt = LUA_TUSERDATA;
00103 u->uv.len = s;
00104 u->uv.metatable = NULL;
00105 u->uv.env = e;
00106
00107 u->uv.next = G(L)->mainthread->next;
00108 G(L)->mainthread->next = obj2gco(u);
00109 return u;
00110 }