forked from scylladb/scylladb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamortized_reserve.hh
53 lines (47 loc) · 1.71 KB
/
amortized_reserve.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* Copyright (C) 2022-present ScyllaDB
*/
/*
* SPDX-License-Identifier: LicenseRef-ScyllaDB-Source-Available-1.0
*/
#pragma once
#include <concepts>
#include <vector>
/// Represents a container which can preallocate space for future insertions
/// which can be used to reduce the number of overall memory re-allocation and item movement.
///
/// The number of items for which space is currently reserved is returned by capacity().
/// This includes items currently present in the container.
///
/// The number of items currently present is returned by size().
///
/// Invariant:
///
/// size() <= capacity()
///
/// Space is reserved by calling reserve(desired_capacity).
/// The post-condition of calling reserve() is:
///
/// capacity() >= desired_capacity
///
/// It is guaranteed insertion of (capacity() - size()) items does not
/// throw if T::value_type constructor and move constructor do not throw.
template <typename T>
concept ContainerWithCapacity = requires (T x, size_t desired_capacity, typename T::value_type e) {
{ x.reserve(desired_capacity) } -> std::same_as<void>;
{ x.capacity() } -> std::same_as<size_t>;
{ x.size() } -> std::same_as<size_t>;
};
static_assert(ContainerWithCapacity<std::vector<int>>);
/// Reserves space for at least desired_capacity - v.size() elements.
///
/// Amortizes space expansion so that a series of N calls to amortized_reserve(v, v.size() + 1)
/// starting from an empty container takes O(N) time overall.
///
/// Post-condition: v.capacity() >= desired_capacity
template <ContainerWithCapacity T>
void amortized_reserve(T& v, size_t desired_capacity) {
if (desired_capacity > v.capacity()) {
v.reserve(std::max(desired_capacity, v.capacity() * 2));
}
}