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