1 // Copyright 2016 The Fuchsia Authors
2 // Copyright (c) 2009-2013 Travis Geiselbrecht
3 //
4 // Use of this source code is governed by a MIT-style
5 // license that can be found in the LICENSE file or at
6 // https://opensource.org/licenses/MIT
7 
8 #pragma once
9 
10 #include <kernel/event.h>
11 #include <kernel/spinlock.h>
12 #include <sys/types.h>
13 #include <zircon/compiler.h>
14 
15 __BEGIN_CDECLS
16 
17 typedef struct cbuf {
18     uint head;
19     uint tail;
20     uint len_pow2;
21     char* buf;
22     event_t event;
23     spin_lock_t lock;
24 } cbuf_t;
25 
26 /**
27  * cbuf_initialize
28  *
29  * Initialize a cbuf structure, mallocing the underlying data buffer in the
30  * process.  Make sure that the buffer has enough space for at least len bytes.
31  *
32  * @param[in] cbuf A pointer to the cbuf structure to allocate.
33  * @param[in] len The minimum number of bytes for the underlying data buffer.
34  */
35 void cbuf_initialize(cbuf_t* cbuf, size_t len);
36 
37 /**
38  * cbuf_initialize_etc
39  *
40  * Initialize a cbuf structure using the supplied buffer for internal storage.
41  *
42  * @param[in] cbuf A pointer to the cbuf structure to allocate.
43  * @param[in] len The size of the supplied buffer, in bytes.
44  * @param[in] buf A pointer to the memory to be used for internal storage.
45  */
46 void cbuf_initialize_etc(cbuf_t* cbuf, size_t len, void* buf);
47 
48 /**
49  * cbuf_space_avail
50  *
51  * @param[in] cbuf The cbuf instance to query
52  *
53  * @return The number of free space available in the cbuf (IOW - the maximum
54  * number of bytes which can currently be written)
55  */
56 size_t cbuf_space_avail(const cbuf_t* cbuf);
57 
58 /* special cases for dealing with a single char of data */
59 size_t cbuf_read_char(cbuf_t* cbuf, char* c, bool block);
60 size_t cbuf_write_char(cbuf_t* cbuf, char c);
61 
62 __END_CDECLS
63