nk 1.0.0
C++ Numerical Computing Runtime
Loading...
Searching...
No Matches
value_json.hpp
1#pragma once
2//
3// value_json.hpp — per-cell JSON serialization of a numeric Value.
4//
5// Single source of truth for how one matrix cell is turned into a JSON
6// token in the IDE's Variable viewer. Shared by the WASM repl_bindings
7// serializers (emitMatrixDataArray / getVarTileJSON / valuePreview) so
8// that every display path renders integer / single / double / logical
9// values identically — and so the logic stays testable in the native
10// gtest (repl_bindings.cpp itself is an emscripten-only translation unit).
11//
12// CHAR and COMPLEX have their own string framing at the call sites and are
13// intentionally NOT handled here.
14
15#include <nk/value/value.hpp>
16#include <nk/value/value_type.hpp>
17
18#include <string>
19#include <sstream>
20#include <cmath>
21
22namespace nk {
23
24// True for the real scalar/bool element classes numericCellJSON renders:
25// DOUBLE, SINGLE, LOGICAL, and every signed/unsigned integer class.
26// (COMPLEX / CHAR / CELL / STRUCT / FUNC_HANDLE / STRING are excluded —
27// callers frame those separately.)
28inline bool isRealNumericCell(ValueType t)
29{
30 return t == ValueType::DOUBLE || t == ValueType::SINGLE
31 || t == ValueType::LOGICAL || isIntegerType(t);
32}
33
34// JSON token for the cell at column-major linear index `i`.
35// integer classes → exact decimal, no fractional part (e.g. 200)
36// LOGICAL → true / false
37// DOUBLE / SINGLE → NaN → null, +Inf → "Inf", -Inf → "-Inf",
38// finite → full 17-significant-digit decimal
39// Precondition: isRealNumericCell(val.type()) and i < val.numel().
40inline std::string numericCellJSON(const Value &val, std::size_t i)
41{
42 switch (val.type()) {
43 case ValueType::INT8: return std::to_string(static_cast<int>(val.int8Data()[i]));
44 case ValueType::INT16: return std::to_string(static_cast<int>(val.int16Data()[i]));
45 case ValueType::INT32: return std::to_string(val.int32Data()[i]);
46 case ValueType::INT64: return std::to_string(static_cast<long long>(val.int64Data()[i]));
47 case ValueType::UINT8: return std::to_string(static_cast<unsigned>(val.uint8Data()[i]));
48 case ValueType::UINT16: return std::to_string(static_cast<unsigned>(val.uint16Data()[i]));
49 case ValueType::UINT32: return std::to_string(val.uint32Data()[i]);
50 case ValueType::UINT64: return std::to_string(static_cast<unsigned long long>(val.uint64Data()[i]));
51 case ValueType::LOGICAL: return val.logicalData()[i] ? "true" : "false";
52 default: { // DOUBLE / SINGLE
53 double v = val.elemAsDouble(i);
54 if (std::isnan(v)) return "null";
55 if (std::isinf(v)) return v > 0 ? "\"Inf\"" : "\"-Inf\"";
56 std::ostringstream s;
57 s.precision(17);
58 s << v;
59 return s.str();
60 }
61 }
62}
63
64} // namespace nk
Core MATLAB-compatible multidimensional array and scalar value type.
Definition value.hpp:61