stack.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //
  2. // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/json
  8. //
  9. #ifndef BOOST_JSON_DETAIL_STACK_HPP
  10. #define BOOST_JSON_DETAIL_STACK_HPP
  11. #include <boost/json/detail/config.hpp>
  12. #include <boost/json/storage_ptr.hpp>
  13. #include <cstring>
  14. BOOST_JSON_NS_BEGIN
  15. namespace detail {
  16. class stack
  17. {
  18. storage_ptr sp_;
  19. std::size_t cap_ = 0;
  20. std::size_t size_ = 0;
  21. char* buf_ = nullptr;
  22. public:
  23. BOOST_JSON_DECL
  24. ~stack();
  25. bool
  26. empty() const noexcept
  27. {
  28. return size_ == 0;
  29. }
  30. void
  31. clear() noexcept
  32. {
  33. size_ = 0;
  34. }
  35. BOOST_JSON_DECL
  36. void
  37. reserve(std::size_t n);
  38. template<class T>
  39. void
  40. push(T const& t)
  41. {
  42. auto const n = sizeof(T);
  43. // If this assert goes off, it
  44. // means the calling code did not
  45. // reserve enough to prevent a
  46. // reallocation.
  47. //BOOST_ASSERT(cap_ >= size_ + n);
  48. reserve(size_ + n);
  49. std::memcpy(
  50. buf_ + size_, &t, n);
  51. size_ += n;
  52. }
  53. template<class T>
  54. void
  55. push_unchecked(T const& t)
  56. {
  57. auto const n = sizeof(T);
  58. BOOST_ASSERT(size_ + n <= cap_);
  59. std::memcpy(
  60. buf_ + size_, &t, n);
  61. size_ += n;
  62. }
  63. template<class T>
  64. void
  65. peek(T& t)
  66. {
  67. auto const n = sizeof(T);
  68. BOOST_ASSERT(size_ >= n);
  69. std::memcpy(&t,
  70. buf_ + size_ - n, n);
  71. }
  72. template<class T>
  73. void
  74. pop(T& t)
  75. {
  76. auto const n = sizeof(T);
  77. BOOST_ASSERT(size_ >= n);
  78. size_ -= n;
  79. std::memcpy(
  80. &t, buf_ + size_, n);
  81. }
  82. };
  83. } // detail
  84. BOOST_JSON_NS_END
  85. #endif