|
| 1 | +// |
| 2 | +// Copyright (c) 2021 Vinnie Falco (vinnie.falco@gmail.com) |
| 3 | +// |
| 4 | +// Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 5 | +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 6 | +// |
| 7 | +// Official repository: https://github.com/cppalliance/http_proto |
| 8 | +// |
| 9 | + |
| 10 | +#ifndef BOOST_HTTP_PROTO_STRING_BODY_HPP |
| 11 | +#define BOOST_HTTP_PROTO_STRING_BODY_HPP |
| 12 | + |
| 13 | +#include <boost/http_proto/detail/config.hpp> |
| 14 | +#include <boost/buffers/const_buffer.hpp> |
| 15 | +#include <string> |
| 16 | +#include <utility> |
| 17 | + |
| 18 | +namespace boost { |
| 19 | +namespace http_proto { |
| 20 | + |
| 21 | +/** A ConstBufferSequence adapter for an owned `std::string`. |
| 22 | +
|
| 23 | + Takes ownership of a `std::string` and exposes |
| 24 | + it via an interface conforming to the |
| 25 | + ConstBufferSequence requirements. |
| 26 | +
|
| 27 | + @par Example |
| 28 | + @code |
| 29 | + rts::context ctx; |
| 30 | + serializer sr(ctx); |
| 31 | + response res(status::not_found); |
| 32 | +
|
| 33 | + std::string body = |
| 34 | + "<html>" |
| 35 | + "<body>" |
| 36 | + " <h1>404 Not Found</h1>" |
| 37 | + " <p>Sorry, the page does not exist.</p>" |
| 38 | + "</body>" |
| 39 | + "</html>"; |
| 40 | + sr.start<string_body>(res, std::move(body)); |
| 41 | + @endcode |
| 42 | +
|
| 43 | + @see |
| 44 | + @ref serializer. |
| 45 | +*/ |
| 46 | +class string_body |
| 47 | +{ |
| 48 | + std::string s_; |
| 49 | + buffers::const_buffer cb_; |
| 50 | + |
| 51 | +public: |
| 52 | + /// The type for each buffer. |
| 53 | + using value_type = buffers::const_buffer; |
| 54 | + |
| 55 | + /// The type of a const iterator. |
| 56 | + using const_iterator = buffers::const_buffer const*; |
| 57 | + |
| 58 | + string_body( |
| 59 | + string_body&& other) noexcept |
| 60 | + : s_(std::move(other.s_)) |
| 61 | + , cb_(s_.data(), s_.size()) |
| 62 | + { |
| 63 | + other.cb_ = {}; |
| 64 | + } |
| 65 | + |
| 66 | + /** Constructor. |
| 67 | + */ |
| 68 | + string_body( |
| 69 | + string_body const& other) = delete; |
| 70 | + |
| 71 | + /** Constructor. |
| 72 | +
|
| 73 | + @param s The string to take ownership of. |
| 74 | + */ |
| 75 | + string_body( |
| 76 | + std::string s) noexcept |
| 77 | + : s_(std::move(s)) |
| 78 | + , cb_(s_.data(), s_.size()) |
| 79 | + { |
| 80 | + } |
| 81 | + |
| 82 | + /** Return an iterator to the beginning of the |
| 83 | + buffer sequence. |
| 84 | + */ |
| 85 | + const_iterator |
| 86 | + begin() const noexcept |
| 87 | + { |
| 88 | + return &cb_; |
| 89 | + } |
| 90 | + |
| 91 | + /** Return an iterator to the end of the |
| 92 | + buffer sequence. |
| 93 | + */ |
| 94 | + const_iterator |
| 95 | + end() const noexcept |
| 96 | + { |
| 97 | + return &cb_ + 1; |
| 98 | + } |
| 99 | +}; |
| 100 | + |
| 101 | +} // http_proto |
| 102 | +} // boost |
| 103 | + |
| 104 | +#endif |
0 commit comments