3 * BlueZ - Bluetooth protocol stack for Linux
5 * Copyright (C) 2012 Intel Corporation. All rights reserved.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
34 #include "src/shared/ringbuf.h"
36 static unsigned int nlpo2(unsigned int x)
47 static unsigned int fls(unsigned int x)
49 return x ? sizeof(x) * 8 - __builtin_clz(x) : 0;
52 static unsigned int align_power2(unsigned int u)
54 return 1 << fls(u - 1);
57 static void test_power2(void)
61 for (i = 1; i < 1000000; i++) {
62 size_t size1, size2, size3 = 1;
65 size2 = align_power2(i);
67 /* Find the next power of two */
68 while (size3 < i && size3 < SIZE_MAX)
72 g_print("%zu -> size1=%zu size2=%zu size3=%zu\n",
73 i, size1, size2, size3);
75 g_assert(size1 == size2);
76 g_assert(size2 == size3);
77 g_assert(size3 == size1);
81 static void test_alloc(void)
85 for (i = 2; i < 10000; i++) {
89 g_print("Iteration %i\n", i);
94 g_assert(ringbuf_capacity(rb) == ringbuf_avail(rb));
100 static void test_printf(void)
102 static size_t rb_size = 500;
103 static size_t rb_capa = 512;
107 rb = ringbuf_new(rb_size);
108 g_assert(rb != NULL);
109 g_assert(ringbuf_capacity(rb) == rb_capa);
111 for (i = 0; i < 10000; i++) {
112 size_t len, count = i % rb_capa;
118 if (g_test_verbose())
119 g_print("Iteration %i\n", i);
121 len = asprintf(&str, "%*c", (int) count, 'x');
122 g_assert(len == count);
124 len = ringbuf_printf(rb, "%s", str);
125 g_assert(len == count);
126 g_assert(ringbuf_len(rb) == count);
127 g_assert(ringbuf_avail(rb) == rb_capa - len);
129 ptr = ringbuf_peek(rb, 0, &len);
130 g_assert(ptr != NULL);
131 g_assert(len == count);
132 g_assert(strncmp(str, ptr, len) == 0);
134 len = ringbuf_drain(rb, count);
135 g_assert(len == count);
136 g_assert(ringbuf_len(rb) == 0);
137 g_assert(ringbuf_avail(rb) == rb_capa);
145 int main(int argc, char *argv[])
147 g_test_init(&argc, &argv, NULL);
149 g_test_add_func("/ringbuf/power2", test_power2);
150 g_test_add_func("/ringbuf/alloc", test_alloc);
151 g_test_add_func("/ringbuf/printf", test_printf);