Skip to content

Commit

Permalink
Struct hack in buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
rtheunissen committed Feb 20, 2019
1 parent 7749e6f commit db5e4c7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
11 changes: 6 additions & 5 deletions src/buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ ds_buffer_t *ds_buffer(zend_long capacity)
{
php_printf("buffer: allocate capacity of " ZEND_LONG_FMT "\n", capacity);

ds_buffer_t *buffer = ecalloc(1, sizeof(ds_buffer_t));
ds_buffer_t *buffer = ecalloc(1, DS_BUFFER_ALLOC_SIZE(capacity));
zend_object *object = (zend_object *) buffer;

zend_object_std_init((zend_object *) buffer, ds_buffer_ce);

object->handlers = &ds_buffer_handlers;
buffer->data = ecalloc(capacity, sizeof(zval));
buffer->len = capacity;

return buffer;
Expand Down Expand Up @@ -52,12 +51,14 @@ void ds_buffer_set(ds_buffer_t *buffer, zend_long offset, zval *value)
ZVAL_COPY(&buffer->data[offset], value);
}

void ds_buffer_realloc(ds_buffer_t *buffer, zend_long capacity)
ds_buffer_t *ds_buffer_realloc(ds_buffer_t *buffer, zend_long capacity)
{
php_printf("buffer: increase capacity to " ZEND_LONG_FMT "\n", capacity);

buffer->data = erealloc(buffer->data, capacity * sizeof(zval));
buffer->len = capacity;
buffer = erealloc(buffer, DS_BUFFER_ALLOC_SIZE(capacity));
buffer->len = capacity;

return buffer;
}

ds_buffer_t *ds_buffer_create_copy(ds_buffer_t *src)
Expand Down
10 changes: 8 additions & 2 deletions src/buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,19 @@
*/
#define DS_ZVAL_GET_BUFFER(z) ((ds_buffer_t *) (Z_OBJ_P(z)))

/**
* Allocation length for the buffer struct and data.
*/
#define DS_BUFFER_ALLOC_SIZE(capacity) \
(sizeof(ds_buffer_t) + sizeof(zval) * (capacity - 1))

/**
* Buffer object.
*/
typedef struct ds_buffer {
zend_object std;
zval *data;
zend_long len;
zval data[1];
} ds_buffer_t;

/**
Expand Down Expand Up @@ -50,7 +56,7 @@ ds_buffer_t *ds_buffer_create_copy(ds_buffer_t *src);
/**
* Reallocates the buffer to a given capacity.
*/
void ds_buffer_realloc(ds_buffer_t *obj, zend_long capacity);
ds_buffer_t *ds_buffer_realloc(ds_buffer_t *buffer, zend_long capacity);

/**
* Sets the array representation of a given buffer.
Expand Down
3 changes: 2 additions & 1 deletion src/vector.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ void ds_vector_push(ds_vector_t *vector, zval *value)

/* Check if we need to grow. */
if (vector->size == buffer->len) {
ds_buffer_realloc(buffer, buffer->len * 2 + 1);
buffer = ds_buffer_realloc(buffer, buffer->len * 2 + 1);
DS_VECTOR_SET_BUFFER(vector, buffer);
}

ds_buffer_set(buffer, vector->size, value);
Expand Down

0 comments on commit db5e4c7

Please sign in to comment.