Source code implementation of string types in Lua

Source: Internet
Author: User

Overview

    Lua full adoption 8 bit encoded, lua Characters in a string can have any numeric encoding, including the numeric value 0 lua immutable values ). If modified, essentially creates a new string. According to the above " Lua In the source code implementation of the data type , you know, in lua tstring To implement the storage string value. The following will be done through the lua 5. 2.1 of the source code to see the implementation of the string and summarizes the use of strings in Lua considerations.

Source Code Implementation

First of all, the string corresponding data structure tstring, the source code is as follows (lobject.h):

410/*411 * * Header for string value; String bytes Follow the end of this structure412 */413 typedef union tstring {414   l_umaxalign dummy;  /* Ensures maximum alignment for strings */415   struct {416     commonheader;417 lu_byte     Extra;  /* Reserved words for short strings; "Have hash" for longs */418     unsigned int hash;419     size_t len;  /* Number of characters in string */420   } tsv;421} tstring;

For this consortium definition, there are a few points worth explaining:

I, a member of the Consortium tstring l_umaxalign dummy is used to guarantee the maximum length of C The type is aligned and is defined as follows (llimits.h):

*/* Type to ensure maximum alignment */#if!defined (luai_user_alignment_t) #define LUAI_USER_ALIGNMENT_T   Uni on {double u; void *s; long l;} #endif a      typedef luai_user_alignment_t l_umaxalign;

In the implementation of other objects that can be recycled (such as table), you can also see this union member, which is designed to speed up CPU access to memory by aligning memory .

II, the member TSV in the consortium is really used to implement the string. Where member commonheader is used for GC, it is defined as a macro in all recyclable objects, and the code is as follows (lobject.h ):

Common/* * * * * * * Header for all collectable objects (in macro form, to be-in-objects * * Included in + other) * */#def Ine Commonheader    gcobject *next; lu_byte tt; Lu_byte marked

The structure of this macro corresponds to the following form (lobject.h):

