1 /******************************************************************************
2  *
3  *  Copyright (C) 2014 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 #ifndef _BUFFER_H_
20 #define _BUFFER_H_
21 
22 #include <stdbool.h>
23 #include <stddef.h>
24 
25 typedef struct buffer_t buffer_t;
26 
27 // Returns a new buffer of |size| bytes. Returns NULL if a buffer could not be
28 // allocated. |size| must be non-zero. The caller must release this buffer with
29 // |buffer_free|.
30 buffer_t *buffer_new(size_t size);
31 
32 // Creates a new reference to the buffer |buf|. A reference is indistinguishable
33 // from the original: writes to the original will be reflected in the reference
34 // and vice versa. In other words, this function creates an alias to |buf|. The
35 // caller must release the returned buffer with |buffer_free|. Note that releasing
36 // the returned buffer does not release |buf|. |buf| must not be NULL.
37 buffer_t *buffer_new_ref(const buffer_t *buf);
38 
39 // Creates a new reference to the last |slice_size| bytes of |buf|. See
40 // |buffer_new_ref| for a description of references. |slice_size| must be
41 // greater than 0 and may be at most |buffer_length|
42 // (0 < slice_size <= buffer_length). |buf| must not be NULL.
43 buffer_t *buffer_new_slice(const buffer_t *buf, size_t slice_size);
44 
45 // Frees a buffer object. |buf| may be NULL.
46 void buffer_free(buffer_t *buf);
47 
48 // Returns a pointer to a writeable memory region for |buf|. All references
49 // and slices that share overlapping bytes will also be written to when
50 // writing to the returned pointer. The caller may safely write up to
51 // |buffer_length| consecutive bytes starting at the address returned by
52 // this function. |buf| must not be NULL.
53 void *buffer_ptr(const buffer_t *buf);
54 
55 // Returns the length of the writeable memory region referred to by |buf|.
56 // |buf| must not be NULL.
57 size_t buffer_length(const buffer_t *buf);
58 
59 #endif /*_BUFFER_H_*/
60