bmv2
Designing your own switch target with bmv2
Loading...
Searching...
No Matches
packet_buffer.h
Go to the documentation of this file.
1/* Copyright 2013-present Barefoot Networks, Inc.
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
16/*
17 * Antonin Bas (antonin@barefootnetworks.com)
18 *
19 */
20
22
23#ifndef BM_BM_SIM_PACKET_BUFFER_H_
24#define BM_BM_SIM_PACKET_BUFFER_H_
25
26#include <memory>
27#include <algorithm> // for std::copy
28
29#include <cassert>
30
31namespace bm {
32
49 public:
50 struct state_t {
51 char *head;
52 size_t data_size;
53 };
54
55 public:
56 PacketBuffer() {}
57
58 explicit PacketBuffer(size_t size)
59 : size(size),
60 data_size(0),
61 buffer(std::unique_ptr<char[]>(new char[size])),
62 head(buffer.get() + size) {}
63
77 PacketBuffer(size_t size, const char *data, size_t data_size)
78 : size(size),
79 data_size(0),
80 buffer(std::unique_ptr<char[]>(new char[size])),
81 head(buffer.get() + size) {
82 std::copy(data, data + data_size, push(data_size));
83 }
84
85 char *start() const { return head; }
86
87 char *end() const { return buffer.get() + size; }
88
89 char *push(size_t bytes) {
90 assert(data_size + bytes <= size);
91 data_size += bytes;
92 head -= bytes;
93 return head;
94 }
95
96 char *pop(size_t bytes) {
97 assert(bytes <= data_size);
98 data_size -= bytes;
99 head += bytes;
100 return head;
101 }
102
103 const state_t save_state() const {
104 return {head, data_size};
105 }
106
107 void restore_state(const state_t &state) {
108 head = state.head;
109 data_size = state.data_size;
110 }
111
112 size_t get_data_size() const { return data_size; }
113
114 PacketBuffer clone(size_t end_bytes) const {
115 assert(end_bytes <= data_size);
116 PacketBuffer pb(size);
117 std::copy(end() - end_bytes, end(), pb.push(end_bytes));
118 return pb;
119 }
120
121 PacketBuffer(const PacketBuffer &other) = delete;
122 PacketBuffer &operator=(const PacketBuffer &other) = delete;
123
124 PacketBuffer(PacketBuffer &&other) /*noexcept*/ = default;
125 PacketBuffer &operator=(PacketBuffer &&other) /*noexcept*/ = default;
126
127 private:
128 size_t size{0};
129 size_t data_size{0};
130 std::unique_ptr<char[]> buffer{nullptr};
131 char *head{nullptr};
132};
133
134} // namespace bm
135
136#endif // BM_BM_SIM_PACKET_BUFFER_H_
Definition packet_buffer.h:48
PacketBuffer(size_t size, const char *data, size_t data_size)
Definition packet_buffer.h:77