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
10#ifndef BOOST_BEAST_IMPL_READ_SIZE_HPP
11#define BOOST_BEAST_IMPL_READ_SIZE_HPP
12
13#include <boost/asio/buffer.hpp>
14#include <boost/assert.hpp>
15#include <stdexcept>
16#include <type_traits>
17
18namespace boost {
19namespace beast {
20
21namespace detail {
22
23template<class T, class = void>
24struct has_read_size_helper : std::false_type {};
25
26template<class T>
27struct has_read_size_helper<T, decltype(
28 read_size_helper(std::declval<T&>(), 512),
29 (void)0)> : std::true_type
30{
31};
32
33template<class DynamicBuffer>
34std::size_t
35read_size(DynamicBuffer& buffer,
36 std::size_t max_size, std::true_type)
37{
38 return read_size_helper(buffer, max_size);
39}
40
41template<class DynamicBuffer>
42std::size_t
43read_size(DynamicBuffer& buffer,
44 std::size_t max_size, std::false_type)
45{
46 static_assert(
47 net::is_dynamic_buffer<DynamicBuffer>::value,
48 "DynamicBuffer type requirements not met");
49 auto const size = buffer.size();
50 auto const limit = buffer.max_size() - size;
51 BOOST_ASSERT(size <= buffer.max_size());
52 return std::min<std::size_t>(
53 std::max<std::size_t>(512, buffer.capacity() - size),
54 std::min<std::size_t>(max_size, limit));
55}
56
57} // detail
58
59template<class DynamicBuffer>
60std::size_t
61read_size(
62 DynamicBuffer& buffer, std::size_t max_size)
63{
64 return detail::read_size(buffer, max_size,
65 detail::has_read_size_helper<DynamicBuffer>{});
66}
67
68template<class DynamicBuffer>
69std::size_t
70read_size_or_throw(
71 DynamicBuffer& buffer, std::size_t max_size)
72{
73 auto const n = read_size(buffer, max_size);
74 if(n == 0)
75 BOOST_THROW_EXCEPTION(std::length_error{
76 "buffer overflow"});
77 return n;
78}
79
80} // beast
81} // boost
82
83#endif
84

source code of boost/libs/beast/include/boost/beast/core/impl/read_size.hpp