Use _Generic instead of string comparisons for code that depends on field type.

This will allow us to add fields that can't be cast to int or double, without breaking print.

PiperOrigin-RevId: 456005913
Change-Id: I1fccfd11466f4745f69172af0ae61be07642927c
This commit is contained in:
Nimrod Gileadi
2022-06-20 00:02:31 -07:00
committed by Copybara-Service
parent 37fe45d41e
commit b1faec1dc2
+16 -6
View File
@@ -308,15 +308,21 @@ void mj_printFormattedModel(const mjModel* m, const char* filename, const char*
#define X(type, name, num, sz) \ #define X(type, name, num, sz) \
if (&m->num == object_class && (strncmp(#name, "name_", 5) != 0) && sz) { \ if (&m->num == object_class && (strncmp(#name, "name_", 5) != 0) && sz) { \
const char* format = _Generic(*m->name, \
double: float_format, \
float: float_format, \
int: INT_FORMAT, \
mjtByte: INT_FORMAT, \
default: NULL); \
if (format) { \
fprintf(fp, " "); \ fprintf(fp, " "); \
fprintf(fp, NAME_FORMAT, #name); \ fprintf(fp, NAME_FORMAT, #name); \
for (int j = 0; j < sz; j++) { \ for (int j = 0; j < sz; j++) { \
((strcmp(#type, "mjtNum") == 0) || (strcmp(#type, "float") == 0)) ? \ fprintf(fp, format, m->name[sz * i + j]); \
(fprintf(fp, float_format, (mjtNum)m->name[sz*i+j]), \ fprintf(fp, " "); \
fprintf(fp, " ")) : \
fprintf(fp, INT_FORMAT " ", (int)m->name[sz*i+j]); \
} \ } \
fprintf(fp, "\n"); \ fprintf(fp, "\n"); \
} \
} }
// bodies // bodies
@@ -715,10 +721,14 @@ void mj_printFormattedData(const mjModel* m, mjData* d, const char* filename,
fprintf(fp, "SIZES\n"); fprintf(fp, "SIZES\n");
#define X(type, name) \ #define X(type, name) \
if(strcmp(#type, "int")==0) { \ { \
const char* format = _Generic(d->name, int : INT_FORMAT, default : NULL); \
if (format) { \
fprintf(fp, " "); \ fprintf(fp, " "); \
fprintf(fp, NAME_FORMAT, #name); \ fprintf(fp, NAME_FORMAT, #name); \
fprintf(fp, INT_FORMAT "\n", (int)d->name); \ fprintf(fp, format, d->name); \
fprintf(fp, "\n"); \
} \
} }
MJDATA_SCALAR MJDATA_SCALAR