Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_stream / socket_stream.cc
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_stream/socket_stream.h"
16 namespace pw::stream {
17
18 static constexpr uint32_t kMaxConcurrentUser = 1;
19
20 // Listen to the port and return after a client is connected
21 Status SocketStream::Init(uint16_t port) {
22   listen_port_ = port;
23   socket_fd_ = socket(AF_INET, SOCK_STREAM, 0);
24   if (socket_fd_ == kInvalidFd) {
25     return Status::Internal();
26   }
27
28   struct sockaddr_in addr;
29   addr.sin_family = AF_INET;
30   addr.sin_port = htons(listen_port_);
31   addr.sin_addr.s_addr = INADDR_ANY;
32
33   int result =
34       bind(socket_fd_, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr));
35   if (result < 0) {
36     return Status::Internal();
37   }
38
39   result = listen(socket_fd_, kMaxConcurrentUser);
40   if (result < 0) {
41     return Status::Internal();
42   }
43
44   socklen_t len = sizeof(sockaddr_client_);
45
46   conn_fd_ =
47       accept(socket_fd_, reinterpret_cast<sockaddr*>(&sockaddr_client_), &len);
48   if (conn_fd_ < 0) {
49     return Status::Internal();
50   }
51   return OkStatus();
52 }
53
54 Status SocketStream::DoWrite(std::span<const std::byte> data) {
55   ssize_t bytes_sent = send(conn_fd_, data.data(), data.size_bytes(), 0);
56
57   if (bytes_sent < 0 || static_cast<uint64_t>(bytes_sent) != data.size()) {
58     return Status::Internal();
59   }
60   return OkStatus();
61 }
62
63 StatusWithSize SocketStream::DoRead(ByteSpan dest) {
64   ssize_t bytes_rcvd = recv(conn_fd_, dest.data(), dest.size_bytes(), 0);
65   if (bytes_rcvd < 0) {
66     return StatusWithSize::Internal();
67   }
68   return StatusWithSize(bytes_rcvd);
69 }
70
71 };  // namespace pw::stream