Skip to content

Commit

Permalink
Add string to int ID conversion (#2279)
Browse files Browse the repository at this point in the history
The Track ID to ExternalObject ID conversion (string to int) now handles
cases where the mapping is not one-to-one.
  • Loading branch information
adamlm authored Jan 12, 2024
1 parent 347a51e commit 3707df6
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions carma_cooperative_perception/src/msg_conversion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
#include <j3224_v2x_msgs/msg/object_type.hpp>

#include <algorithm>
#include <cctype>
#include <charconv>
#include <chrono>
#include <cmath>
#include <limits>
Expand Down Expand Up @@ -375,15 +377,26 @@ auto to_external_object_msg(const carma_cooperative_perception_interfaces::msg::
external_object.header = track.header;
external_object.presence_vector = 0;

try {
if (const auto numeric_id{std::stol(track.id)};
numeric_id >= 0 && numeric_id <= std::numeric_limits<std::uint32_t>::max()) {
external_object.presence_vector |= external_object.ID_PRESENCE_VECTOR;
external_object.id = static_cast<std::uint32_t>(numeric_id);
const auto to_numeric_id = [](std::string string_id) -> std::optional<uint32_t> {
auto non_digit_start = std::remove_if(
std::begin(string_id), std::end(string_id),
[](const auto & ch) { return !std::isdigit(ch); });

std::uint32_t numeric_id;
const auto digit_substr_size{std::distance(std::begin(string_id), non_digit_start)};
if (
std::from_chars(string_id.c_str(), string_id.c_str() + digit_substr_size, numeric_id).ec ==
std::errc{}) {
return numeric_id;
}
} catch (const std::invalid_argument & /* exception */) {
external_object.presence_vector &= ~external_object.ID_PRESENCE_VECTOR;
} catch (const std::out_of_range & /* exception */) {

return std::nullopt;
};

if (const auto numeric_id{to_numeric_id(track.id)}) {
external_object.presence_vector |= external_object.ID_PRESENCE_VECTOR;
external_object.id = numeric_id.value();
} else {
external_object.presence_vector &= ~external_object.ID_PRESENCE_VECTOR;
}

Expand Down

0 comments on commit 3707df6

Please sign in to comment.