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"
35 #include "src/shared/tester.h"
37 static unsigned int nlpo2(unsigned int x)
48 static unsigned int fls(unsigned int x)
50 return x ? sizeof(x) * 8 - __builtin_clz(x) : 0;
53 static unsigned int align_power2(unsigned int u)
55 return 1 << fls(u - 1);
58 static void test_power2(const void *data)
62 for (i = 1; i < 1000000; i++) {
63 size_t size1, size2, size3 = 1;
66 size2 = align_power2(i);
68 /* Find the next power of two */
69 while (size3 < i && size3 < SIZE_MAX)
72 tester_debug("%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);
83 static void test_alloc(const void *data)
87 for (i = 2; i < 10000; i++) {
90 tester_debug("Iteration %i\n", i);
95 g_assert(ringbuf_capacity(rb) == ringbuf_avail(rb));
100 tester_test_passed();
103 static void test_printf(const void *data)
105 static size_t rb_size = 500;
106 static size_t rb_capa = 512;
110 rb = ringbuf_new(rb_size);
111 g_assert(rb != NULL);
112 g_assert(ringbuf_capacity(rb) == rb_capa);
114 for (i = 0; i < 10000; i++) {
115 size_t len, count = i % rb_capa;
121 tester_debug("Iteration %i\n", i);
123 len = asprintf(&str, "%*c", (int) count, 'x');
124 g_assert(len == count);
126 len = ringbuf_printf(rb, "%s", str);
127 g_assert(len == count);
128 g_assert(ringbuf_len(rb) == count);
129 g_assert(ringbuf_avail(rb) == rb_capa - len);
131 ptr = ringbuf_peek(rb, 0, &len);
132 g_assert(ptr != NULL);
133 g_assert(len == count);
134 g_assert(strncmp(str, ptr, len) == 0);
136 len = ringbuf_drain(rb, count);
137 g_assert(len == count);
138 g_assert(ringbuf_len(rb) == 0);
139 g_assert(ringbuf_avail(rb) == rb_capa);
145 tester_test_passed();
148 int main(int argc, char *argv[])
150 tester_init(&argc, &argv);
152 tester_add("/ringbuf/power2", NULL, NULL, test_power2, NULL);
153 tester_add("/ringbuf/alloc", NULL, NULL, test_alloc, NULL);
154 tester_add("/ringbuf/printf", NULL, NULL, test_printf, NULL);