Skip to content

Commit

Permalink
detail::stack grows by powers of 2
Browse files Browse the repository at this point in the history
  • Loading branch information
grisumbras committed Oct 16, 2023
1 parent d5a3cb3 commit ee78f18
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions include/boost/json/detail/impl/stack.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,25 @@ reserve_impl(std::size_t n)
// caller checks this
BOOST_ASSERT(n > cap_);

if(BOOST_JSON_UNLIKELY( n > std::numeric_limits<std::size_t>::max() - n ))
constexpr std::size_t max = std::numeric_limits<std::size_t>::max();
std::size_t cap = cap_ ? cap_ : 32 ;
do
{
if(BOOST_JSON_UNLIKELY( cap > max - cap ))
throw_exception( std::bad_alloc(), BOOST_CURRENT_LOCATION );
cap *= 2;
}
while(cap < n);

if(BOOST_JSON_UNLIKELY( cap > max - cap ))
throw_exception( std::bad_alloc(), BOOST_CURRENT_LOCATION );

auto const base = static_cast<unsigned char*>( sp_->allocate(n * 2) );
auto const base = static_cast<unsigned char*>( sp_->allocate(cap * 2) );
if(base_)
{
// copy trivials
if(size1_ > 0)
std::memcpy(base + n - size1_, base_ + cap_ - size1_, size1_);
std::memcpy(base + cap - size1_, base_ + cap_ - size1_, size1_);

// copy non-trivials
if(head_)
Expand Down Expand Up @@ -85,7 +95,7 @@ reserve_impl(std::size_t n)
sp_->deallocate(base_, cap_ * 2);
}
base_ = base;
cap_ = n;
cap_ = cap;
}

template<class T>
Expand Down

0 comments on commit ee78f18

Please sign in to comment.