From af7c729eee881646c110fb8d553cee2d9b916676 Mon Sep 17 00:00:00 2001 From: m12watanabe1a <40206149+m12watanabe1a@users.noreply.github.com> Date: Mon, 29 Apr 2024 14:07:44 +0900 Subject: [PATCH] Implement resize function --- .../rosidl_runtime_c/string_functions.h | 13 +++++++++++ rosidl_runtime_c/src/string_functions.c | 22 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/rosidl_runtime_c/include/rosidl_runtime_c/string_functions.h b/rosidl_runtime_c/include/rosidl_runtime_c/string_functions.h index 5f378220e..d8cb4d805 100644 --- a/rosidl_runtime_c/include/rosidl_runtime_c/string_functions.h +++ b/rosidl_runtime_c/include/rosidl_runtime_c/string_functions.h @@ -117,6 +117,19 @@ bool rosidl_runtime_c__String__assign( rosidl_runtime_c__String * str, const char * value); +/// Resize the char pointer. +/** + * This function resize the input value pointer. + * + * \param[in] n the new size of the internal buffer + * \return true if successful, false if the passed string pointer is null + * or if the size is higher than SIZE_MAX or if the memory reallocation failed. + */ +ROSIDL_GENERATOR_C_PUBLIC +bool +rosidl_runtime_c__String__resize( + rosidl_runtime_c__String * str, size_t n); + /// Initialize a rosidl_runtime_c__String__Sequence__init structure. /** * The rosidl_runtime_c__String__Sequence is initialized with the size passed to the function. diff --git a/rosidl_runtime_c/src/string_functions.c b/rosidl_runtime_c/src/string_functions.c index ed44e6413..20b8e26ff 100644 --- a/rosidl_runtime_c/src/string_functions.c +++ b/rosidl_runtime_c/src/string_functions.c @@ -143,6 +143,28 @@ rosidl_runtime_c__String__copy( output, input->data, input->size); } +bool rosidl_runtime_c__String__resize( + rosidl_runtime_c__String *str, size_t n) +{ + if(!str) { + return false; + } + // check valid range of n before allocating n + 1 characters + if(n > SIZE_MAX / sizeof(char) - 1) { + return false; + } + rcutils_allocator_t allocator = rcutils_get_default_allocator(); + char * data = allocator.reallocate(str->data, (n + 1) * sizeof(char), allocator.state); + if(!data) { + return false; + } + data[n] = 0; + str->data = data; + str->size = n; + str->capacity = n + 1; + return true; +} + bool rosidl_runtime_c__String__Sequence__init( rosidl_runtime_c__String__Sequence * sequence, size_t size)