1#include <stdio.h>
 2#include <stdlib.h>
 3
 4#include "allocator.h"
 5#include "ringbuffer.h"
 6
 7
 8bool srb_init(SyncRingBuffer* srb, unsigned size)
 9{
10    if (init_ringbuffer(&srb->ringbuf, size)) {
11        if (mtx_init(&srb->lock, mtx_plain) != thrd_success) {
12            fprintf(stderr, "%s cannot init mutex\n", __func__);
13        } else {
14            srb->more = create_event();
15            srb->less = create_event();
16            if (srb->more && srb->less) {
17                set_event(srb->less);  // the buffer is empty
18                return true;
19            }
20            delete_event(&srb->more);
21            delete_event(&srb->less);
22        }
23        fini_ringbuffer(&srb->ringbuf);
24    }
25    return false;
26}
27
28void srb_fini(SyncRingBuffer* srb)
29{
30    if (srb->ringbuf.data) {
31        mtx_destroy(&srb->lock);
32        delete_event(&srb->more);
33        delete_event(&srb->less);
34        fini_ringbuffer(&srb->ringbuf);
35    }
36}
37
38SyncRingBuffer* srb_create(unsigned size)
39{
40    SyncRingBuffer* srb = allocate(sizeof(SyncRingBuffer), true);
41    if (srb) {
42        if (srb_init(srb, size)) {
43            return srb;
44        }
45        release((void**) &srb, sizeof(SyncRingBuffer));
46    }
47    return nullptr;
48}
49
50void srb_delete(SyncRingBuffer** srb_ptr)
51{
52    SyncRingBuffer* srb = *srb_ptr;
53    if (srb) {
54        srb_fini(srb);
55        release((void**) &srb, sizeof(SyncRingBuffer));
56    }
57    *srb_ptr = nullptr;
58}
59
60bool srb_grow(SyncRingBuffer* srb, unsigned new_size)
61{
62    mtx_lock(&srb->lock);
63    bool result = grow_ringbuffer(&srb->ringbuf, new_size);
64    set_event(srb->less);
65    mtx_unlock(&srb->lock);
66    return result;
67}
68
69void srb_shrink(SyncRingBuffer* srb, unsigned new_size)
70{
71    mtx_lock(&srb->lock);
72    shrink_ringbuffer(&srb->ringbuf, new_size);
73    mtx_unlock(&srb->lock);
74}
75
76unsigned srb_read(SyncRingBuffer* srb, uint8_t* buffer, unsigned size)
77{
78    mtx_lock(&srb->lock);
79    unsigned result = read_ringbuffer(&srb->ringbuf, buffer, size);
80    set_event(srb->less);
81    mtx_unlock(&srb->lock);
82    return result;
83}
84
85bool srb_write(SyncRingBuffer* srb, uint8_t* data, unsigned size)
86{
87    mtx_lock(&srb->lock);
88    bool result = write_ringbuffer(&srb->ringbuf, data, size);
89    set_event(srb->more);
90    mtx_unlock(&srb->lock);
91    return result;
92}