serializable.cc 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "serializable.h"
  5. #include <utility>
  6. namespace crdtp {
  7. // =============================================================================
  8. // Serializable - An object to be emitted as a sequence of bytes.
  9. // =============================================================================
  10. std::vector<uint8_t> Serializable::Serialize() const {
  11. std::vector<uint8_t> out;
  12. AppendSerialized(&out);
  13. return out;
  14. }
  15. namespace {
  16. class PreSerialized : public Serializable {
  17. public:
  18. explicit PreSerialized(std::vector<uint8_t> bytes)
  19. : bytes_(std::move(bytes)) {}
  20. void AppendSerialized(std::vector<uint8_t>* out) const override {
  21. out->insert(out->end(), bytes_.begin(), bytes_.end());
  22. }
  23. private:
  24. std::vector<uint8_t> bytes_;
  25. };
  26. } // namespace
  27. // static
  28. std::unique_ptr<Serializable> Serializable::From(std::vector<uint8_t> bytes) {
  29. return std::make_unique<PreSerialized>(std::move(bytes));
  30. }
  31. } // namespace crdtp