stack.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. //
  2. // Copyright (c) 2019 Vinnie Falco ([email protected])
  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. namespace boost {
  15. namespace json {
  16. namespace detail {
  17. class stack
  18. {
  19. storage_ptr sp_;
  20. std::size_t cap_ = 0;
  21. std::size_t size_ = 0;
  22. unsigned char* base_ = nullptr;
  23. unsigned char* buf_ = nullptr;
  24. public:
  25. BOOST_JSON_DECL
  26. ~stack();
  27. stack() = default;
  28. stack(
  29. storage_ptr sp,
  30. unsigned char* buf,
  31. std::size_t buf_size) noexcept;
  32. bool
  33. empty() const noexcept
  34. {
  35. return size_ == 0;
  36. }
  37. void
  38. clear() noexcept
  39. {
  40. size_ = 0;
  41. }
  42. BOOST_JSON_DECL
  43. void
  44. reserve(std::size_t n);
  45. template<class T>
  46. void
  47. push(T const& t)
  48. {
  49. auto const n = sizeof(T);
  50. // If this assert goes off, it
  51. // means the calling code did not
  52. // reserve enough to prevent a
  53. // reallocation.
  54. //BOOST_ASSERT(cap_ >= size_ + n);
  55. reserve(size_ + n);
  56. std::memcpy(
  57. base_ + size_, &t, n);
  58. size_ += n;
  59. }
  60. template<class T>
  61. void
  62. push_unchecked(T const& t)
  63. {
  64. auto const n = sizeof(T);
  65. BOOST_ASSERT(size_ + n <= cap_);
  66. std::memcpy(
  67. base_ + size_, &t, n);
  68. size_ += n;
  69. }
  70. template<class T>
  71. void
  72. peek(T& t)
  73. {
  74. auto const n = sizeof(T);
  75. BOOST_ASSERT(size_ >= n);
  76. std::memcpy(&t,
  77. base_ + size_ - n, n);
  78. }
  79. template<class T>
  80. void
  81. pop(T& t)
  82. {
  83. auto const n = sizeof(T);
  84. BOOST_ASSERT(size_ >= n);
  85. size_ -= n;
  86. std::memcpy(
  87. &t, base_ + size_, n);
  88. }
  89. };
  90. } // detail
  91. } // namespace json
  92. } // namespace boost
  93. #endif