深入Lua - 字符串

作者: JYGod丶 | 来源:发表于2018-07-24 17:40 被阅读9次

    字符串结构定义

    Lua中字符串结构体定义:

    /*
    ** Common Header for all collectable objects (in macro form, to be
    ** included in other objects)
    */
    #define CommonHeader    GCObject *next; lu_byte tt; lu_byte marked
    
    /*
    ** Header for string value; string bytes follow the end of this structure
    ** (aligned according to 'UTString'; see next).
    */
    typedef struct TString {
      CommonHeader;
      lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
      lu_byte shrlen;  /* length for short strings */
      unsigned int hash;
      union {
        size_t lnglen;  /* length for long strings */
        struct TString *hnext;  /* linked list for hash table */
      } u;
    } TString;
    
    
    /*
    ** Ensures that address after this type is always fully aligned.
    */
    typedef union UTString {
      L_Umaxalign dummy;  /* ensures maximum alignment for strings */
      TString tsv;
    } UTString;
    

    字符串缓存

    在创建字符串时,首先会从global_State的strcache缓存中查找看是否存在:

    strcache结构.png
    // #define STRCACHE_N       53
    // #define STRCACHE_M       2
    
    TString *luaS_new (lua_State *L, const char *str) {
      unsigned int i = point2uint(str) % STRCACHE_N;  /* hash */
      int j;
      TString **p = G(L)->strcache[i];
      for (j = 0; j < STRCACHE_M; j++) {
        // strcmp == 0,两个str相同
        // getstr --> TString转string
        if (strcmp(str, getstr(p[j])) == 0) 
          return p[j]; // 找到相同str
      }
      for (j = STRCACHE_M - 1; j > 0; j--)
        p[j] = p[j - 1]; // 移动元素
      // 新元素会插入到list最前端
      p[0] = luaS_newlstr(L, str, strlen(str));
      return p[0];
    }
    

    创建一个字符串的时候,首先会在strcache中查找,第7行根据str计算出该str在strcache的索引位置,在该strcache位置上又有一个大小为2( STRCACHE_M )的TString数组,若在这个数组中找到相同的字符串,则返回cache中字符串对应的TString;若未找到,会将p[0]位置的TString挪到p[1]位置,而p[0]位置存放luaS_newlstr新创建的TString。

    创建字符串

    // #define LUAI_MAXSHORTLEN 40
    
    /*
    ** new string (with explicit length)
    */
    TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
      if (l <= LUAI_MAXSHORTLEN)  /* short string? */
        return internshrstr(L, str, l);
      else {
        TString *ts;
        if (l >= (MAX_SIZE - sizeof(TString))/sizeof(char))
          luaM_toobig(L);
        ts = luaS_createlngstrobj(L, l);
        memcpy(getstr(ts), str, l * sizeof(char));
        return ts;
      }
    }
    

    新建一个TString时,会判断字符串长度是否大于40( LUAI_MAXSHORTLEN ),对于长度大于40的str,会直接创建TString并返回,而对于长度40以内的short string,会从global_State中的一个stringtable(strt)查找并记录:

    /*
    ** checks whether short string exists and reuses it or creates a new one
    */
    static TString *internshrstr (lua_State *L, const char *str, size_t l) {
      TString *ts;
      global_State *g = G(L);
      unsigned int h = luaS_hash(str, l, g->seed);
      TString **list = &g->strt.hash[lmod(h, g->strt.size)];
      lua_assert(str != NULL);  /* otherwise 'memcmp'/'memcpy' are undefined */
      for (ts = *list; ts != NULL; ts = ts->u.hnext) {
        if (l == ts->shrlen &&
            (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
          /* found! */
          if (isdead(g, ts))  /* dead (but not collected yet)? */
            changewhite(ts);  /* resurrect it */
          return ts;
        }
      }
      // list中如果没找到
      // resize 扩容
      if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) {
        luaS_resize(L, g->strt.size * 2);
        list = &g->strt.hash[lmod(h, g->strt.size)];  /* recompute with new size */
      }
      // 不需要扩容的情况
      ts = createstrobj(L, l, LUA_TSHRSTR, h);
      memcpy(getstr(ts), str, l * sizeof(char));
      ts->shrlen = cast_byte(l);
      ts->u.hnext = *list;
      *list = ts;
      g->strt.nuse++;
      return ts;
    }
    

    strt的数据结构类似于HashMap,它的初始化的数组长度为128,首先根据str计算得到的hash值(0~127),找到数组对应的下标索引,取出对应下标的list链表,10 ~ 18行是对该list进行遍历,若找到则直接返回;如未找到,则继续向下走。第21行, 如果 nuse(当前strt中TSring总数) 超过容量size(初始128)值,就会进行luaS_resize扩容操作(后续细讲),strt的容量将扩为原来的2倍。如果不需要扩容,第26行开始,会创建一个新的TString,并将其插入到当前list的头部。

    strt结构.png

    扩容

    /*
    ** resizes the string table
    */
    void luaS_resize (lua_State *L, int newsize) {
      int i;
      stringtable *tb = &G(L)->strt;
      if (newsize > tb->size) {  /* grow table if needed */
        luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
        for (i = tb->size; i < newsize; i++)
          tb->hash[i] = NULL;
      }
      for (i = 0; i < tb->size; i++) {  /* rehash */
        TString *p = tb->hash[i];
        tb->hash[i] = NULL;
        while (p) {  // 遍历每一个节点
          TString *hnext = p->u.hnext; 
          unsigned int h = lmod(p->hash, newsize); 
          p->u.hnext = tb->hash[h];
          tb->hash[h] = p;
          p = hnext;
        }
      }
      if (newsize < tb->size) {  /* shrink table if needed */
        /* vanishing slice should be empty */
        lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);
        luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
      }
      tb->size = newsize;
    }
    

    第7行,如果需要扩容,则调用luaM_reallocvector将 tb->hash 数组扩大到newsize (2倍),12行~22行对每一个数组位置list链表中每一个TString节点的元素重新计算hash值,并将其插入到对应数组中的链表头部位置处。

    相关文章

      网友评论

        本文标题:深入Lua - 字符串

        本文链接:https://www.haomeiwen.com/subject/uleymftx.html