Wyatt Hepler | cb9d957 | 2020-06-01 11:25:58 -0700 | [diff] [blame^] | 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 | |
| 15 | #include "pw_rpc/internal/base_server_writer.h" |
| 16 | |
| 17 | #include "pw_assert/assert.h" |
| 18 | #include "pw_rpc/internal/method.h" |
| 19 | #include "pw_rpc/internal/packet.h" |
| 20 | #include "pw_rpc/server.h" |
| 21 | |
| 22 | namespace pw::rpc::internal { |
| 23 | |
| 24 | BaseServerWriter& BaseServerWriter::operator=(BaseServerWriter&& other) { |
| 25 | context_ = std::move(other.context_); |
| 26 | response_ = std::move(other.response_); |
| 27 | state_ = std::move(other.state_); |
| 28 | other.state_ = kClosed; |
| 29 | return *this; |
| 30 | } |
| 31 | |
| 32 | void BaseServerWriter::close() { |
| 33 | if (open()) { |
| 34 | // TODO(hepler): Send a control packet indicating that the stream has |
| 35 | // terminated, and remove this ServerWriter from the Server's list. |
| 36 | |
| 37 | state_ = kClosed; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | span<std::byte> BaseServerWriter::AcquireBuffer() { |
| 42 | if (!open()) { |
| 43 | return {}; |
| 44 | } |
| 45 | |
| 46 | PW_DCHECK(response_.empty()); |
| 47 | response_ = context_.channel_->AcquireBuffer(); |
| 48 | |
| 49 | // Reserve space for the RPC packet header. |
| 50 | return packet().PayloadUsableSpace(response_); |
| 51 | } |
| 52 | |
| 53 | Status BaseServerWriter::SendAndReleaseBuffer(span<const std::byte> payload) { |
| 54 | if (!open()) { |
| 55 | return Status::FAILED_PRECONDITION; |
| 56 | } |
| 57 | |
| 58 | Packet response_packet = packet(); |
| 59 | response_packet.set_payload(payload); |
| 60 | StatusWithSize encoded = response_packet.Encode(response_); |
| 61 | response_ = {}; |
| 62 | |
| 63 | if (!encoded.ok()) { |
| 64 | context_.channel_->SendAndReleaseBuffer(0); |
| 65 | return Status::INTERNAL; |
| 66 | } |
| 67 | |
| 68 | // TODO(hepler): Should Channel::SendAndReleaseBuffer return Status? |
| 69 | context_.channel_->SendAndReleaseBuffer(encoded.size()); |
| 70 | return Status::OK; |
| 71 | } |
| 72 | |
| 73 | Packet BaseServerWriter::packet() const { |
| 74 | return Packet(PacketType::RPC, |
| 75 | context_.channel_id(), |
| 76 | context_.service_->id(), |
| 77 | method().id()); |
| 78 | } |
| 79 | |
| 80 | } // namespace pw::rpc::internal |