Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions mjpc/utilities.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "mjpc/utilities.h"

#include <algorithm>
#include <bit>
#include <cerrno>
#include <cmath>
#include <cstdint>
Expand Down Expand Up @@ -115,12 +116,16 @@ void Clamp(double* x, const double* bounds, int n) {
}
}

int ReinterpretAsInt(double value) {
return *std::launder(reinterpret_cast<const int*>(&value));
int64_t ReinterpretAsInt(double value) {
static_assert(sizeof(double) == sizeof(int64_t),
"double and int64_t must have same size");
return std::bit_cast<int64_t>(value);
}

double ReinterpretAsDouble(int64_t value) {
return *std::launder(reinterpret_cast<const double*>(&value));
static_assert(sizeof(double) == sizeof(int64_t),
"double and int64_t must have same size");
return std::bit_cast<double>(value);
}

absl::flat_hash_map<std::string, std::vector<std::string>>
Expand Down Expand Up @@ -225,7 +230,7 @@ int ParameterIndex(const mjModel* model, std::string_view name) {
double DefaultResidualSelection(const mjModel* m, int numeric_index) {
// list selections are stored as ints, but numeric values are doubles.
int64_t value = m->numeric_data[m->numeric_adr[numeric_index]];
return *std::launder(reinterpret_cast<const double*>(&value));
return ReinterpretAsDouble(value);
}

int CostTermByName(const mjModel* m, const std::string& name) {
Expand Down
4 changes: 2 additions & 2 deletions mjpc/utilities.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ T GetNumberOrDefault(T default_value, const mjModel* m, std::string_view name) {
return GetNumber<T>(m, name).value_or(default_value);
}

// reinterpret double as int
int ReinterpretAsInt(double value);
// reinterpret double as int64_t
int64_t ReinterpretAsInt(double value);

// reinterpret int64_t as double
double ReinterpretAsDouble(int64_t value);
Expand Down
Loading