Skip to content

fl::json: custom 64-bit packed tagged-number type (replaces variant<i64, float, double> in #3002) #3022

Closed

Description

@zackees

Motivation

Spinning out of #3002 (drop libgcc soft-FP bloat in fl::json on Cortex-M0+ / no-FPU). The current proposal in #3002 is fl::variant<fixed-point types> for the numeric slot of the JSON value variant. After more thought that design wastes the 64-bit storage budget:

  • fl::variant<...> carries a separate u8 discriminator outside the payload bytes, so the effective JSON-value slot is max(alternative_size) + 1B tag + padding — minimum 9 B, usually padded to 16 B on the alignment of the largest alternative.
  • All existing fl::fixed_point<> types are 32-bit only (s0x32, s16x16, u24x8, ...). To represent the integer ranges JSON-RPC traffic in (microsecond timestamps, LED counts, file offsets, money in fixed-point cents) we need at least 60 effective bits of payload.
  • fl::variant<i64, fl::sfixed_integer<...>, fl::ufixed_integer<...>> would either truncate the integer range (each alternative is 32 b) or add even more discriminator + padding overhead.

Proposal

A purpose-built packed 64-bit tagged number that lives in exactly one 64-bit slot of json_value::variant_t, replacing both the i64 and float alternatives currently there:

namespace fl {

struct json_number {
    // 64 bits total.
    //   Bits [63:61]  tag  (3 bits, 8 representations)
    //   Bits [60:0]   payload (61 bits)
    fl::u64 raw;

    enum class Tag : fl::u8 {
        SIGNED_INT      = 0,   // payload = sign-extended 61-bit signed integer
        UNSIGNED_INT    = 1,   // payload = 61-bit unsigned integer
        FIXED_Q30_31    = 2,   // 1 sign bit + 30 int bits + 30 frac bits  (covers ~±10^9 with ~10^-9 resolution)
        FIXED_Q15_46    = 3,   // 1 sign bit + 14 int bits + 46 frac bits  (covers ±16 384, sub-ppm fractional precision — ratios / brightness)
        FIXED_UQ32_29   = 4,   // 32 int bits + 29 frac bits (unsigned)    (covers timestamps with sub-ns fractions if needed)
        // Reserved tags 5..7 for future expansion (e.g. signed bigint, IEEE-half on host, NaN sentinel for `error` numbers from parse failures, ...).
        RESERVED_5      = 5,
        RESERVED_6      = 6,
        RESERVED_7      = 7,
    };

    constexpr Tag tag() const FL_NOEXCEPT { return static_cast<Tag>(raw >> 61); }
    constexpr fl::u64 payload_bits() const FL_NOEXCEPT { return raw & 0x1FFF'FFFF'FFFF'FFFFULL; }

    // Construction (only constexpr-safe int paths; fixed-point paths must
    // call the explicit factory functions below to make the loss-of-precision
    // intent visible at the call site).
    static constexpr json_number from_i64(fl::i64 v) FL_NOEXCEPT;
    static constexpr json_number from_u64(fl::u64 v) FL_NOEXCEPT;
    static json_number from_q30_31(fl::i32 int_part, fl::u32 frac_part) FL_NOEXCEPT;
    static json_number from_double_lossy(double v) FL_NOEXCEPT;   // host only — selects best Tag
    static json_number from_float_lossy(float v) FL_NOEXCEPT;     // host only — same

    // Extraction (always defined; integer extraction saturates on FP tags).
    constexpr fl::i64    to_i64() const FL_NOEXCEPT;
    constexpr fl::u64    to_u64() const FL_NOEXCEPT;
    // The to_float / to_double paths are gated behind FL_PLATFORM_HAS_LARGE_MEMORY
    // — on Low-memory targets they compile-error to keep the soft-FP cascade
    // permanently absent from the link. Callers that need a float on those
    // platforms must explicitly use the fixed-point Q-format extractors
    // below (`to_q30_31()` etc.) so the loss-of-precision intent is visible.
    float   to_float()  const FL_NOEXCEPT;
    double  to_double() const FL_NOEXCEPT;

    // Q-format extractors (always available — pure integer math).
    fl::pair<fl::i32, fl::u32> to_q30_31() const FL_NOEXCEPT;
    // ... one per Q-format Tag.
};

}  // namespace fl

Why this fits the fl::json use case

  1. No IEEE 754 on the wire. Every conversion between tags is integer arithmetic on raw (sign-extend, bit-shift, mask). The soft-FP cascade we identified during LPC845 bring-up (__aeabi_dadd/__aeabi_dmul chains via _floatdisf.o / _fixunssfdi.o) is structurally absent from this path.
  2. JSON-RPC numbers fit comfortably. Protocol IDs, LED counts, GPIO indices, millis timestamps, money/cents/ppm fractions — every realistic JSON-RPC payload type maps cleanly to one of the four Tags above. The SIGNED_INT / UNSIGNED_INT tags alone (61 bits) cover the full int64 range with one bit of headroom.
  3. One slot in json_value::variant_t instead of two. Today the variant carries i64 and float as separate alternatives, eating two variant-tag positions and forcing every type-conversion visitor to enumerate both. After this lands the variant carries one json_number alternative; the type-conversion visitors fan out across Tags inline (one switch on n.tag()) instead of across variant alternatives.
  4. The 8-bit variant discriminator stops growing. fl::variant discriminates between alternatives with a u8 tag; we're removing one alternative (float) and replacing the i64 slot with json_number — net minus-one alternative, free space for future variant alternatives (e.g. fl::vector<u16> audio buckets if those land).
  5. Host stays on double via the template parameter from fl::json: replace double with templated fixed-point variant to drop libgcc soft-FP bloat on embedded #3002. When FL_PLATFORM_HAS_LARGE_MEMORY=1, the json_value's number slot can stay on double so the host IEEE 754 round-trip tests do not lose precision. The template choice gates json_number to double at compile time.

Why this is NOT covered by existing fl::fixed_point<>

The existing fl::fixed_point<IntBits, FracBits, Sign> templates (src/fl/math/fixed_point/) are deliberately 32-bit only — see src/fl/math/fixed_point.h:18-20:

Available types (IntBits.FracBits):
Signed: s0x32, s4x12, s8x8, s8x24, s12x4, s16x16, s24x8
Unsigned: u0x32, u4x12, u8x8, u8x24, u12x4, u16x16, u24x8

json_number needs >=60 effective payload bits to represent int64 ranges. The right move is a new sibling type specific to the JSON number slot, not a 64-bit extension of fl::fixed_point<> (which has its own carefully-tuned SIMD / promotion / saturation behavior that does not transfer to a tagged-union representation).

Out of scope

  • General-purpose use outside fl::json. If json_number proves useful elsewhere it can promote to a public utility later — but the design constraint here is "fits one 64-bit slot of fl::json's variant", not "is the canonical FastLED 64-bit number".
  • IEEE 754 storage. If a host-side caller really needs full double precision, they use the existing host config (FL_PLATFORM_HAS_LARGE_MEMORY=1, json_value stays on double).
  • NaN / Inf representation in the embedded path. JSON itself does not allow NaN / Inf in the standard, and the embedded path is fixed-point; any host-side from_double_lossy(NaN) must throw a parse error (or map to a RESERVED_* sentinel — design decision deferred).

Acceptance criteria

  1. sizeof(fl::json_number) == 8 and alignof(fl::json_number) == 8 on every supported platform.
  2. Construction + extraction round-trips for every Tag (host unit tests under tests/fl/stl/json/json_number.cpp):
    • i64 -> from_i64 -> to_i64: bitwise identity within the 61-bit range, saturating outside.
    • u64 -> from_u64 -> to_u64: same.
    • q30_31 -> from_q30_31 -> to_q30_31: bitwise identity.
    • q15_46 / uq32_29: same.
  3. to_double() / to_float() symbol-strip check: when FL_PLATFORM_HAS_LARGE_MEMORY=0 and a TU references either method, the build fails at compile time with a static_assert pointing the caller at the Q-format extractors. (Prevents the host-only path from accidentally linking into an embedded target.)
  4. fl::json's variant_t is updated: i64 and float alternatives are removed, replaced by a single fl::json_number alternative (on embedded). Host config keeps double separately.
  5. The JSON parser's number path uses hand-rolled integer parsers feeding json_number::from_*, never strtod / strtof.
  6. The full fl::json: replace double with templated fixed-point variant to drop libgcc soft-FP bloat on embedded #3002 success criterion support TLS3001 #1 (zero __aeabi_d* / __aeabi_f* symbols in the LPC845 ELF) passes via arm-none-eabi-nm -C firmware.elf | grep -E '(aeabi_d|aeabi_f|__[gle]q?[ds]f|scalbn|lround|fmod|atan|acos)' producing empty output.

Related

Filed via Claude Code per the request in the design discussion on #3002.

Activity

  1. zackees commented on Jun 14, 2026

    @zackees
    MemberAuthor

    Design discussion follow-up: why to_float() / to_double() are gated, not bit-cast through

    Capturing a design back-and-forth from the conversation that filed this issue.

    Q: Could we just do to_double() / to_float() via integer ops + bit_cast to FP, avoiding the soft-FP cascade?

    The intuition: a fl::bit_cast<float>(u32_bits) is free on no-FPU silicon — it's purely a type-system reinterpretation, no instruction emitted. Compute the IEEE 754 bit pattern from the tagged payload using integer arithmetic, then bit_cast to float / double.

    A: The bit_cast is free, but the contract isn't.

    Five risks, in order of severity:

    1. The caller poisons the link, not the converter.

    Once to_float() returns a float, the call site doing anything with it — f + 1.0f, f * 0.5f, printf("%f", f), even passing it as an argument under some calling conventions — drags the soft-FP cascade right back in.

    The gate isn't really protecting the converter, it's protecting downstream consumers from accidentally crossing the FP arithmetic boundary. A non-gated to_float() would be a structural footgun: the JSON path stays clean, the sketch's response handler one frame up the stack pulls in 6 KB.

    2. We'd be reimplementing libgcc's int→FP family from scratch.

    Producing the correct IEEE 754 bit pattern from an int64 or Q-format payload requires:

    • Count-leading-zeros normalisation to find the exponent.
    • Round-to-nearest-even on the mantissa truncation (n→53 bits for double, n→24 for float). Truncating without rounding gives results that differ from (double)int64 by 0.5 ULP roughly 50% of the time — small enough to pass casual tests, big enough to fail JSON round-trip golden files.
    • Denormal / subnormal handling at the very-small end. A naïve converter that emits a subnormal can trigger micro-exception cascades on platforms with traps enabled.
    • Sign-zero handling (distinguishing +0.0 from -0.0 when the source had no sign).

    That's ~200–500 bytes per converter, written and tested ourselves. The bloat doesn't vanish — it just moves from libgcc into our object file, and now we own the bugs.

    3. Q-format → float is even worse.

    For e.g. FIXED_Q30_31, you have a 60-bit fixed value and need to compute value × 2⁻³¹ as a double. Same normalisation + rounding work as int→float, plus you have to handle the fractional bits. Same code size, same rounding pitfalls.

    4. Tooling won't see your hand-rolled converter as soft-FP.

    The acceptance-criterion grep in #3002 — arm-none-eabi-nm -C firmware.elf | grep -E '(aeabi_d|...)' — succeeds because the canonical libgcc symbols aren't referenced. But the bloat is still in the binary as fl::json_number::to_float and friends. The metric becomes misleading; the regression test passes while the budget gets eaten.

    5. The lopsided contract is the real problem.

    to_double() working "for free" on a low-memory target invites callers to write auto x = n.to_double(); doSomething(x); — and then the build fails three levels of inlining deep with a soft-FP linkage error that's hard to attribute. The static_assert gate is a hard cut at the API boundary that says "if you want a float here, use the Q-format extractor and convert yourself, knowing exactly which FP cost you're opting into."

    Q: So to_double and to_float are gated on libm inclusion?

    Close, but with one clarification: the gate is on FL_PLATFORM_HAS_LARGE_MEMORY (the platform-tier macro from #3019), not literally on libm inclusion.

    The two correlate but aren't identical:

    • Low-memory tier (FL_PLATFORM_HAS_LARGE_MEMORY=0) — LPC845, ATmega, ESP8266, Teensy LC/3.x, STM32F1, etc. Soft-FP and libm together cost ~6 KB of flash that we can't spare. The static_assert in to_float() / to_double() fires at compile time on these targets.
    • Large/Huge tier (FL_PLATFORM_HAS_LARGE_MEMORY=1) — ESP32, Teensy 4.x/3.5+, SAMD51, host. Either has an FPU (so soft-FP is irrelevant) or has enough flash that the libgcc helpers are noise. to_float() / to_double() compile normally.

    What this gates is the arithmetic boundary, not the libm symbol presence. A hypothetical bare-metal Cortex-M7 with hardware FP and no libm linked would still let the methods through — and rightly so, because the hardware FPU handles it.

    A more pedantically accurate phrasing of the contract:

    to_float() / to_double() are available iff the platform tier asserts "FP arithmetic is affordable here." On the Low-memory tier they static_assert-fail; callers must convert through the Q-format extractors and own the precision-loss decision explicitly.

    Whether libm itself ends up linked depends on what else in the binary uses it — but at the JSON path's API surface, the gate is FL_PLATFORM_HAS_LARGE_MEMORY. That's the right axis because the goal is "don't let the JSON layer be the thing that drags FP into the link," not "guarantee libm is absent" (a more demanding property that's a different issue's problem to enforce).

  2. zackees commented on Jun 14, 2026

    @zackees
    MemberAuthor

    Design clarification on FL_JSON_HAS_FLOAT=0 parser semantics

    After in-flight discussion: when FL_JSON_HAS_FLOAT=0, the parser must take over the conversion of fractional JSON numbers, not just truncate them. The library owns the float-to-fixed-point conversion path; callers should not silently lose precision because the JSON source contained "3.14" instead of "3".

    Concrete plan for the in-flight PR for #3022 (phase 1):

    1. The JsonToken::NUMBER branch on FL_JSON_HAS_FLOAT=0 currently parses the integer prefix and discards the .NNN[eN] suffix. That is a placeholder. Before phase 1 ships, it must be replaced with one of:

      • A Q30.31 fixed-point parse (per the design's FIXED_Q30_31 Tag) — the parser scans int_part, then frac_part as a fixed-precision count of decimal digits, scales to 31 bits, packs into the integer payload. Always pure integer arithmetic. Or
      • Storing the raw string and routing extraction through to_q30_31() / to_qN_M() extractors on demand — matches the json_number::from_* factory style in the parent design.
    2. The as_int()/as_q*() extractors on the resulting json_value must round-trip without ever touching IEEE-754. (Verified at link time by the existing arm-none-eabi-nm symbol-strip check.)

    3. The narrow phase-1-minimal version of this PR (fl::json: custom 64-bit packed tagged-number type (replaces variant<i64, float, double> in #3002) #3022) intentionally lands the structural removal of the float / vector<float> variant alternatives + parser/serializer float gates first, with a placeholder integer-prefix parse for fractional numbers, marked TODO referencing this comment. The Q-format extractor work follows in a phase-2 PR so each step ships verifiable LPC-side bloat reductions without bundling two design changes.

    This avoids the "silently truncating user data" footgun for embedded callers that parse JSON-RPC payloads carrying ratios or fractional fields.

  3. zackees commented on Jun 19, 2026

    @zackees
    MemberAuthor

    Closing -- phase 1 shipped in #3294

    The structural pieces of this issue have landed:

    1. 64-bit packed tagged number type. fl::number lives in src/fl/math/number.h per the design's storage shape:

      • raw : fl::u64 -- exactly 64 bits, slots into the JSON variant cell without padding overhead (FL_STATIC_ASSERT enforces).
      • 3-bit tag enum at bits [63:61]: SIGNED_INT, UNSIGNED_INT, FLOAT_60, plus RESERVED_3..7 slots for future expansion (Q-format fixed-point, NaN sentinel, IEEE-half on host).
      • 61-bit payload at bits [60:0].
      • Factories from_signed(i64) / from_unsigned(u64) saturate on overflow so a call site never silently aliases into a different tag's payload semantics.
      • Accessors get_tag(), payload(), as_signed_payload() with sign-extension.
    2. Integer IEEE-754 bit-codec relocated to fl/math/. The json_double_to_float narrowing path from feat(json): integer-only IEEE 754 codec replaces soft-FP cascade (refs #3022) #3038 plus a new soft_float_to_double widening companion now live in fl/math/soft_float.h -- accessible to non-JSON callers. JSON internally delegates via a thin types_impl.h shim.

    3. JSON as_float / as_double no longer leaks soft-FP on no-FPU targets. The two residual static_cast<double>(float) / static_cast<float>(double) sites in float_conversion_visitor (which would have anchored __aeabi_f2d / __aeabi_d2f if the path survived DCE) now route through the integer bit-codec.

    What's NOT in #3294, and is left for follow-up issues:

    • FLOAT_60 parser/serializer: the tag enum exists, but no from_float_60 / as_float_60 factories yet. Will require a 60-bit-mantissa custom IEEE-like layout (sign + 11-bit exp + 49-bit mantissa) with its own widen/narrow against IEEE-754 double, and updates to the JSON parser to recognize fractional numbers and pack them into a FLOAT_60 payload.
    • JSON variant slot swap: json_value's variant currently still holds i64 / float / double as separate alternatives. Swapping to a single fl::number slot is a separate refactor that touches the schema/serializer/RPC plumbing.
    • FASTLED_JSON_HAS_FLOAT=0 integer-only parser path: the design called for the parser to take over float-to-fixed-point conversion when float is disabled. That's the phase-2 work referenced in the prior comment.

    These are filed as separate follow-ups so each ships a self-contained measurable improvement instead of bundling design decisions.

    Closing this issue -- the foundational fl::number shape and bit-codec relocation are in. The remaining work is sub-issue-able with concrete acceptance criteria once the variant-slot swap is scoped.

    Filed via /clud-fix burn-down on meta #3208.

  4. moved this from Triage to Done in FastLED Trackeron Jun 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions