Skip to content

Commit

Permalink
Update buffer from 'github/zhaojh329/buffer'
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <jianhuizhao329@gmail.com>
  • Loading branch information
Jianhui Zhao committed Oct 8, 2018
1 parent ddda3d1 commit 9cd9ab4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <limits.h>
Expand Down Expand Up @@ -109,6 +108,7 @@ void *buffer_put(struct buffer *b, size_t len)

tmp = b->tail;
b->tail += len;

return tmp;
}

Expand Down Expand Up @@ -230,6 +230,8 @@ size_t buffer_pull(struct buffer *b, void *dest, size_t len)

b->data += len;

buffer_check_persistent_size(b);

return len;
}

Expand Down Expand Up @@ -283,6 +285,8 @@ int buffer_pull_to_fd(struct buffer *b, int fd, size_t len,
b->data += ret;
} while (remain);

buffer_check_persistent_size(b);

return len - remain;
}

Expand Down
23 changes: 22 additions & 1 deletion src/buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/types.h>

Expand All @@ -46,6 +47,7 @@ enum {
};

struct buffer {
size_t persistent; /* persistent size */
uint8_t *head; /* Head of buffer */
uint8_t *data; /* Data head pointer */
uint8_t *tail; /* Data tail pointer */
Expand Down Expand Up @@ -84,6 +86,23 @@ static inline void *buffer_data(const struct buffer *b)
return b->data;
}

static inline void buffer_set_persistent_size(struct buffer *b, size_t size)
{
size_t new_size = getpagesize();

while (new_size < size)
new_size <<= 1;

b->persistent = new_size;
}

static inline void buffer_check_persistent_size(struct buffer *b)
{
if (b->persistent > 0 &&
buffer_size(b) > b->persistent && buffer_length(b) < b->persistent)
buffer_resize(b, b->persistent);
}

void *buffer_put(struct buffer *b, size_t len);

static inline void *buffer_put_zero(struct buffer *b, size_t len)
Expand Down Expand Up @@ -182,8 +201,10 @@ int buffer_put_fd(struct buffer *b, int fd, ssize_t len, bool *eof,
*/
static inline void buffer_truncate(struct buffer *b, size_t len)
{
if (buffer_length(b) > len)
if (buffer_length(b) > len) {
b->tail = b->data + len;
buffer_check_persistent_size(b);
}
}


Expand Down

0 comments on commit 9cd9ab4

Please sign in to comment.