diff options
Diffstat (limited to 'sql/sql_array.h')
-rw-r--r-- | sql/sql_array.h | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/sql/sql_array.h b/sql/sql_array.h index dfaa9b02947..19ce4e2e62b 100644 --- a/sql/sql_array.h +++ b/sql/sql_array.h @@ -69,4 +69,74 @@ public: } }; +/* + Array of pointers to Elem that uses memory from MEM_ROOT + + MEM_ROOT has no realloc() so this is supposed to be used for cases when + reallocations are rare. +*/ + +template <class Elem> class Array +{ + enum {alloc_increment = 16}; + Elem **buffer; + uint n_elements, max_element; +public: + Array(MEM_ROOT *mem_root, uint prealloc=16) + { + buffer= (Elem**)alloc_root(mem_root, prealloc * sizeof(Elem**)); + max_element = buffer? prealloc : 0; + n_elements= 0; + } + + Elem& at(int idx) + { + return *(((Elem*)buffer) + idx); + } + + Elem **front() + { + return buffer; + } + + Elem **back() + { + return buffer + n_elements; + } + + bool append(MEM_ROOT *mem_root, Elem *el) + { + if (n_elements == max_element) + { + Elem **newbuf; + if (!(newbuf= (Elem**)alloc_root(mem_root, (n_elements + alloc_increment)* + sizeof(Elem**)))) + { + return FALSE; + } + memcpy(newbuf, buffer, n_elements*sizeof(Elem*)); + buffer= newbuf; + } + buffer[n_elements++]= el; + return FALSE; + } + + int elements() + { + return n_elements; + } + + void clear() + { + n_elements= 0; + } + + typedef int (*CMP_FUNC)(Elem * const *el1, Elem *const *el2); + + void sort(CMP_FUNC cmp_func) + { + my_qsort(buffer, n_elements, sizeof(Elem*), (qsort_cmp)cmp_func); + } +}; + #endif /* SQL_ARRAY_INCLUDED */ |