How does Lua UTString ensure maximum string alignment?

I am reading the lua (5.3.0) source code, and in lobject.h

I found it using a strange method for manipulating a string:

 ** Header for string value; string bytes follow the end of this structure
 ** (aligned according to 'UTString'; see next).
 typedef struct TString {
     lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
     unsigned int hash;
     size_t len;  /* number of characters in string */
     struct TString *hnext;  /* linked list for hash table */
} TString;

** Ensures that address after this type is always fully aligned.
typedef union UTString {
    L_Umaxalign dummy;  /* ensures maximum alignment for strings */
    TString tsv;

 ** Get the actual string (array of bytes) from a 'TString'.
 ** (Access to 'extra' ensures that value is really a 'TString'.)
#define getaddrstr(ts)  (cast(char *, (ts)) + sizeof(UTString))
#define getstr(ts)  \
check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts)))


I found a good answer on the reason for using such a method in there . But I'm wondering oh ensures maximum alignment for strings

what does that mean? Why do we need maximum alignment

and how to provide?


source to share

All Articles