1 // Copyright 2016 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef LIB_ZX_SOCKET_H_
6 #define LIB_ZX_SOCKET_H_
7 
8 #include <lib/zx/handle.h>
9 #include <lib/zx/object.h>
10 
11 namespace zx {
12 
13 class socket : public object<socket> {
14 public:
15     static constexpr zx_obj_type_t TYPE = ZX_OBJ_TYPE_SOCKET;
16 
17     constexpr socket() = default;
18 
socket(zx_handle_t value)19     explicit socket(zx_handle_t value) : object(value) {}
20 
socket(handle && h)21     explicit socket(handle&& h) : object(h.release()) {}
22 
socket(socket && other)23     socket(socket&& other) : object(other.release()) {}
24 
25     socket& operator=(socket&& other) {
26         reset(other.release());
27         return *this;
28     }
29 
30     static zx_status_t create(uint32_t options, socket* endpoint0,
31                               socket* endpoint1);
32 
write(uint32_t options,const void * buffer,size_t len,size_t * actual)33     zx_status_t write(uint32_t options, const void* buffer, size_t len,
34                       size_t* actual) const {
35         return zx_socket_write(get(), options, buffer, len, actual);
36     }
37 
read(uint32_t options,void * buffer,size_t len,size_t * actual)38     zx_status_t read(uint32_t options, void* buffer, size_t len,
39                      size_t* actual) const {
40         return zx_socket_read(get(), options, buffer, len, actual);
41     }
42 
share(socket socket_to_share)43     zx_status_t share(socket socket_to_share) const {
44         return zx_socket_share(get(), socket_to_share.release());
45     }
46 
accept(socket * out_socket)47     zx_status_t accept(socket* out_socket) const {
48         // We use a temporary to handle the case where |this| and |out_socket|
49         // are aliased.
50         socket result;
51         zx_status_t status = zx_socket_accept(get(), result.reset_and_get_address());
52         out_socket->reset(result.release());
53         return status;
54     }
55 
shutdown(uint32_t options)56     zx_status_t shutdown(uint32_t options) const {
57         return zx_socket_shutdown(get(), options);
58     }
59 };
60 
61 using unowned_socket = unowned<socket>;
62 
63 } // namespace zx
64 
65 #endif  // LIB_ZX_SOCKET_H_
66