1/*
2 * Copyright 2016, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(D61_BSD)
11 */
12
13#include <data_struct/cqueue.h>
14#include <assert.h>
15#include <stdio.h>
16
17void cqueue_init(cqueue_t *q, uint32_t maxSize) {
18    assert(q);
19    q->data = kmalloc(sizeof(cqueue_item_t) * maxSize);
20    assert(q->data);
21    q->top = 0;
22    q->count = 0;
23    q->maxSize = maxSize;
24}
25
26bool cqueue_push(cqueue_t *q, cqueue_item_t e) {
27    assert(q && q->data);
28    while (q->count >= q->maxSize) {
29        return false;
30    }
31    q->data[q->top] = e;
32    q->top = (q->top + 1) % q->maxSize;
33    q->count++;
34    return true;
35}
36
37cqueue_item_t cqueue_pop(cqueue_t *q) {
38    assert(q && q->data);
39    if (q->count == 0) {
40        return (cqueue_item_t) NULL;
41    }
42    uint32_t bot = (q->top >= q->count) ? (q->top - q->count) : (q->maxSize - (q->count - q->top));
43    assert(bot < q->maxSize);
44    cqueue_item_t item =  q->data[bot];
45    q->count--;
46    return item;
47}
48
49void cqueue_free(cqueue_t *q) {
50    if (q->data) {
51        kfree(q->data);
52        q->data = NULL;
53    }
54    q->top = 0;
55    q->count = 0;
56    q->maxSize = 0;
57}