SwArray data structures

SwArray is a Swoole array structure that implements pre-allocation of space.

Basic data structure

typedef struct _swArray
{
    // void * pointer array, page space
    void **pages;
    // Number of pages
    uint16_t page_num;
    // The number of data elements in the page
    uint16_t page_size;
    // Data element size
    uint32_t item_size;
    // Total number of elements
    uint32_t item_num;
    // The current index position of the array is offset, which is used to append elements
    uint32_t offset; 
} swArray;
Copy the code

chart

Basic method

// Calculate which page of the swArray index n is located in
#define swArray_page(array, n)      ((n) / (array)->page_size)
// Calculates the offset between the index n bit and the page item specified by swArray
#define swArray_offset(array, n)    ((n) % (array)->page_size)

// Create an array
swArray *swArray_new(int page_size, size_t item_size);
// Destroy the array
void swArray_free(swArray *array);
// Get an array element
void *swArray_fetch(swArray *array.uint32_t n);
// Store a data at index n
int swArray_store(swArray *array.uint32_t n, void *data);
// Allocate n elements, expand the array if there are not enough pages
void *swArray_alloc(swArray *array.uint32_t n);
// Appends an element
int swArray_append(swArray *array.void *data);
// Extend the array to allocate a page structure
int swArray_extend(swArray *array);
// Clear the array contents
void swArray_clear(swArray *array);
Copy the code

Analysis of core technical points

  1. Create a new array swArray_new and define the number of elements in each page and the size of the elements. Then use swArray_extend to preassign a page.

  2. The append element swArray_append is based on the offset attribute in swArray, which is the offset of the current element, the index of the current element, and is a cumulative value.

  3. SwArray_store adds elements to the user-specified index N

  4. To remove an array

// Simply set offset and item_num to 0 to clear data without freeing space
void swArray_clear(swArray *array)
{
    array->offset = 0;
    array->item_num = 0;
}

/ / = = = = = = = = = = = = = = = / /

// Traversal frees each page and frees pages and the entire array memory space
void swArray_free(swArray *array)
{
    int i;
    // The number of pages traversed
    for (i = 0; i < array->page_num; i++)
    {
        sw_free(array->pages[i]);
    }
    // Release the page variable
    sw_free(array->pages);
    // Free the entire array
    sw_free(array);
}

Copy the code