Skip to content

Commit b6e86f1

Browse files
committed
feat: ability to override the default allocator
Signed-off-by: Russ Webber <[email protected]>
1 parent cb567ca commit b6e86f1

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

include/rcutils/allocator.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,21 @@ RCUTILS_WARN_UNUSED
108108
rcutils_allocator_t
109109
rcutils_get_default_allocator(void);
110110

111+
/// Override the default allocator returned by rcutils_get_default_allocator.
112+
/**
113+
* Attribute | Adherence
114+
* ------------------ | -------------
115+
* Allocates Memory | No
116+
* Thread-Safe | No
117+
* Uses Atomics | No
118+
* Lock-Free | Yes
119+
*
120+
* \param[in] override_allocator The allocator to set as the default.
121+
*/
122+
RCUTILS_PUBLIC
123+
void
124+
rcutils_set_default_allocator(rcutils_allocator_t override_allocator);
125+
111126
/// Return true if the given allocator has non-null function pointers.
112127
/**
113128
* \param[in] allocator to be checked by the function

src/allocator.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,16 +69,32 @@ rcutils_get_zero_initialized_allocator(void)
6969
return zero_allocator;
7070
}
7171

72+
static rcutils_allocator_t
73+
rcutils_override_default_allocator = {0};
74+
75+
void
76+
rcutils_set_default_allocator(rcutils_allocator_t override_allocator)
77+
{
78+
if (rcutils_allocator_is_valid(&override_allocator)) {
79+
rcutils_override_default_allocator = override_allocator;
80+
}
81+
}
82+
7283
rcutils_allocator_t
7384
rcutils_get_default_allocator(void)
7485
{
86+
if (rcutils_allocator_is_valid(&rcutils_override_default_allocator)) {
87+
return rcutils_override_default_allocator;
88+
}
89+
7590
static rcutils_allocator_t default_allocator = {
7691
.allocate = __default_allocate,
7792
.deallocate = __default_deallocate,
7893
.reallocate = __default_reallocate,
7994
.zero_allocate = __default_zero_allocate,
8095
.state = NULL,
8196
};
97+
8298
return default_allocator;
8399
}
84100

0 commit comments

Comments
 (0)