Bayi */* Common header in struct form----*/--typedef struct GCHEADER {   commonheader; gcheader;

struct gcheader is useful in the definition of the universal recyclable object union gcobject.

III,lu_byte extra for short strings, used to record whether the string is a reserved word, for a long string, can be used for lazy hash value; The unsigned int hash member is the hash value of the string (in the following case, how Lua computes the hash of the string size_t len is used to denote the length of a string.

IV, The structure above only describes the structure of a string, the real string data is saved immediately after the structure.

InLua5.2.1before, the string is not distinguished between long and short strings, all strings are saved in a globalHashtable, forLuavirtual machines, the same string has only one copy of the data, fromLua5.2.1start, just put a short string string (currently defined as length less than equals +) on the globalHashtable, and long strings are generated independently, while the calculationHashvalue, a random seed is introduced to preventHash Dos--attackers construct very much the sameHashdifferent strings of values, thereby reducingLuastring that presses the string from the outside into the globalHashefficiency of the table. Below isLua5.2.1, the steps for generating a new string, the corresponding code islstring.cMedium:

  (1 If the string length is greater than luai_maxshortlen (the default is Span style= "Font-family:verdana" >40 ) is a long string that calls directly to the function that created the string interface createstrobj (of course the length of the string needs to be saved in the member size_t len lstring.c

 * * * Creates a new String Object 97 */                              98 static tstring *createstrobj (lua_state *l, const char *STR, size_t L, Gcobject int tag, unsigned int h, **list) {tstring *ts                                                                                     ;  101 size_t TotalSize;  /* Total size of tstring Object */102 TotalSize = sizeof (tstring) + ((L + 1)                                          * sizeof (char)); 103 ts = &luac_newobj (L, tag, totalsize, list, 0)->ts;104 Ts->tsv.len = l;105 Ts->tsv.hash = h;106 ts                                                                               ->tsv.extra = 0;  107 memcpy (ts+1, str, l*sizeof (char)), 108 ((char *) (ts+1)) [l] = ' n ';                                 /* Ending 0 */                     109 Return ts;110}  

The

can see that the strings passed in are placed exactly behind the struct tstring memory, Also note that 108 " c language strings are compatible.

  (2 ) If the string is a short string, first calculate the string's hash hash table, using the method of linking method, To place all conflicting elements in the same list), find whether the currently created string is already in hash table, if already exists, returns the string directly. Otherwise, the function is called newshrstr newshrstr createstrobj function creates a new string and places the newly created string into the hash lstring.c

130/*131 * *  Checks whether short string exists and reuses it or creates a new one132 */133 static tstring *internshrstr (Lua_state *l, const char *STR, size_t l) {134 Gcobject *o;135 global_state *g = g (l); 136 unsigned int h = luas_hash (str, L, G->     , seed); 137 for (o = G->strt.hash[lmod (h, g->strt.size)];138 o! = null;139 o = GCH (o)->next) {140         Tstring *ts = Rawgco2ts (o) 141 if (h = = Ts->tsv.hash &&142 Ts->tsv.len = = L &&143 (MEMCMP (str, GETSTR (TS), L * sizeof (char)) = = 0))  {144 if (Isdead (G (L), O))/* string is dead (and was not collected yet)? */145 Changewhite (o);  /* Resurrect it */146 return ts;147}148}149 return newshrstr (L, str, L, h); /* not found; Create a new string */150} 

The global string Hash table is saved in the virtual Machine Global State Member strt (lstate.h):

119   stringtable strt;  /* Hash table for Strings */

The type stringtable is a struct, which is defined as follows (lstate.h):

A typedef struct STRINGTABLE {   gcobject **hash;   lu_int32 nuse;  /* Number of elements * */"   int" size; stringtable};

Where member gcobject **hash is an array of pointers, Each member in the array essentially points to tstring (note tstring include macros commonheader in this macro next Members can construct a hash nuse is an array of hash size is the current array hash

Before the function newshrstr Inserts a new string, it will be judged whether the nuse value is greater than size, andif it is greater, the Hash table size is not enough to expand, then the size of the Hash table is expanded to 2 times the original, the corresponding code is as follows (lstring.c ):

121   if (tb->nuse >= cast (Lu_int32, tb->size) && tb->size <= max_int/2)                               122     Luas_ Resize (L, tb->size*2);  

When GC nuse is more than size/ 2 is also small (in lua 5.1 Nuse and Size/4, if yes, re-resize Span style= "font-family: Song body" > this stringtable half. The corresponding code is as follows (lgc.c

783     int hs = g->strt.size/2;  /* Half the size of the string table                           *     /784 if (G->strt.nuse < cast (Lu_int32, HS))/  * using less than th At half? *       /785 Luas_resize (L, HS);  /* Halve its size */

For string comparisons, the first comparison of types, if different types of strings, is certainly not the same, and then distinguish between short strings and long strings, for short strings, if the two pointers are equal, then the same, otherwise, the corresponding long string, the first comparison of pointer values, if different, the comparison length value and content-per-character comparison.

Summarize

(1) The reserved words and meta-method names in Lua are used as short strings, and they are placed into the global short string Hash table when the virtual machine is started , and are not recycled.

(2) It is more efficient to find characters, but it is inefficient to modify or insert strings, which, in addition to calculations, copies the outer strings to the virtual machine at least.

(3) for hash valuesof long strings,Lua does not look at each character, thus avoiding the ability to quickly calculate hash values for long strings. Its corresponding code is as follows (lstring.c):

 Wuyi unsigned int luas_hash (const char *STR, size_t l, unsigned int seed) {unsigned int                                                                        h = seed ^ l;                                                                                        size_t L1;                                                          size_t step = (L >> luai_hashlimit) + 1; for (L1 = l; L1 >= step; L1-to-step), H = h ^ (                                             (h<<5) + (H&GT;&GT;2) + cast_byte (Str[l1-1]));                                                                                         +-H; * * * Lua wil                       L Use @ Most ~ (2^luai_hashlimit) bytes from a string to * * compute its hash                                                          24 */                                                                        !defined #if (Luai_hashlimit)                                                                       #define LUAI_HASHLIMIT 5 #endif

(4) when there are multiple strings connected, you should not directly concatenate the operator ".." With a string, but instead use the table.concat operation or String.Format to speed up the operation of the string connection.

(5) The string hash algorithm used in Lua is Jshash, the various hash functions of the string, the network has an article to summarize it:https://www.byvoid.com /blog/string-hash-compare (Comparison of various string hash functions).


Source code implementation of string types in Lua

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.