Repository navigation
Description
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 separateu8discriminator outside the payload bytes, so the effective JSON-value slot ismax(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 flWhy this fits the fl::json use case
- 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_dmulchains via_floatdisf.o/_fixunssfdi.o) is structurally absent from this path. - 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_INTtags alone (61 bits) cover the full int64 range with one bit of headroom. - One slot in
json_value::variant_tinstead of two. Today the variant carriesi64andfloatas separate alternatives, eating two variant-tag positions and forcing every type-conversion visitor to enumerate both. After this lands the variant carries onejson_numberalternative; the type-conversion visitors fan out across Tags inline (one switch onn.tag()) instead of across variant alternatives. - The 8-bit variant discriminator stops growing.
fl::variantdiscriminates between alternatives with au8tag; we're removing one alternative (float) and replacing thei64slot withjson_number— net minus-one alternative, free space for future variant alternatives (e.g.fl::vector<u16>audio buckets if those land). - Host stays on
doublevia the template parameter from fl::json: replace double with templated fixed-point variant to drop libgcc soft-FP bloat on embedded #3002. WhenFL_PLATFORM_HAS_LARGE_MEMORY=1, thejson_value's number slot can stay ondoubleso the host IEEE 754 round-trip tests do not lose precision. The template choice gatesjson_numbertodoubleat 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. Ifjson_numberproves useful elsewhere it can promote to a public utility later — but the design constraint here is "fits one 64-bit slot offl::json's variant", not "is the canonical FastLED 64-bit number". - IEEE 754 storage. If a host-side caller really needs full
doubleprecision, they use the existing host config (FL_PLATFORM_HAS_LARGE_MEMORY=1,json_valuestays ondouble). - 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 aRESERVED_*sentinel — design decision deferred).
Acceptance criteria
sizeof(fl::json_number) == 8andalignof(fl::json_number) == 8on every supported platform.- 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.
to_double()/to_float()symbol-strip check: whenFL_PLATFORM_HAS_LARGE_MEMORY=0and 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.)fl::json's variant_t is updated:i64andfloatalternatives are removed, replaced by a singlefl::json_numberalternative (on embedded). Host config keepsdoubleseparately.- The JSON parser's number path uses hand-rolled integer parsers feeding
json_number::from_*, neverstrtod/strtof. - 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 viaarm-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
- fl::json: replace double with templated fixed-point variant to drop libgcc soft-FP bloat on embedded #3002 — parent issue (
fl::json: replace double with templated fixed-point variant). This issue is the concrete number-type design that lands inside fl::json: replace double with templated fixed-point variant to drop libgcc soft-FP bloat on embedded #3002. - Rename SKETCH_HAS_*_MEMORY macros to FL_PLATFORM_HAS_*_MEMORY #3000 —
FL_PLATFORM_HAS_*_MEMORYcanonical names (already merged via refactor(system): introduce FL_PLATFORM_HAS_*_MEMORY canonical names (closes #3000) #3019); used as the compile-time switch forto_double()/to_float()gating above. src/fl/math/fixed_point/— existing 32-bit fixed-point templates; sibling, not replaced.
Filed via Claude Code per the request in the design discussion on #3002.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
zackees commentedon Jun 14, 2026
Design discussion follow-up: why
to_float()/to_double()are gated, not bit-cast throughCapturing 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_castto 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 afloat, 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:
(double)int64by 0.5 ULP roughly 50% of the time — small enough to pass casual tests, big enough to fail JSON round-trip golden files.+0.0from-0.0when 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 computevalue × 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 asfl::json_number::to_floatand 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 writeauto 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_doubleandto_floatare 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:
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. Thestatic_assertinto_float()/to_double()fires at compile time on these targets.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:
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).zackees commentedon Jun 14, 2026
Design clarification on
FL_JSON_HAS_FLOAT=0parser semanticsAfter 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):
The
JsonToken::NUMBERbranch onFL_JSON_HAS_FLOAT=0currently 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:Q30.31fixed-point parse (per the design'sFIXED_Q30_31Tag) — the parser scansint_part, thenfrac_partas a fixed-precision count of decimal digits, scales to 31 bits, packs into the integer payload. Always pure integer arithmetic. Orto_q30_31()/to_qN_M()extractors on demand — matches thejson_number::from_*factory style in the parent design.The
as_int()/as_q*()extractors on the resultingjson_valuemust round-trip without ever touching IEEE-754. (Verified at link time by the existingarm-none-eabi-nmsymbol-strip check.)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.
feat(json): remove float truncation fallback + add fixed_point setter (…
feat(json): introduce fl::json_number packed-tag Q-format number (#3022/
feat(json): integer-only IEEE 754 codec replaces soft-FP cascade (refs …
feat(autoresearch): retire AutoResearchLpc.ino, fold into AutoResearc…
refactor(math): move JSON soft-FP bit-codec into fl/math/ + fl::numbe…
zackees commentedon Jun 19, 2026
Closing -- phase 1 shipped in #3294
The structural pieces of this issue have landed:
64-bit packed tagged number type.
fl::numberlives insrc/fl/math/number.hper the design's storage shape:raw : fl::u64-- exactly 64 bits, slots into the JSON variant cell without padding overhead (FL_STATIC_ASSERT enforces).tagenum at bits [63:61]:SIGNED_INT,UNSIGNED_INT,FLOAT_60, plusRESERVED_3..7slots for future expansion (Q-format fixed-point, NaN sentinel, IEEE-half on host).from_signed(i64)/from_unsigned(u64)saturate on overflow so a call site never silently aliases into a different tag's payload semantics.get_tag(),payload(),as_signed_payload()with sign-extension.Integer IEEE-754 bit-codec relocated to
fl/math/. Thejson_double_to_floatnarrowing path from feat(json): integer-only IEEE 754 codec replaces soft-FP cascade (refs #3022) #3038 plus a newsoft_float_to_doublewidening companion now live infl/math/soft_float.h-- accessible to non-JSON callers. JSON internally delegates via a thintypes_impl.hshim.JSON
as_float/as_doubleno longer leaks soft-FP on no-FPU targets. The two residualstatic_cast<double>(float)/static_cast<float>(double)sites infloat_conversion_visitor(which would have anchored__aeabi_f2d/__aeabi_d2fif the path survived DCE) now route through the integer bit-codec.What's NOT in #3294, and is left for follow-up issues:
FLOAT_60parser/serializer: the tag enum exists, but nofrom_float_60/as_float_60factories 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 aFLOAT_60payload.json_value's variant currently still holdsi64/float/doubleas separate alternatives. Swapping to a singlefl::numberslot is a separate refactor that touches the schema/serializer/RPC plumbing.FASTLED_JSON_HAS_FLOAT=0integer-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::numbershape 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.