1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <nvram/messages/blob.h>
18
19 extern "C" {
20 #include <stdlib.h>
21 #include <string.h>
22 }
23
24 namespace nvram {
25
Blob()26 Blob::Blob() {}
27
~Blob()28 Blob::~Blob() {
29 free(data_);
30 data_ = nullptr;
31 size_ = 0;
32 }
33
Blob(Blob && other)34 Blob::Blob(Blob&& other) : Blob() {
35 swap(*this, other);
36 }
37
operator =(Blob && other)38 Blob& Blob::operator=(Blob&& other) {
39 swap(*this, other);
40 return *this;
41 }
42
swap(Blob & first,Blob & second)43 void swap(Blob& first, Blob& second) {
44 // This does not use std::swap since it needs to work in environments that are
45 // lacking a standard library.
46 uint8_t* data_tmp = first.data_;
47 size_t size_tmp = first.size_;
48 first.data_ = second.data_;
49 first.size_ = second.size_;
50 second.data_ = data_tmp;
51 second.size_ = size_tmp;
52 }
53
Assign(const void * data,size_t size)54 bool Blob::Assign(const void* data, size_t size) {
55 free(data_);
56 data_ = static_cast<uint8_t*>(malloc(size));
57 if (!data_) {
58 size_ = 0;
59 return false;
60 }
61 memcpy(data_, data, size);
62 size_ = size;
63 return true;
64 }
65
Resize(size_t size)66 bool Blob::Resize(size_t size) {
67 uint8_t* tmp_data = static_cast<uint8_t*>(realloc(data_, size));
68 if (size != 0 && !tmp_data) {
69 return false;
70 }
71
72 data_ = tmp_data;
73 size_ = size;
74 return true;
75 }
76
77 } // namespace nvram
78