Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_rpc / public / pw_rpc / internal / channel.h
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15
16 #include <span>
17
18 #include "pw_rpc/channel.h"
19 #include "pw_status/status.h"
20
21 namespace pw::rpc::internal {
22
23 class Packet;
24
25 class Channel : public rpc::Channel {
26  public:
27   Channel() = delete;
28
29   constexpr Channel(uint32_t id, ChannelOutput* output)
30       : rpc::Channel(id, output) {}
31
32   class OutputBuffer {
33    public:
34     constexpr OutputBuffer() = default;
35
36     OutputBuffer(const OutputBuffer&) = delete;
37
38     OutputBuffer(OutputBuffer&& other) { *this = std::move(other); }
39
40     ~OutputBuffer() { PW_DCHECK(buffer_.empty()); }
41
42     OutputBuffer& operator=(const OutputBuffer&) = delete;
43
44     OutputBuffer& operator=(OutputBuffer&& other) {
45       PW_DCHECK(buffer_.empty());
46       buffer_ = other.buffer_;
47       other.buffer_ = {};
48       return *this;
49     }
50
51     // Returns a portion of this OutputBuffer to use as the packet payload.
52     std::span<std::byte> payload(const Packet& packet) const;
53
54     bool Contains(std::span<const std::byte> buffer) const {
55       return buffer.data() >= buffer_.data() &&
56              buffer.data() + buffer.size() <= buffer_.data() + buffer_.size();
57     }
58
59     bool empty() const { return buffer_.empty(); }
60
61    private:
62     friend class Channel;
63
64     explicit constexpr OutputBuffer(std::span<std::byte> buffer)
65         : buffer_(buffer) {}
66
67     std::span<std::byte> buffer_;
68   };
69
70   // Acquires a buffer for the packet.
71   OutputBuffer AcquireBuffer() const {
72     return OutputBuffer(output().AcquireBuffer());
73   }
74
75   Status Send(const internal::Packet& packet) {
76     OutputBuffer buffer = AcquireBuffer();
77     return Send(buffer, packet);
78   }
79
80   Status Send(OutputBuffer& output, const internal::Packet& packet);
81
82   void Release(OutputBuffer& buffer) {
83     output().DiscardBuffer(buffer.buffer_);
84     buffer.buffer_ = {};
85   }
86 };
87
88 }  // namespace pw::rpc::internal