blob.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include <nvram/messages/blob.h>
  17. extern "C" {
  18. #include <stdlib.h>
  19. #include <string.h>
  20. }
  21. namespace nvram {
  22. Blob::Blob() {}
  23. Blob::~Blob() {
  24. free(data_);
  25. data_ = nullptr;
  26. size_ = 0;
  27. }
  28. Blob::Blob(Blob&& other) : Blob() {
  29. swap(*this, other);
  30. }
  31. Blob& Blob::operator=(Blob&& other) {
  32. swap(*this, other);
  33. return *this;
  34. }
  35. void swap(Blob& first, Blob& second) {
  36. // This does not use std::swap since it needs to work in environments that are
  37. // lacking a standard library.
  38. uint8_t* data_tmp = first.data_;
  39. size_t size_tmp = first.size_;
  40. first.data_ = second.data_;
  41. first.size_ = second.size_;
  42. second.data_ = data_tmp;
  43. second.size_ = size_tmp;
  44. }
  45. bool Blob::Assign(const void* data, size_t size) {
  46. free(data_);
  47. data_ = static_cast<uint8_t*>(malloc(size));
  48. if (!data_) {
  49. size_ = 0;
  50. return false;
  51. }
  52. memcpy(data_, data, size);
  53. size_ = size;
  54. return true;
  55. }
  56. bool Blob::Resize(size_t size) {
  57. uint8_t* tmp_data = static_cast<uint8_t*>(realloc(data_, size));
  58. if (size != 0 && !tmp_data) {
  59. return false;
  60. }
  61. data_ = tmp_data;
  62. size_ = size;
  63. return true;
  64. }
  65. } // namespace nvram