1 /*
2 * Copyright (c) 2012 Travis Geiselbrecht
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23 #include <debug.h>
24 #include <assert.h>
25 #include <err.h>
26 #include <pow2.h>
27 #include <stdlib.h>
28 #include <lib/evlog.h>
29
30 #define INCPTR(e, ptr, inc) \
31 modpow2((ptr) + (inc), (e)->len_pow2)
32
evlog_init_etc(evlog_t * e,uint len,uint unitsize,uintptr_t * items)33 status_t evlog_init_etc(evlog_t *e, uint len, uint unitsize, uintptr_t *items)
34 {
35 if (len < 2 || !ispow2(len)) {
36 return ERR_INVALID_ARGS;
37 }
38 if (unitsize < 1 || !ispow2(unitsize)) {
39 return ERR_INVALID_ARGS;
40 }
41 if (unitsize > len) {
42 return ERR_INVALID_ARGS;
43 }
44
45 e->head = 0;
46 e->unitsize = unitsize;
47 e->len_pow2 = log2_uint(len);
48 e->items = items;
49
50 return NO_ERROR;
51 }
52
evlog_init(evlog_t * e,uint len,uint unitsize)53 status_t evlog_init(evlog_t *e, uint len, uint unitsize)
54 {
55 uintptr_t *items = calloc(1, len * sizeof(uintptr_t));
56 if (!items) {
57 return ERR_NO_MEMORY;
58 }
59
60 status_t err = evlog_init_etc(e, len, unitsize, items);
61 if (err < 0)
62 free(items);
63 return err;
64 }
65
evlog_bump_head(evlog_t * e)66 uint evlog_bump_head(evlog_t *e)
67 {
68 uint index = e->head;
69 e->head = INCPTR(e, e->head, e->unitsize);
70
71 return index;
72 }
73
evlog_dump(evlog_t * e,evlog_dump_cb cb)74 void evlog_dump(evlog_t *e, evlog_dump_cb cb)
75 {
76 for (uint index = INCPTR(e, e->head, e->unitsize); index != e->head; index = INCPTR(e, index, e->unitsize)) {
77 cb(&e->items[index]);
78 }
79 }
80
81
82