Skip to content

Commit 6ae0fc9

Browse files
pmr: Don't promise more capacity than whats actually remaining in pool
1 parent 1e33fb1 commit 6ae0fc9

1 file changed

Lines changed: 20 additions & 7 deletions

File tree

api/util/detail/alloc_pmr.hpp

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ namespace os::mem::detail {
3333

3434
void* do_allocate(size_t size, size_t align) override {
3535
if (UNLIKELY(size + allocated_ > cap_total_)) {
36+
//printf("pmr about to throw bad alloc: sz=%zu alloc=%zu cap=%zu\n", size, allocated_, cap_total_);
3637
throw std::bad_alloc();
3738
}
3839

@@ -46,6 +47,7 @@ namespace os::mem::detail {
4647
void* buf = memalign(align, size);
4748

4849
if (buf == nullptr) {
50+
//printf("pmr memalign return nullptr, throw bad alloc\n");
4951
throw std::bad_alloc();
5052
}
5153

@@ -152,7 +154,9 @@ namespace os::mem::detail {
152154

153155
std::size_t resource_capacity() {
154156
if (cap_suballoc_ == 0)
157+
{
155158
return cap_total_ / (used_resources_ + os::mem::Pmr_pool::resource_division_offset);
159+
}
156160
return cap_suballoc_;
157161
}
158162

@@ -244,7 +248,9 @@ namespace os::mem {
244248
// Pmr_resource implementation
245249
//
246250
Pmr_resource::Pmr_resource(Pool_ptr p) : pool_{p} {}
247-
std::size_t Pmr_resource::capacity() { return pool_->resource_capacity(); }
251+
std::size_t Pmr_resource::capacity() {
252+
return std::min(pool_->resource_capacity(), pool_->allocatable());
253+
}
248254
std::size_t Pmr_resource::allocatable() {
249255
auto cap = capacity();
250256
if (used > cap)
@@ -266,12 +272,19 @@ namespace os::mem {
266272
throw std::bad_alloc();
267273
}
268274

269-
void* buf = pool_->allocate(size, align);
270-
271-
used += size;
272-
allocs++;
273-
274-
return buf;
275+
try
276+
{
277+
void* buf = pool_->allocate(size, align);
278+
used += size;
279+
allocs++;
280+
return buf;
281+
}
282+
catch(const std::bad_alloc&)
283+
{
284+
//printf("Pool returned bad alloc, resource: used=%zu reported_cap=%zu allocatable=%zu\n",
285+
// used, cap, allocatable());
286+
throw;
287+
}
275288
}
276289

277290
void Pmr_resource::do_deallocate(void* ptr, std::size_t s, std::size_t a) {

0 commit comments

Comments
 (0)