1 /* 2 * Copyright (C) 2020 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 #pragma once 18 19 #include <sys/types.h> 20 21 #include <algorithm> 22 #include <memory> 23 24 // This class is used instead of std::string or std::vector because their clear(), erase(), etc 25 // functions don't actually deallocate. shrink_to_fit() does deallocate but is not guaranteed to 26 // work and swapping with an empty string/vector is clunky. 27 class SerializedData { 28 public: SerializedData()29 SerializedData() {} SerializedData(size_t size)30 SerializedData(size_t size) : data_(new uint8_t[size]), size_(size) {} 31 Resize(size_t new_size)32 void Resize(size_t new_size) { 33 if (size_ == 0) { 34 data_.reset(new uint8_t[new_size]); 35 size_ = new_size; 36 } else if (new_size == 0) { 37 data_.reset(); 38 size_ = 0; 39 } else if (new_size != size_) { 40 std::unique_ptr<uint8_t[]> new_data(new uint8_t[new_size]); 41 size_t copy_size = std::min(size_, new_size); 42 memcpy(new_data.get(), data_.get(), copy_size); 43 data_.swap(new_data); 44 size_ = new_size; 45 } 46 } 47 data()48 uint8_t* data() { return data_.get(); } data()49 const uint8_t* data() const { return data_.get(); } size()50 size_t size() const { return size_; } 51 52 private: 53 std::unique_ptr<uint8_t[]> data_; 54 size_t size_ = 0; 55 };