beve 5.0.1

Rust implementation of the BEVE (Binary Efficient Versatile Encoding) specification with serde support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>

#include <matio.h>

namespace {

struct MatCloser {
  void operator()(mat_t* mat) const {
    if (mat != nullptr) {
      Mat_Close(mat);
    }
  }
};

struct MatVarCloser {
  void operator()(matvar_t* var) const {
    if (var != nullptr) {
      Mat_VarFree(var);
    }
  }
};

using MatFilePtr = std::unique_ptr<mat_t, MatCloser>;
using MatVarPtr = std::unique_ptr<matvar_t, MatVarCloser>;

[[noreturn]] void fail(std::string_view message) {
  throw std::runtime_error(std::string(message));
}

size_t numel(const matvar_t* var) {
  if (var == nullptr) {
    return 0;
  }
  size_t total = 1;
  for (int idx = 0; idx < var->rank; ++idx) {
    total *= var->dims[idx];
  }
  return total;
}

void write_json_string(std::ostream& out, std::string_view value) {
  out << '"';
  for (unsigned char ch : value) {
    switch (ch) {
      case '\\':
        out << "\\\\";
        break;
      case '"':
        out << "\\\"";
        break;
      case '\b':
        out << "\\b";
        break;
      case '\f':
        out << "\\f";
        break;
      case '\n':
        out << "\\n";
        break;
      case '\r':
        out << "\\r";
        break;
      case '\t':
        out << "\\t";
        break;
      default:
        if (ch < 0x20) {
          out << "\\u" << std::hex << std::setw(4) << std::setfill('0')
              << static_cast<unsigned int>(ch) << std::dec << std::setfill(' ');
        } else {
          out << static_cast<char>(ch);
        }
        break;
    }
  }
  out << '"';
}

void append_utf8(std::string& out, uint32_t cp) {
  if (cp <= 0x7F) {
    out.push_back(static_cast<char>(cp));
  } else if (cp <= 0x7FF) {
    out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
    out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
  } else if (cp <= 0xFFFF) {
    out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
    out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
    out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
  } else {
    out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
    out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
    out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
    out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
  }
}

std::string decode_utf16(const mat_uint16_t* data, size_t len) {
  std::string out;
  out.reserve(len);
  for (size_t idx = 0; idx < len; ++idx) {
    const uint16_t unit = data[idx];
    if (unit >= 0xD800 && unit <= 0xDBFF && idx + 1 < len) {
      const uint16_t next = data[idx + 1];
      if (next >= 0xDC00 && next <= 0xDFFF) {
        const uint32_t high = static_cast<uint32_t>(unit - 0xD800);
        const uint32_t low = static_cast<uint32_t>(next - 0xDC00);
        append_utf8(out, 0x10000 + ((high << 10) | low));
        ++idx;
        continue;
      }
    }
    append_utf8(out, unit);
  }
  return out;
}

std::string decode_utf32(const mat_uint32_t* data, size_t len) {
  std::string out;
  out.reserve(len);
  for (size_t idx = 0; idx < len; ++idx) {
    append_utf8(out, data[idx]);
  }
  return out;
}

std::string decode_char_data(const matvar_t* var) {
  const size_t len = numel(var);
  if (len == 0 || var->data == nullptr) {
    return {};
  }

  switch (var->data_type) {
    case MAT_T_UTF8:
    case MAT_T_UINT8:
      return std::string(static_cast<const char*>(var->data), len);
    case MAT_T_UTF16:
    case MAT_T_UINT16:
      return decode_utf16(static_cast<const mat_uint16_t*>(var->data), len);
    case MAT_T_UTF32:
    case MAT_T_UINT32:
      return decode_utf32(static_cast<const mat_uint32_t*>(var->data), len);
    default:
      fail("unsupported MATIO char encoding");
  }
}

void write_dims(std::ostream& out, const matvar_t* var) {
  out << '[';
  for (int idx = 0; idx < var->rank; ++idx) {
    if (idx > 0) {
      out << ',';
    }
    out << var->dims[idx];
  }
  out << ']';
}

template <typename T>
void write_numeric_list(std::ostream& out, const T* data, size_t len) {
  out << '[';
  if constexpr (std::is_floating_point_v<T>) {
    out << std::setprecision(std::numeric_limits<T>::max_digits10);
  }
  for (size_t idx = 0; idx < len; ++idx) {
    if (idx > 0) {
      out << ',';
    }
    if constexpr (std::is_same_v<T, int8_t>) {
      out << static_cast<int>(data[idx]);
    } else if constexpr (std::is_same_v<T, uint8_t>) {
      out << static_cast<unsigned int>(data[idx]);
    } else {
      out << data[idx];
    }
  }
  out << ']';
}

void write_logical_list(std::ostream& out, const matvar_t* var) {
  const size_t len = numel(var);
  const auto* data = static_cast<const mat_uint8_t*>(var->data);
  out << '[';
  for (size_t idx = 0; idx < len; ++idx) {
    if (idx > 0) {
      out << ',';
    }
    out << ((data != nullptr && data[idx] != 0) ? "true" : "false");
  }
  out << ']';
}

template <typename T>
void write_numeric_value(std::ostream& out, const matvar_t* var, std::string_view kind) {
  out << "{\"kind\":";
  write_json_string(out, kind);
  out << ",\"dims\":";
  write_dims(out, var);
  out << ",\"data\":";
  const auto* data = static_cast<const T*>(var->data);
  if (numel(var) > 0 && data == nullptr) {
    fail("numeric array is missing data");
  }
  write_numeric_list(out, data, numel(var));
  out << '}';
}

template <typename T>
void write_complex_value(std::ostream& out, const matvar_t* var, std::string_view kind) {
  out << "{\"kind\":";
  write_json_string(out, kind);
  out << ",\"dims\":";
  write_dims(out, var);
  out << ",\"real\":";
  const auto* split = static_cast<const mat_complex_split_t*>(var->data);
  const auto* real = split == nullptr ? nullptr : static_cast<const T*>(split->Re);
  const auto* imag = split == nullptr ? nullptr : static_cast<const T*>(split->Im);
  if (numel(var) > 0 && (real == nullptr || imag == nullptr)) {
    fail("complex array is missing split data");
  }
  write_numeric_list(out, real, numel(var));
  out << ",\"imag\":";
  write_numeric_list(out, imag, numel(var));
  out << '}';
}

void write_value(std::ostream& out, const matvar_t* var);

void write_struct_value(std::ostream& out, const matvar_t* var) {
  out << "{\"kind\":\"struct\",\"dims\":";
  write_dims(out, var);
  out << ",\"fields\":{";

  const auto nfields = Mat_VarGetNumberOfFields(const_cast<matvar_t*>(var));
  const auto* names = Mat_VarGetStructFieldnames(var);
  const auto nelems = numel(var);
  for (unsigned field_idx = 0; field_idx < nfields; ++field_idx) {
    if (field_idx > 0) {
      out << ',';
    }
    const char* field_name = (names != nullptr) ? names[field_idx] : "";
    write_json_string(out, field_name == nullptr ? "" : field_name);
    out << ':';
    out << '[';
    for (size_t elem_idx = 0; elem_idx < nelems; ++elem_idx) {
      if (elem_idx > 0) {
        out << ',';
      }
      auto* field =
          Mat_VarGetStructFieldByIndex(const_cast<matvar_t*>(var), field_idx, elem_idx);
      if (field == nullptr) {
        fail("struct field is missing data");
      }
      write_value(out, field);
    }
    out << ']';
  }
  out << "}}";
}

void write_cell_value(std::ostream& out, const matvar_t* var) {
  out << "{\"kind\":\"cell\",\"dims\":";
  write_dims(out, var);
  out << ",\"elements\":";
  out << '[';
  const auto nelems = numel(var);
  for (size_t idx = 0; idx < nelems; ++idx) {
    if (idx > 0) {
      out << ',';
    }
    auto* cell = Mat_VarGetCell(const_cast<matvar_t*>(var), static_cast<int>(idx));
    if (cell == nullptr) {
      fail("cell element is missing data");
    }
    write_value(out, cell);
  }
  out << "]}";
}

void write_value(std::ostream& out, const matvar_t* var) {
  if (var == nullptr) {
    fail("null MAT variable");
  }

  if (var->class_type == 0 && var->data_type == 0) {
    out << "{\"kind\":\"unknown\",\"dims\":";
    write_dims(out, var);
    out << ",\"class_type\":0,\"data_type\":0}";
    return;
  }

  if (var->isLogical) {
    out << "{\"kind\":\"logical\",\"dims\":";
    write_dims(out, var);
    out << ",\"data\":";
    write_logical_list(out, var);
    out << '}';
    return;
  }

  switch (var->class_type) {
    case MAT_C_CHAR:
      out << "{\"kind\":\"char\",\"dims\":";
      write_dims(out, var);
      out << ",\"value\":";
      write_json_string(out, decode_char_data(var));
      out << '}';
      return;
    case MAT_C_DOUBLE:
      if (var->isComplex) {
        write_complex_value<double>(out, var, "complex_double");
      } else {
        write_numeric_value<double>(out, var, "double");
      }
      return;
    case MAT_C_SINGLE:
      if (var->isComplex) {
        write_complex_value<float>(out, var, "complex_single");
      } else {
        write_numeric_value<float>(out, var, "single");
      }
      return;
    case MAT_C_INT8:
      write_numeric_value<int8_t>(out, var, "int8");
      return;
    case MAT_C_UINT8:
      write_numeric_value<uint8_t>(out, var, "uint8");
      return;
    case MAT_C_INT16:
      write_numeric_value<int16_t>(out, var, "int16");
      return;
    case MAT_C_UINT16:
      write_numeric_value<uint16_t>(out, var, "uint16");
      return;
    case MAT_C_INT32:
      write_numeric_value<int32_t>(out, var, "int32");
      return;
    case MAT_C_UINT32:
      write_numeric_value<uint32_t>(out, var, "uint32");
      return;
    case MAT_C_INT64:
      write_numeric_value<int64_t>(out, var, "int64");
      return;
    case MAT_C_UINT64:
      write_numeric_value<uint64_t>(out, var, "uint64");
      return;
    case MAT_C_STRUCT:
      write_struct_value(out, var);
      return;
    case MAT_C_CELL:
      write_cell_value(out, var);
      return;
    case MAT_C_EMPTY:
      out << "{\"kind\":\"empty\",\"dims\":";
      write_dims(out, var);
      out << '}';
      return;
    default:
      fail("unsupported MATLAB class in MATIO oracle");
  }
}

}  // namespace

int main(int argc, char** argv) {
  try {
    if (argc != 3 || std::string_view(argv[1]) != "dump") {
      std::cerr << "usage: matio_oracle dump <path>\n";
      return 2;
    }

    MatFilePtr mat(Mat_Open(argv[2], MAT_ACC_RDONLY));
    if (!mat) {
      std::cerr << "failed to open MAT file\n";
      return 3;
    }

    std::cout << "{\"variables\":{";
    bool first = true;
    while (matvar_t* raw = Mat_VarReadNext(mat.get())) {
      MatVarPtr var(raw);
      if (var->name == nullptr || var->name[0] == '#') {
        continue;
      }
      if (!first) {
        std::cout << ',';
      }
      first = false;
      write_json_string(std::cout, var->name);
      std::cout << ':';
      write_value(std::cout, var.get());
    }
    std::cout << "}}\n";
    return 0;
  } catch (const std::exception& err) {
    std::cerr << err.what() << '\n';
    return 1;
  }
}