Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
ipool.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2023 Roc Streaming authors
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 */
8
9//! @file roc_core/ipool.h
10//! @brief Memory pool interface.
11
12#ifndef ROC_CORE_IPOOL_H_
13#define ROC_CORE_IPOOL_H_
14
15#include "roc_core/attributes.h"
16#include "roc_core/panic.h"
17#include "roc_core/stddefs.h"
18
19namespace roc {
20namespace core {
21
22//! Memory pool interface.
23class IPool {
24public:
25 virtual ~IPool();
26
27 //! Get size of object allocated by pool.
28 virtual size_t object_size() const = 0;
29
30 //! Reserve memory for given number of objects.
31 //! @returns
32 //! false if allocation failed.
33 virtual ROC_ATTR_NODISCARD bool reserve(size_t n_objects) = 0;
34
35 //! Allocate memory for an object.
36 //! @returns
37 //! pointer to a maximum aligned uninitialized memory for a new object
38 //! or NULL if memory can't be allocated.
39 virtual void* allocate() = 0;
40
41 //! Return memory to pool.
42 virtual void deallocate(void* memory) = 0;
43
44 //! Destroy object and deallocate its memory.
45 template <class T> void destroy_object(T& object) {
46 object.~T();
47 deallocate(&object);
48 }
49};
50
51} // namespace core
52} // namespace roc
53
54//! Placement new for core::IPool.
55//! @note
56//! nothrow forces compiler to check for NULL return value before calling ctor.
57inline void* operator new(size_t size, roc::core::IPool& pool) throw() {
58 roc_panic_if_not(size <= pool.object_size());
59 return pool.allocate();
60}
61
62//! Placement delete for core::IPool.
63//! @note
64//! Compiler calls this if ctor throws in a placement new expression.
65inline void operator delete(void* ptr, roc::core::IPool& pool) throw() {
66 pool.deallocate(ptr);
67}
68
69#endif // ROC_CORE_IPOOL_H_
Compiler attributes.
#define ROC_ATTR_NODISCARD
Emit warning if function result is not checked.
Definition: attributes.h:31
Memory pool interface.
Definition: ipool.h:23
virtual ROC_ATTR_NODISCARD bool reserve(size_t n_objects)=0
Reserve memory for given number of objects.
virtual size_t object_size() const =0
Get size of object allocated by pool.
virtual void * allocate()=0
Allocate memory for an object.
virtual void deallocate(void *memory)=0
Return memory to pool.
void destroy_object(T &object)
Destroy object and deallocate its memory.
Definition: ipool.h:45
Root namespace.
Panic.
#define roc_panic_if_not(x)
Panic if condition is false.
Definition: panic.h:37
Commonly used types and functions.