1 | // |
2 | // detail/buffer_resize_guard.hpp |
3 | // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
4 | // |
5 | // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) |
6 | // |
7 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
8 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
9 | // |
10 | |
11 | #ifndef BOOST_ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP |
12 | #define BOOST_ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP |
13 | |
14 | #if defined(_MSC_VER) && (_MSC_VER >= 1200) |
15 | # pragma once |
16 | #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) |
17 | |
18 | #include <boost/asio/detail/config.hpp> |
19 | #include <boost/asio/detail/limits.hpp> |
20 | |
21 | #include <boost/asio/detail/push_options.hpp> |
22 | |
23 | namespace boost { |
24 | namespace asio { |
25 | namespace detail { |
26 | |
27 | // Helper class to manage buffer resizing in an exception safe way. |
28 | template <typename Buffer> |
29 | class buffer_resize_guard |
30 | { |
31 | public: |
32 | // Constructor. |
33 | buffer_resize_guard(Buffer& buffer) |
34 | : buffer_(buffer), |
35 | old_size_(buffer.size()) |
36 | { |
37 | } |
38 | |
39 | // Destructor rolls back the buffer resize unless commit was called. |
40 | ~buffer_resize_guard() |
41 | { |
42 | if (old_size_ != (std::numeric_limits<size_t>::max)()) |
43 | { |
44 | buffer_.resize(old_size_); |
45 | } |
46 | } |
47 | |
48 | // Commit the resize transaction. |
49 | void commit() |
50 | { |
51 | old_size_ = (std::numeric_limits<size_t>::max)(); |
52 | } |
53 | |
54 | private: |
55 | // The buffer being managed. |
56 | Buffer& buffer_; |
57 | |
58 | // The size of the buffer at the time the guard was constructed. |
59 | size_t old_size_; |
60 | }; |
61 | |
62 | } // namespace detail |
63 | } // namespace asio |
64 | } // namespace boost |
65 | |
66 | #include <boost/asio/detail/pop_options.hpp> |
67 | |
68 | #endif // BOOST_ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP |
69 | |