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