buffer_resize_guard.hpp 1.6 KB

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