Coverage Report

Created: 2026-05-04 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/Fast-DDS/src/cpp/utils/collections/ObjectPool.hpp
Line
Count
Source
1
// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima).
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
/**
16
 * @file ObjectPool.hpp
17
 *
18
 */
19
20
#ifndef FASTDDS_UTILS_COLLECTIONS_OBJECTPOOL_HPP_
21
#define FASTDDS_UTILS_COLLECTIONS_OBJECTPOOL_HPP_
22
23
#include <memory>
24
#include <type_traits>
25
#include <vector>
26
27
namespace eprosima {
28
namespace fastdds {
29
30
/**
31
 * A generic pool of objects.
32
 *
33
 * This template class holds a circular queue of fixed size. Pushing a new element to a full queue
34
 * will result in an error.
35
 *
36
 * @tparam _Ty                 Element type.
37
 * @tparam _Alloc              Allocator to use on the underlying collection type, defaults to std::allocator<_Ty>.
38
 * @tparam _Collection         Underlying collection type, defaults to std::vector<_Ty, _Alloc>
39
 *
40
 * @ingroup UTILITIES_MODULE
41
 */
42
template<
43
    typename _Ty,
44
    typename _Alloc = std::allocator<_Ty>,
45
    typename _Collection = std::vector<_Ty, _Alloc>>
46
struct ObjectPool final
47
{
48
    using allocator_type = _Alloc;
49
    using value_type = _Ty;
50
51
    /**
52
     * Construct an ObjectPool.
53
     */
54
    ObjectPool(
55
            const allocator_type& alloc = allocator_type())
56
0
        : collection_(alloc)
57
0
    {
58
0
    }
59
60
    const _Collection& collection() const noexcept
61
    {
62
        return collection_;
63
    }
64
65
    _Collection& collection() noexcept
66
0
    {
67
0
        return collection_;
68
0
    }
69
70
    template<typename _DefaultGetter>
71
    value_type get(
72
            _DefaultGetter _Default)
73
0
    {
74
0
        if (collection_.empty())
75
0
        {
76
0
            return _Default();
77
0
        }
78
79
0
        value_type ret = collection_.back();
80
0
        collection_.pop_back();
81
0
        return ret;
82
0
    }
83
84
    template<class ... _Valty>
85
    void put(
86
            _Valty&&... _Val)
87
0
    {
88
0
        collection_.emplace_back(std::forward<_Valty>(_Val)...);
89
0
    }
90
91
private:
92
93
    _Collection collection_;
94
95
};
96
97
}  // namespace fastdds
98
}  // namespace eprosima
99
100
#endif /* FASTDDS_UTILS_COLLECTIONS_OBJECTPOOL_HPP_ */