@@ -87,6 +87,80 @@ set_failing_allocator_is_failing(rcutils_allocator_t & failing_allocator, bool s
8787 ((__failing_allocator_state * )failing_allocator .state )-> is_failing = state ;
8888}
8989
90+ typedef struct time_bomb_allocator_state
91+ {
92+ int count_until_failure ;
93+ } time_bomb_allocator_state ;
94+
95+ static void * time_bomb_malloc (size_t size , void * state )
96+ {
97+ time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state * )state ;
98+ if (time_bomb_state -> count_until_failure >= 0 &&
99+ time_bomb_state -> count_until_failure -- == 0 )
100+ {
101+ return nullptr ;
102+ }
103+ return rcutils_get_default_allocator ().allocate (size , rcutils_get_default_allocator ().state );
104+ }
105+
106+ static void *
107+ time_bomb_realloc (void * pointer , size_t size , void * state )
108+ {
109+ time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state * )state ;
110+ if (time_bomb_state -> count_until_failure >= 0 &&
111+ time_bomb_state -> count_until_failure -- == 0 )
112+ {
113+ return nullptr ;
114+ }
115+ return rcutils_get_default_allocator ().reallocate (
116+ pointer , size , rcutils_get_default_allocator ().state );
117+ }
118+
119+ static void
120+ time_bomb_free (void * pointer , void * state )
121+ {
122+ time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state * )state ;
123+ if (time_bomb_state -> count_until_failure >= 0 &&
124+ time_bomb_state -> count_until_failure -- == 0 )
125+ {
126+ return ;
127+ }
128+ rcutils_get_default_allocator ().deallocate (pointer , rcutils_get_default_allocator ().state );
129+ }
130+
131+ static void *
132+ time_bomb_calloc (size_t number_of_elements , size_t size_of_element , void * state )
133+ {
134+ time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state * )state ;
135+ if (time_bomb_state -> count_until_failure >= 0 &&
136+ time_bomb_state -> count_until_failure -- == 0 )
137+ {
138+ return nullptr ;
139+ }
140+ return rcutils_get_default_allocator ().zero_allocate (
141+ number_of_elements , size_of_element , rcutils_get_default_allocator ().state );
142+ }
143+
144+ static inline rcutils_allocator_t
145+ get_time_bombed_allocator (void )
146+ {
147+ static time_bomb_allocator_state state ;
148+ state .count_until_failure = 1 ;
149+ auto time_bombed_allocator = rcutils_get_default_allocator ();
150+ time_bombed_allocator .allocate = time_bomb_malloc ;
151+ time_bombed_allocator .deallocate = time_bomb_free ;
152+ time_bombed_allocator .reallocate = time_bomb_realloc ;
153+ time_bombed_allocator .zero_allocate = time_bomb_calloc ;
154+ time_bombed_allocator .state = & state ;
155+ return time_bombed_allocator ;
156+ }
157+
158+ static inline void
159+ set_time_bombed_allocator_count (rcutils_allocator_t & time_bombed_allocator , int count )
160+ {
161+ ((time_bomb_allocator_state * )time_bombed_allocator .state )-> count_until_failure = count ;
162+ }
163+
90164#ifdef __cplusplus
91165}
92166#endif
0 commit comments