FiberIO
Fiber-based C++ network library
iostream.hpp
Go to the documentation of this file.
1 #ifndef _FIBERIO_IOSTREAM_HPP_
2 #define _FIBERIO_IOSTREAM_HPP_
3 
4 #include <fiberio/socket.hpp>
5 #include <iostream>
6 #include <memory>
7 #include <boost/iostreams/concepts.hpp>
8 #include <boost/iostreams/stream_buffer.hpp>
9 #include <boost/iostreams/stream.hpp>
10 
11 namespace fiberio {
12 
13 namespace detail {
14 
16  public boost::iostreams::device<boost::iostreams::bidirectional>
17 {
18 public:
20  : socket_{ socket }, closed_in_{false}, closed_out_{false}
21  {}
22 
23  std::streamsize read(char* s, std::streamsize n) {
24  std::streamsize bytes_read = 0;
25  while(socket_.is_open() && bytes_read < n) {
26  bytes_read += socket_.read(s + bytes_read, n - bytes_read);
27  }
28  return bytes_read;
29  }
30 
31  std::streamsize write(const char* s, std::streamsize n) {
32  socket_.write(s, n);
33  return n;
34  }
35 
36  void close(std::ios_base::openmode mode) {
37  if (mode == std::ios_base::out) {
38  closed_out_ = true;
39  } else if (mode == std::ios_base::in) {
40  closed_in_ = true;
41  }
42  if (closed_in_ && closed_out_) {
43  socket_.close();
44  }
45  }
46 
47 private:
48  socket socket_;
49  bool closed_in_ : 1;
50  bool closed_out_ : 1;
51 };
52 
53 }
54 
60 using socket_stream = boost::iostreams::stream<fiberio::detail::socket_device>;
61 
67 using socket_streambuf =
68  boost::iostreams::stream_buffer<fiberio::detail::socket_device>;
69 
70 }
71 
72 #endif
void close()
Closes the socket if it&#39;s not already closed.
boost::iostreams::stream_buffer< fiberio::detail::socket_device > socket_streambuf
std::basic_streambuf type for reading/writing to a socket
Definition: iostream.hpp:68
boost::iostreams::stream< fiberio::detail::socket_device > socket_stream
std::basic_iostream type for reading/writing to a socket
Definition: iostream.hpp:60
Client socket for communicating over a network and opening connections.
Definition: socket.hpp:12
std::size_t read(char *buf, std::size_t size)
Reads up to size bytes into buf.
void write(const char *data, std::size_t len)
Writes data from the buffer and returns once the buffer can be freed.
std::streamsize read(char *s, std::streamsize n)
Definition: iostream.hpp:23
void close(std::ios_base::openmode mode)
Definition: iostream.hpp:36
bool is_open()
Check if the connection is open.
std::streamsize write(const char *s, std::streamsize n)
Definition: iostream.hpp:31
socket_device(socket socket)
Definition: iostream.hpp:19