1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3  *     Copyright 2017 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 
18 #include "blob.h"
19 
20 #include "objectregistry.h"
21 
22 #include <cstring>
23 
New(const char* start, const size_t len)24 Blob* Blob::New(const char* start, const size_t len) {
25     size_t total_len = getAllocationSize(len);
26     Blob* t = new (::operator new(total_len)) Blob(start, len);
27     return t;
28 }
29 
New(const size_t len)30 Blob* Blob::New(const size_t len) {
31     size_t total_len = getAllocationSize(len);
32     Blob* t = new (::operator new(total_len)) Blob(len);
33     return t;
34 }
35 
Copy(const Blob& other)36 Blob* Blob::Copy(const Blob& other) {
37     Blob* t = new (::operator new(Blob::getAllocationSize(other.valueSize())))
38             Blob(other);
39     return t;
40 }
41 
Blob(const char* start, const size_t len)42 Blob::Blob(const char* start, const size_t len)
43     : size(static_cast<uint32_t>(len)), age(0) {
44     if (start != NULL) {
45         std::memcpy(data, start, len);
46 #ifdef VALGRIND
47     } else {
48         memset(data, 0, len);
49 #endif
50     }
51     ObjectRegistry::onCreateBlob(this);
52 }
53 
Blob(const size_t len)54 Blob::Blob(const size_t len) : Blob(nullptr, len) {
55 }
56 
Blob(const Blob& other)57 Blob::Blob(const Blob& other)
58     : size(other.size.load()),
59       // While this is a copy, it is a new allocation therefore reset age.
60       age(0) {
61     std::memcpy(data, other.data, other.valueSize());
62     ObjectRegistry::onCreateBlob(this);
63 }
64 
to_s() const65 const std::string Blob::to_s() const {
66     return std::string(data, valueSize());
67 }
68 
~Blob()69 Blob::~Blob() {
70     ObjectRegistry::onDeleteBlob(this);
71 }
72