Action Engine
Loading...
Searching...
No Matches
msgpack.h
1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef ACTIONENGINE_MSGPACK_MSGPACK_H
16#define ACTIONENGINE_MSGPACK_MSGPACK_H
17
18#include <cstddef>
19#include <string_view>
20#include <utility>
21#include <vector>
22
23#include <absl/status/status.h>
24
25// IWYU pragma: begin_exports
26#include "actionengine/msgpack/array.h"
27#include "actionengine/msgpack/core_helpers.h"
28#include "actionengine/msgpack/float.h"
29#include "actionengine/msgpack/int.h"
30#include "actionengine/msgpack/misc.h"
31#include "actionengine/msgpack/strbin.h"
32
33// IWYU pragma: end_exports
34
35namespace act::msgpack {
36
37class Packer {
38 public:
39 explicit Packer(SerializedBytesVector bytes = {});
40
41 template <typename T>
42 absl::Status Pack(const T& value) {
43 InsertInfo insert{&bytes_, bytes_.end()};
44 return EgltMsgpackSerialize(value, insert);
45 }
46
47 template <typename T>
48 absl::Status Unpack(T& destination) {
49 if (offset_ >= bytes_.size()) {
50 return absl::InvalidArgumentError("Offset is out of bounds.");
51 }
52 const auto pos = bytes_.data() + offset_;
53 const auto end = bytes_.data() + bytes_.size();
54 auto deserialized_extent =
55 Deserialize<T>(LookupPointer(pos, end), &destination);
56 if (!deserialized_extent.ok()) {
57 return deserialized_extent.status();
58 }
59 offset_ += *deserialized_extent;
60 return absl::OkStatus();
61 }
62
63 void Reset();
64
65 void Reserve(size_t size);
66
67 [[nodiscard]] const SerializedBytesVector& GetVector() const;
68
69 [[nodiscard]] std::vector<Byte> GetStdVector() const;
70
71 SerializedBytesVector ReleaseVector();
72
73 std::vector<Byte> ReleaseStdVector();
74
75 private:
76 SerializedBytesVector bytes_;
77 size_t offset_ = 0;
78};
79
80} // namespace act::msgpack
81
82#endif // ACTIONENGINE_MSGPACK_MSGPACK_H