blob.h revision a715cb1840f9a0c813c90707a351687f7a77950e
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#ifndef NVRAM_MESSAGES_BLOB_H_ 18#define NVRAM_MESSAGES_BLOB_H_ 19 20extern "C" { 21#include <stddef.h> 22#include <stdint.h> 23} 24 25#include <nvram/messages/compiler.h> 26 27namespace nvram { 28 29// A simple wrapper class holding binary data of fixed size. 30// 31// This is intended for use in restricted environments where there is no full 32// C++ standard library available and/or memory allocation failure must be 33// handled gracefully. 34class NVRAM_EXPORT Blob { 35 public: 36 Blob(); 37 ~Blob(); 38 39 // Blob is movable, but not copyable since the latter requires memory 40 // allocations, which can fail. 41 Blob(const Blob& other) = delete; 42 Blob& operator=(const Blob& other) = delete; 43 Blob(Blob&& other); 44 Blob& operator=(Blob&& other); 45 friend void swap(Blob& first, Blob& second); 46 47 uint8_t* data() { return data_; } 48 const uint8_t* data() const { return data_; } 49 50 size_t size() const { return size_; } 51 52 // Reallocate the underlying buffer to hold |size| bytes and copy in |data|. 53 // Returns true on success, false if memory allocation fails. Blob size and 54 // contents remain unchanged upon failure. 55 bool Assign(const void* data, size_t size) NVRAM_WARN_UNUSED_RESULT; 56 57 // Resize the blob to |size|. Existing data within the new |size| limit is 58 // retained. If |size| increases, new contents are unspecified. Returns true 59 // on success, false if memory allocation fails. Blob size and contents remain 60 // unchanged upon failure. 61 bool Resize(size_t size) NVRAM_WARN_UNUSED_RESULT; 62 63 private: 64 uint8_t* data_ = nullptr; 65 size_t size_ = 0; 66}; 67 68} // namespace nvram 69 70#endif // NVRAM_MESSAGES_BLOB_H_ 71