• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 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 #define LOG_TAG "bt_osi_buffer"
20 
21 #include "osi/include/buffer.h"
22 
23 #include <base/logging.h>
24 #include <stdint.h>
25 
26 #include "check.h"
27 #include "osi/include/allocator.h"
28 #include "osi/include/log.h"
29 
30 struct buffer_t {
31   buffer_t* root;
32   size_t refcount;
33   size_t length;
34   uint8_t data[];
35 };
36 
buffer_new(size_t size)37 buffer_t* buffer_new(size_t size) {
38   CHECK(size > 0);
39 
40   buffer_t* buffer =
41       static_cast<buffer_t*>(osi_calloc(sizeof(buffer_t) + size));
42 
43   buffer->root = buffer;
44   buffer->refcount = 1;
45   buffer->length = size;
46 
47   return buffer;
48 }
49 
buffer_new_ref(const buffer_t * buf)50 buffer_t* buffer_new_ref(const buffer_t* buf) {
51   CHECK(buf != NULL);
52   return buffer_new_slice(buf, buf->length);
53 }
54 
buffer_new_slice(const buffer_t * buf,size_t slice_size)55 buffer_t* buffer_new_slice(const buffer_t* buf, size_t slice_size) {
56   CHECK(buf != NULL);
57   CHECK(slice_size > 0);
58   CHECK(slice_size <= buf->length);
59 
60   buffer_t* ret = static_cast<buffer_t*>(osi_calloc(sizeof(buffer_t)));
61 
62   ret->root = buf->root;
63   ret->refcount = SIZE_MAX;
64   ret->length = slice_size;
65 
66   ++buf->root->refcount;
67 
68   return ret;
69 }
70 
buffer_free(buffer_t * buffer)71 void buffer_free(buffer_t* buffer) {
72   if (!buffer) return;
73 
74   if (buffer->root != buffer) {
75     // We're a leaf node. Delete the root node if we're the last referent.
76     if (--buffer->root->refcount == 0) osi_free(buffer->root);
77     osi_free(buffer);
78   } else if (--buffer->refcount == 0) {
79     // We're a root node. Roots are only deleted when their refcount goes to 0.
80     osi_free(buffer);
81   }
82 }
83 
buffer_ptr(const buffer_t * buf)84 void* buffer_ptr(const buffer_t* buf) {
85   CHECK(buf != NULL);
86   return buf->root->data + buf->root->length - buf->length;
87 }
88 
buffer_length(const buffer_t * buf)89 size_t buffer_length(const buffer_t* buf) {
90   CHECK(buf != NULL);
91   return buf->length;
92 }
93