basic_parser.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot 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/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_HTTP_IMPL_BASIC_PARSER_HPP
  10. #define BOOST_BEAST_HTTP_IMPL_BASIC_PARSER_HPP
  11. #include <boost/beast/core/buffer_traits.hpp>
  12. #include <boost/asio/buffer.hpp>
  13. #include <boost/make_unique.hpp>
  14. namespace boost {
  15. namespace beast {
  16. namespace http {
  17. template<bool isRequest>
  18. template<class ConstBufferSequence>
  19. std::size_t
  20. basic_parser<isRequest>::
  21. put(ConstBufferSequence const& buffers,
  22. error_code& ec)
  23. {
  24. static_assert(net::is_const_buffer_sequence<
  25. ConstBufferSequence>::value,
  26. "ConstBufferSequence type requirements not met");
  27. auto const p = net::buffer_sequence_begin(buffers);
  28. auto const last = net::buffer_sequence_end(buffers);
  29. if(p == last)
  30. {
  31. ec = {};
  32. return 0;
  33. }
  34. if(std::next(p) == last)
  35. {
  36. // single buffer
  37. return put(net::const_buffer(*p), ec);
  38. }
  39. auto const size = buffer_bytes(buffers);
  40. if(size <= max_stack_buffer)
  41. return put_from_stack(size, buffers, ec);
  42. if(size > buf_len_)
  43. {
  44. // reallocate
  45. buf_ = boost::make_unique_noinit<char[]>(size);
  46. buf_len_ = size;
  47. }
  48. // flatten
  49. net::buffer_copy(net::buffer(
  50. buf_.get(), size), buffers);
  51. return put(net::const_buffer{
  52. buf_.get(), size}, ec);
  53. }
  54. template<bool isRequest>
  55. boost::optional<std::uint64_t>
  56. basic_parser<isRequest>::
  57. content_length_unchecked() const
  58. {
  59. if(f_ & flagContentLength)
  60. return len0_;
  61. return boost::none;
  62. }
  63. template<bool isRequest>
  64. template<class ConstBufferSequence>
  65. std::size_t
  66. basic_parser<isRequest>::
  67. put_from_stack(std::size_t size,
  68. ConstBufferSequence const& buffers,
  69. error_code& ec)
  70. {
  71. char buf[max_stack_buffer];
  72. net::buffer_copy(net::mutable_buffer(
  73. buf, sizeof(buf)), buffers);
  74. return put(net::const_buffer{
  75. buf, size}, ec);
  76. }
  77. } // http
  78. } // beast
  79. } // boost
  80. #endif