buffer_resize_guard.hpp 1.5 KB

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