1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ 2 /* 3 * Copyright 2015 Couchbase, 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 #include "config.h" 18 #include "dynamic_buffer.h" 19 20 #include <platform/cb_malloc.h> 21 grow(size_t needed)22bool DynamicBuffer::grow(size_t needed) { 23 size_t nsize = size; 24 size_t available = nsize - offset; 25 bool rv = true; 26 27 /* Special case: No buffer -- need to allocate fresh */ 28 if (buffer == NULL) { 29 nsize = 1024; 30 available = size = offset = 0; 31 } 32 33 while (needed > available) { 34 cb_assert(nsize > 0); 35 nsize = nsize << 1; 36 available = nsize - offset; 37 } 38 39 if (nsize != size) { 40 char* ptr = reinterpret_cast<char*>(cb_realloc(buffer, nsize)); 41 if (ptr) { 42 buffer = ptr; 43 size = nsize; 44 } else { 45 rv = false; 46 } 47 } 48 49 return rv; 50 } 51 clear()52void DynamicBuffer::clear() { 53 cb_free(buffer); 54 buffer = nullptr; 55 size = 0; 56 offset = 0; 57 } 58