3

I'm reading lua's (5.3.0) source code, and in lobject.h I found it using a strange method to manipulate string as follow:

/*
 ** 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 */
     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;
}UTString;


/*
 ** 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 have found a good answer about the reason of using such a method in there. But I am wondering about the ensures maximum alignment for strings, what does that mean? why do we need maximum alignment and how to ensure?

Community
  • 1
  • 1
xuzhezhao
  • 103
  • 1
  • 7
  • Alignment of `union` equals to maximum of alignments of its components. `L_Umaxalign` obviously has maximal alignment as it is defined as `union { double u; void *s; lua_Integer i; long l; }` – Egor Skriptunoff Apr 24 '15 at 21:35
  • @EgorSkriptunoff I think `sizeof(TString) > sizeof(L_Umaxalign)`, so how could L_Umaxalign ensure maximum alignment for strings? and why doesn't only `TString` ensure that? – xuzhezhao Apr 25 '15 at 01:33
  • 1
    You are confusing size of a structure with its alignment. These concepts are very different. – Egor Skriptunoff Apr 25 '15 at 10:10

0 Answers0