Skip to content

Commit

Permalink
Implement resize function
Browse files Browse the repository at this point in the history
  • Loading branch information
m12watanabe1a committed Apr 29, 2024
1 parent 0d4d9f8 commit af7c729
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions rosidl_runtime_c/include/rosidl_runtime_c/string_functions.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 22 additions & 0 deletions rosidl_runtime_c/src/string_functions.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit af7c729

Please sign in to comment.