1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
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:
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 ******************************************************************************/
19 #define LOG_TAG "bt_osi_buffer"
24 #include "osi/include/allocator.h"
25 #include "osi/include/buffer.h"
26 #include "osi/include/log.h"
35 buffer_t *buffer_new(size_t size) {
38 buffer_t *buffer = osi_calloc(sizeof(buffer_t) + size);
40 LOG_ERROR("%s unable to allocate buffer of %zu bytes.", __func__, size);
44 buffer->root = buffer;
46 buffer->length = size;
51 buffer_t *buffer_new_ref(const buffer_t *buf) {
53 return buffer_new_slice(buf, buf->length);
56 buffer_t *buffer_new_slice(const buffer_t *buf, size_t slice_size) {
58 assert(slice_size > 0);
59 assert(slice_size <= buf->length);
61 buffer_t *ret = osi_calloc(sizeof(buffer_t));
63 LOG_ERROR("%s unable to allocate new buffer for slice of length %zu.", __func__, slice_size);
67 ret->root = buf->root;
68 ret->refcount = SIZE_MAX;
69 ret->length = slice_size;
71 ++buf->root->refcount;
76 void buffer_free(buffer_t *buffer) {
80 if (buffer->root != buffer) {
81 // We're a leaf node. Delete the root node if we're the last referent.
82 if (--buffer->root->refcount == 0)
83 osi_free(buffer->root);
85 } else if (--buffer->refcount == 0) {
86 // We're a root node. Roots are only deleted when their refcount goes to 0.
91 void *buffer_ptr(const buffer_t *buf) {
93 return buf->root->data + buf->root->length - buf->length;
96 size_t buffer_length(const buffer_t *buf) {