Skip to content

Commit

Permalink
Do explicit byte packing for uuids
Browse files Browse the repository at this point in the history
Signed-off-by: methylDragon <methylDragon@gmail.com>
  • Loading branch information
methylDragon committed Oct 14, 2022
1 parent a085d46 commit 72f51e8
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions fuse_core/src/uuid.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,14 @@ UUID generate(const std::string& namespace_string, const rclcpp::Time& stamp)
const auto nanoseconds = stamp.nanoseconds();
constexpr size_t buffer_size = sizeof(nanoseconds);
std::array<unsigned char, buffer_size> buffer;
auto iter = buffer.begin();
iter = std::copy(reinterpret_cast<const unsigned char*>(&nanoseconds),
reinterpret_cast<const unsigned char*>(&nanoseconds) + sizeof(nanoseconds),
iter);

// Explicitly pack nanosecond bits from LSB -> MSB by masking and shifting
// E.g. 10 would be 0x00000000'0000000A, so the buffer would store 0x0A at buffer[0]
for (size_t i = 0; i < sizeof(nanoseconds); i++) {
auto mask = (nanoseconds & (static_cast<int64_t>(0xFF) << 8 * i));
buffer[i] = static_cast<unsigned char>(mask >> 8 * i);
}

return generate(namespace_string, buffer.data(), buffer.size());
}

Expand All @@ -81,13 +85,17 @@ UUID generate(const std::string& namespace_string, const rclcpp::Time& stamp, co
const auto nanoseconds = stamp.nanoseconds();
constexpr size_t buffer_size = sizeof(nanoseconds) + UUID::static_size();
std::array<unsigned char, buffer_size> buffer;
auto iter = buffer.begin();
iter = std::copy(reinterpret_cast<const unsigned char*>(&nanoseconds),
reinterpret_cast<const unsigned char*>(&nanoseconds) + sizeof(nanoseconds),
iter);
iter = std::copy(id.begin(),
id.end(),
iter);

// Explicitly pack nanosecond bits from LSB -> MSB by masking and shifting
for (size_t i = 0; i < sizeof(nanoseconds); i++) {
auto mask = (nanoseconds & (static_cast<int64_t>(0xFF) << 8 * i));
buffer[i] = static_cast<unsigned char>(mask >> 8 * i);
}

// Then append the ID bytes
auto iter = &buffer[sizeof(nanoseconds)];
iter = std::copy(id.begin(), id.end(), iter);

return generate(namespace_string, buffer.data(), buffer.size());
}

Expand Down

0 comments on commit 72f51e8

Please sign in to comment.