buffer_resize_guard.hpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // detail/buffer_resize_guard.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2023 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 "asio/detail/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_ != (std::numeric_limits<size_t>::max)())
  35. {
  36. buffer_.resize(old_size_);
  37. }
  38. }
  39. // Commit the resize transaction.
  40. void commit()
  41. {
  42. old_size_ = (std::numeric_limits<size_t>::max)();
  43. }
  44. private:
  45. // The buffer being managed.
  46. Buffer& buffer_;
  47. // The size of the buffer at the time the guard was constructed.
  48. size_t old_size_;
  49. };
  50. } // namespace detail
  51. } // namespace asio
  52. #include "asio/detail/pop_options.hpp"
  53. #endif // ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP