2 * Copyright (C) 2017 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 * SPDX-License-Identifier: LGPL-2.1-only
8 #include <common/dynamic-buffer.h>
9 #include <common/utils.h>
13 * Round to (upper) power of two, val is returned if it already is a power of
17 size_t round_to_power_of_2(size_t val
)
22 order
= utils_get_count_order_u64(val
);
24 rounded
= (1ULL << order
);
25 assert(rounded
>= val
);
31 void lttng_dynamic_buffer_init(struct lttng_dynamic_buffer
*buffer
)
34 memset(buffer
, 0, sizeof(*buffer
));
38 int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer
*buffer
,
39 const void *buf
, size_t len
)
43 if (!buffer
|| (!buf
&& len
)) {
49 /* Not an error, no-op. */
53 assert(buffer
->_capacity
>= buffer
->size
);
54 if (buffer
->_capacity
< (len
+ buffer
->size
)) {
55 ret
= lttng_dynamic_buffer_set_capacity(buffer
,
57 (len
- (buffer
->_capacity
- buffer
->size
)));
63 memcpy(buffer
->data
+ buffer
->size
, buf
, len
);
70 int lttng_dynamic_buffer_append_buffer(struct lttng_dynamic_buffer
*dst_buffer
,
71 struct lttng_dynamic_buffer
*src_buffer
)
75 if (!dst_buffer
|| !src_buffer
) {
80 ret
= lttng_dynamic_buffer_append(dst_buffer
, src_buffer
->data
,
87 int lttng_dynamic_buffer_set_size(struct lttng_dynamic_buffer
*buffer
,
96 if (new_size
== buffer
->size
) {
100 if (new_size
> buffer
->_capacity
) {
101 ret
= lttng_dynamic_buffer_set_capacity(buffer
, new_size
);
106 memset(buffer
->data
+ buffer
->size
, 0, new_size
- buffer
->size
);
107 } else if (new_size
> buffer
->size
) {
108 memset(buffer
->data
+ buffer
->size
, 0, new_size
- buffer
->size
);
111 * Shrinking size. There is no need to zero-out the newly
112 * released memory as it will either be:
113 * - overwritten by lttng_dynamic_buffer_append,
114 * - expanded later, which will zero-out the memory
116 * Users of external APIs are encouraged to set the buffer's
117 * size _before_ making such calls.
120 buffer
->size
= new_size
;
126 int lttng_dynamic_buffer_set_capacity(struct lttng_dynamic_buffer
*buffer
,
127 size_t demanded_capacity
)
131 size_t new_capacity
= demanded_capacity
?
132 round_to_power_of_2(demanded_capacity
) : 0;
134 if (!buffer
|| demanded_capacity
< buffer
->size
) {
136 * Shrinking a buffer's size by changing its capacity is
143 if (new_capacity
== buffer
->_capacity
) {
147 /* Memory is initialized by the size increases. */
148 new_buf
= realloc(buffer
->data
, new_capacity
);
153 buffer
->data
= new_buf
;
154 buffer
->_capacity
= new_capacity
;
159 /* Release any memory used by the dynamic buffer. */
161 void lttng_dynamic_buffer_reset(struct lttng_dynamic_buffer
*buffer
)
167 buffer
->_capacity
= 0;
172 size_t lttng_dynamic_buffer_get_capacity_left(
173 struct lttng_dynamic_buffer
*buffer
)
178 return buffer
->_capacity
- buffer
->size
;
This page took 0.034899 seconds and 4 git commands to generate.