MySQL中,常常會看到一些關于動態字符串的處理,列如:DYNAMIC_STRING。
為了記錄動態字符串的實際長度,緩沖區的最大長度,以及每次字符串需要調整時,及時分配新的內存,以及調整長度。MySQL使用了DYNAMIC_STRING來保存動態字符串相關的信息:
| typedef struct st_dynamic_string{ char *str; size_t length, max_length, alloc_increment;} DYNAMIC_STRING; |
在這個結構體中,str存儲實際字符串的首地址,length記錄字符串的實際長度,max_length記錄字符串緩沖區最多可以存放多少字符,alloc_increment表示當字符串需要分配內存時,每次分配多少內存。
下面看看這個結構體的初始化過程:
| my_bool init_dynamic_string( DYNAMIC_STRING *str, const char *init_str, size_t init_alloc, size_t alloc_increment ){ size_t length; DBUG_ENTER( "init_dynamic_string" ); if ( !alloc_increment ) alloc_increment = 128; length = 1; if ( init_str && (length = strlen( init_str ) + 1) < init_alloc ) init_alloc = ( (length + alloc_increment - 1) / alloc_increment) * alloc_increment; if ( !init_alloc ) init_alloc = alloc_increment; if ( !(str->str = (char *) my_malloc( init_alloc, MYF( MY_WME ) ) ) ) DBUG_RETURN( TRUE ); str->length = length - 1; if ( init_str ) memcpy( str->str, init_str, length ); str->max_length = init_alloc; str->alloc_increment = alloc_increment; DBUG_RETURN( FALSE );} |
從上述函數可以看到,初始化時,初始分配的字符串緩沖區大小init_alloc會根據需要初始的字符串來做判斷。在分配好該DYNAMIC_STRING空間之后,我們會根據緩沖區的大小,字符串的實際長度,以及alloc_increment來初始化:
length:字符串的實際長度
max_length:緩沖區的最大長度
alloc_increment:空間不夠時,下次分配內存的單元大小.
初始化這些內容之后,如果下次需要在該緩沖區添加更多字符,就可以根據這些值來判斷是否需要對該緩沖區擴容:
| my_bool dynstr_append_mem( DYNAMIC_STRING *str, const char *append, size_t length ){ char *new_ptr; if ( str->length + length >= str->max_length ) /* 如果新增字符串后,總長度超過緩沖區大小 */ {/* 需要分配多少個alloc_increment 大小的內存,才能存下新增后的字符串 */ size_t new_length = (str->length + length + str->alloc_increment) / str->alloc_increment; new_length *= str->alloc_increment; if ( !(new_ptr = (char *) my_realloc( str->str, new_length, MYF( MY_WME ) ) ) ) return(TRUE); str->str = new_ptr; str->max_length = new_length; }/* 將新分配的內容,append到str之后 */ memcpy( str->str + str->length, append, length ); str->length += length; /* 擴容之后str新的長度 */ str->str[str->length] = 0; /* Safety for C programs */ /* 字符串最后一個字符為'/0' */ return(FALSE);} |