buffer_resize_guard.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // buffer_resize_guard.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2008 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. #ifndef BOOST_ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP
  11. #define BOOST_ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/push_options.hpp>
  16. #include <boost/asio/detail/push_options.hpp>
  17. #include <limits>
  18. #include <boost/config.hpp>
  19. #include <boost/asio/detail/pop_options.hpp>
  20. namespace boost {
  21. namespace asio {
  22. namespace detail {
  23. // Helper class to manage buffer resizing in an exception safe way.
  24. template <typename Buffer>
  25. class buffer_resize_guard
  26. {
  27. public:
  28. // Constructor.
  29. buffer_resize_guard(Buffer& buffer)
  30. : buffer_(buffer),
  31. old_size_(buffer.size())
  32. {
  33. }
  34. // Destructor rolls back the buffer resize unless commit was called.
  35. ~buffer_resize_guard()
  36. {
  37. if (old_size_
  38. != std::numeric_limits<size_t>::max BOOST_PREVENT_MACRO_SUBSTITUTION())
  39. {
  40. buffer_.resize(old_size_);
  41. }
  42. }
  43. // Commit the resize transaction.
  44. void commit()
  45. {
  46. old_size_
  47. = std::numeric_limits<size_t>::max BOOST_PREVENT_MACRO_SUBSTITUTION();
  48. }
  49. private:
  50. // The buffer being managed.
  51. Buffer& buffer_;
  52. // The size of the buffer at the time the guard was constructed.
  53. size_t old_size_;
  54. };
  55. } // namespace detail
  56. } // namespace asio
  57. } // namespace boost
  58. #include <boost/asio/detail/pop_options.hpp>
  59. #endif // BOOST_ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP