Inkscape
Vector Graphics Editor
Loading...
Searching...
No Matches
pool.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-2.0-or-later
2
3#include "pool.h"
4
5#include <cassert>
6#include <utility>
7
8namespace Inkscape::Util {
9
10// Round up x to the next multiple of m.
11static std::byte *round_up(std::byte *x, std::size_t m)
12{
13 auto y = reinterpret_cast<uintptr_t>(x);
14 y = ((y - 1) / m + 1) * m;
15 return reinterpret_cast<std::byte*>(y);
16}
17
18std::byte *Pool::allocate(std::size_t size, std::size_t alignment)
19{
20 auto a = round_up(cur, alignment);
21 auto b = a + size;
22
23 if (b <= end) {
24 cur = b;
25 return a;
26 }
27
28 cursize = std::max(nextsize, size + alignment - 1);
29 buffers.push_back(std::make_unique<std::byte[]>(cursize));
30 // TODO: C++20: *once* Apple+AppImage support it: Use std::make_unique_for_overwrite()
31 // buffers.push_back(std::make_unique_for_overwrite<std::byte[]>(cursize));
32
33 resetblock();
34 nextsize = cursize * 3 / 2;
35
36 a = round_up(cur, alignment);
37 b = a + size;
38
39 assert(b <= end);
40 cur = b;
41 return a;
42};
43
44void Pool::free_all() noexcept
45{
46 if (buffers.empty()) return;
47 if (buffers.size() > 1) {
48 buffers.front() = std::move(buffers.back());
49 buffers.resize(1);
50 }
51 resetblock();
52}
53
54void Pool::movefrom(Pool &other) noexcept
55{
56 buffers = std::move(other.buffers);
57 cur = other.cur;
58 end = other.end;
59 cursize = other.cursize;
60 nextsize = other.nextsize;
61
62 other.buffers.clear();
63 other.cur = nullptr;
64 other.end = nullptr;
65 other.cursize = 0;
66 other.nextsize = 2;
67}
68
69void Pool::resetblock() noexcept
70{
71 assert(!buffers.empty());
72 cur = buffers.back().get();
73 end = cur + cursize;
74}
75
76} // namespace Inkscape::Util
77
78/*
79 Local Variables:
80 mode:c++
81 c-file-style:"stroustrup"
82 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
83 indent-tabs-mode:nil
84 fill-column:99
85 End:
86*/
87// vim:filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99:
A Pool is a block allocator with the following characteristics:
Definition pool.h:27
T * allocate()
Convenience function: allocate a block of size and aligment for T.
Definition pool.h:43
std::byte * cur
Definition pool.h:50
std::size_t nextsize
Definition pool.h:51
std::byte * end
Definition pool.h:50
std::vector< std::unique_ptr< std::byte[]> > buffers
Definition pool.h:49
std::size_t cursize
Definition pool.h:51
void movefrom(Pool &other) noexcept
Definition pool.cpp:54
void resetblock() noexcept
Definition pool.cpp:69
void free_all() noexcept
Free all previous allocations, retaining the largest existing buffer for re-use.
Definition pool.cpp:44
Geom::Point end
Miscellaneous supporting code.
Definition document.h:93
T constexpr round_up(T a, T b)
Returns a rounded up to the nearest multiple of b, assuming b >= 1.
Definition mathfns.h:89
std::vector< Buffer > buffers