Lely core libraries  2.2.5
membuf.c
Go to the documentation of this file.
1 
24 #include "util.h"
25 #define LELY_UTIL_MEMBUF_INLINE extern inline
26 #include <lely/util/errnum.h>
27 #include <lely/util/membuf.h>
28 
29 #include <assert.h>
30 #include <stdlib.h>
31 
32 #ifndef LELY_MEMBUF_SIZE
33 #define LELY_MEMBUF_SIZE 16
35 #endif
36 
37 void
38 membuf_fini(struct membuf *buf)
39 {
40  assert(buf);
41 
42  free(buf->begin);
43 }
44 
45 size_t
46 membuf_reserve(struct membuf *buf, size_t size)
47 {
48  assert(buf);
49 
50  size_t capacity = membuf_capacity(buf);
51  if (size <= capacity)
52  return capacity;
53 
54  // The required size equals the size of the data already in the buffer,
55  // plus the data to be added. To limit the number of allocations, we
56  // keep doubling the size of the buffer until it is large enough.
57  size_t buf_size = LELY_MEMBUF_SIZE;
58  while (buf_size < membuf_size(buf) + size)
59  buf_size *= 2;
60 
61  char *begin = realloc(buf->begin, buf_size);
62  if (!begin) {
63  set_errc(errno2c(errno));
64  return 0;
65  }
66 
67  buf->cur = begin + membuf_size(buf);
68  buf->begin = begin;
69  buf->end = buf->begin + buf_size;
70 
71  return membuf_capacity(buf);
72 }
73 
74 void
75 membuf_flush(struct membuf *buf, size_t size)
76 {
77  assert(buf);
78 
79  size = MIN(size, membuf_size(buf));
80  if (size)
81  memmove(buf->begin, buf->begin + size, membuf_size(buf) - size);
82  buf->cur -= size;
83 }
LELY_MEMBUF_SIZE
#define LELY_MEMBUF_SIZE
The initial size (in bytes) of a memory buffer.
Definition: membuf.c:34
membuf_reserve
size_t membuf_reserve(struct membuf *buf, size_t size)
Resizes a memory buffer, if necessary, to make room for at least an additional size bytes.
Definition: membuf.c:46
MIN
#define MIN(a, b)
Returns the minimum of a and b.
Definition: util.h:57
membuf
A memory buffer.
Definition: membuf.h:35
errno2c
int errno2c(int errnum)
Transforms a standard C error number to a native error code.
Definition: errnum.c:43
util.h
membuf_size
size_t membuf_size(const struct membuf *buf)
Returns the total number of bytes written to a memory buffer.
Definition: membuf.h:156
membuf_fini
void membuf_fini(struct membuf *buf)
Finalizes a memory buffer.
Definition: membuf.c:38
membuf::end
char * end
A pointer to one past the last byte in the buffer.
Definition: membuf.h:41
set_errc
void set_errc(int errc)
Sets the current (thread-specific) native error code to errc.
Definition: errnum.c:957
errnum.h
membuf.h
membuf_flush
void membuf_flush(struct membuf *buf, size_t size)
Flushes size bytes from the beginning of a memory buffer.
Definition: membuf.c:75
membuf_capacity
size_t membuf_capacity(const struct membuf *buf)
Returns the number of unused bytes remaining in a memory buffer.
Definition: membuf.h:162
membuf::cur
char * cur
A pointer to one past the last byte written to the buffer.
Definition: membuf.h:37
membuf::begin
char * begin
A pointer to the first byte in the buffer.
Definition: membuf.h:39
stdlib.h