1 /******************************************************************************
2  *
3  *  Copyright (C) 2017 Google Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #pragma once
20 
21 #include <stdint.h>
22 #include <sys/types.h>
23 
24 typedef struct ringbuffer_t ringbuffer_t;
25 
26 // NOTE:
27 // None of the functions below are thread safe when it comes to accessing the
28 // *rb pointer. It is *NOT* possible to insert and pop/delete at the same time.
29 // Callers must protect the *rb pointer separately.
30 
31 // Create a ringbuffer with the specified size
32 // Returns NULL if memory allocation failed. Resulting pointer must be freed
33 // using |ringbuffer_free|.
34 ringbuffer_t* ringbuffer_init(const size_t size);
35 
36 // Frees the ringbuffer structure and buffer
37 // Save to call with NULL.
38 void ringbuffer_free(ringbuffer_t* rb);
39 
40 // Returns remaining buffer size
41 size_t ringbuffer_available(const ringbuffer_t* rb);
42 
43 // Returns size of data in buffer
44 size_t ringbuffer_size(const ringbuffer_t* rb);
45 
46 // Attempts to insert up to |length| bytes of data at |p| into the buffer
47 // Return actual number of bytes added. Can be less than |length| if buffer
48 // is full.
49 size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length);
50 
51 // Peek |length| number of bytes from the ringbuffer, starting at |offset|,
52 // into the buffer |p|. Return the actual number of bytes peeked. Can be less
53 // than |length| if there is less than |length| data available. |offset| must
54 // be non-negative.
55 size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p,
56                        size_t length);
57 
58 // Does the same as |ringbuffer_peek|, but also advances the ring buffer head
59 size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length);
60 
61 // Deletes |length| bytes from the ringbuffer starting from the head
62 // Return actual number of bytes deleted.
63 size_t ringbuffer_delete(ringbuffer_t* rb, size_t length);
64