Skip to content

fix(json): use integer float conversion for low-memory JSON - #3211

Merged
zackees merged 1 commit into
masterfrom
codex/fix-json-lowmem-float-gates
Jun 18, 2026
Merged

zackees merged 1 commit into
masterfrom
codex/fix-json-lowmem-float-gates

Conversation

@zackees

@zackees zackees commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Fixes #3029.
Updates #3208.

Summary

  • Keep fl::json float/double entry points available on low-memory targets while avoiding floating-point arithmetic in the conversion path.
  • Convert 64-bit double inputs to JSON's single-precision float storage with integer IEEE-754 bit handling, including NaN/inf preservation and overflow saturation to infinity.
  • Convert FastLED fixed-point values to JSON float storage with integer bit construction, including saturation when the fixed-point magnitude is too large for single precision.
  • Keep direct float inputs as existing float storage, avoid unnecessary float -> double promotion in ScreenMap::toJson, and continue gating JSON UI implementation files that do real floating-point parsing/arithmetic behind FL_JSON_FLOAT_ENABLED.

Validation

  • bash test --cpp tests/fl/stl/json.cpp
  • bash compile uno --examples Blink --backend fbuild
  • bash compile lpc845brk --examples AutoResearch --backend fbuild passed: flash 62.47 KB / 64 KB, RAM 10.99 KB / 16 KB.

Upgrade Notes

No user-facing upgrade is required for existing JSON float callers. Low-memory builds should continue to use the same fl::json(float), fl::json(double), and fixed-point JSON APIs; the conversion is now handled without depending on target floating-point conversion helpers.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added fixed-point numeric type support for JSON values, including constructors, setters, and as_fixed_point<FP>() extraction.
  • Improvements

    • Enhanced JSON float handling with IEEE-754 bit-accurate conversion.
    • Updated JSON geometry (v2) to emit x/y, diameter, and an integer version.
    • UI JSON number fields and sliders now compile only when float JSON support is enabled.
  • Bug Fixes

    • Adjusted JSON-related warning behavior for builds without JSON support.
  • Tests

    • Added regression coverage for fixed-point round-trips and IEEE-754 conversions.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7083b984-b36c-4620-ba3e-cb76320c9837

📥 Commits

Reviewing files that changed from the base of the PR and between 5c9f24c and 02e6a65.

📒 Files selected for processing (8)
  • src/fl/math/screenmap.cpp.hpp
  • src/fl/stl/json.h
  • src/fl/stl/json/types.h
  • src/fl/stl/json/types.impl.hpp
  • src/platforms/shared/ui/json/json_console.cpp.hpp
  • src/platforms/shared/ui/json/number_field.cpp.hpp
  • src/platforms/shared/ui/json/slider.cpp.hpp
  • tests/fl/stl/json.cpp
✅ Files skipped from review due to trivial changes (3)
  • src/platforms/shared/ui/json/slider.cpp.hpp
  • src/fl/stl/json/types.impl.hpp
  • src/platforms/shared/ui/json/json_console.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/platforms/shared/ui/json/number_field.cpp.hpp
  • src/fl/stl/json/types.h
  • src/fl/math/screenmap.cpp.hpp
  • src/fl/stl/json.h

📝 Walkthrough

Walkthrough

Introduces FL_JSON_FLOAT_ENABLED (defaulting to FL_PLATFORM_HAS_LARGE_MEMORY) and gates all fl::json float/double constructors, assignment operators, and set() overloads behind it. Adds a detail::is_fl_fixed_point trait enabling fixed-point constructors, assignment, and an as_fixed_point<FP>() extractor on fl::json. Implements IEEE-754 bit-level double-to-float conversion to avoid soft-FP on low-memory targets. Platform UI components (slider, number_field, json_console) are guarded by the same flag. Updates ScreenMap::toJson v2 emission to use proper typed values (float coordinates, integer version).

Changes

FL_JSON_FLOAT_ENABLED Guard and Fixed-Point JSON Integration

Layer / File(s) Summary
IEEE-754 double-to-float conversion and FL_JSON_FLOAT_ENABLED flag
src/fl/stl/json/types.h, src/fl/stl/json/types.impl.hpp
Includes fl/stl/bit_cast.h and fl/system/sketch_macros.h; conditionally defines FL_JSON_FLOAT_ENABLED from FL_PLATFORM_HAS_LARGE_MEMORY. Declares and implements fl::detail helpers for IEEE-754 bit-level double-to-float conversion: json_double_to_float(...), json_ieee754_float_bits_from_scaled_u64(...), json_ieee754_float_bits_from_double_bits(...), plus supporting rounding/shift/log2/bit-copy utilities with subnormal/overflow handling. Updates json_value::operator=(double) to route through json_double_to_float(...).
fl::json fixed-point type support
src/fl/stl/json.h
Adds detail::is_fl_fixed_point trait for detecting fixed-point types; introduces fixed-point constructor and assignment operator that store via FP::raw() as i64; updates double constructor/assignment to use IEEE-754 helper; adds as_fixed_point<FP>() extractor returning fl::optional<FP> that reconstructs via FP::from_raw(...) and prefers internal i64 payload or converts from stored float bits via detail::fixed_raw_from_ieee754_bits(...); adds set(const fl::string& key, FP value) overload forwarding to set(key, json(value)).
Platform UI and ScreenMap conditional compilation
src/platforms/shared/ui/json/json_console.cpp.hpp, src/platforms/shared/ui/json/number_field.cpp.hpp, src/platforms/shared/ui/json/slider.cpp.hpp, src/fl/math/screenmap.cpp.hpp
json_console.cpp.hpp adds unconditional types.h include and expands guard to SKETCH_HAS_LARGE_MEMORY && FL_JSON_FLOAT_ENABLED; removes duplicated json.h. number_field.cpp.hpp and slider.cpp.hpp wrap entire float implementations in #if FL_JSON_FLOAT_ENABLED / #endif guards. ScreenMap::toJson emits x/y coordinates directly as float without static_cast<double>(...), emits diameter without cast, emits version as i64(2) instead of floating-point, and simplifies warning macro from FL_WARN_F(...) to FL_WARN(...). On FL_JSON_FLOAT_ENABLED=0, float implementations drop from archive.
Fixed-point and IEEE-754 conversion test coverage
tests/fl/stl/json.cpp
Adds fl/math/fixed_point.h include. New test case verifies fl::fixed_point<16,16> raw bits survive json construction and as_fixed_point<FP>() extraction for direct values and object-key storage. New test case validates internal json_ieee754_float_bits_from_scaled_u64(...) saturates oversized magnitudes to +inf/-inf bit patterns. Extended test case verifies json constructed from IEEE-754 double bit patterns extracts as float with expected bit-level results including overflow to +inf and NaN mapping via fl::bit_cast comparison.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3087: Both PRs modify the fl::json floating-point handling to be conditioned on the large-memory build flags, changing how doubles/floats are converted in the JSON codec paths.
  • FastLED/FastLED#3100: Both PRs modify ScreenMap::toJson's v2 JSON emission (including the top-level version/field formatting and generated segment data), so the changes overlap at the same serializer code path.
  • FastLED/FastLED#3137: The retrieved PR updates tests/fl/stl/json.cpp's ScreenMap serialization assertions to match the v2 version/groups/segments JSON shape, which aligns with the main PR's corresponding ScreenMap::toJson(...) v2 JSON emission changes.

Poem

🐰 Hoppity-hop through the compile tree,
No soft-FP floats where they shouldn't be!
Fixed-point bits in IEEE-754's care,
FL_JSON_FLOAT_ENABLED guards float everywhere.
Raw round-trips done on platforms lean —
The fastest, leanest JSON you've seen! 🚀

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.76% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective of implementing integer-based float conversion for low-memory JSON builds, which is the primary focus of all code changes.
Linked Issues check ✅ Passed The PR successfully addresses all primary objectives from issue #3029: implements IEEE-754 bit-level float conversions avoiding FP operations, adds fixed-point JSON APIs, and gates float-consuming UI files behind FL_JSON_FLOAT_ENABLED.
Out of Scope Changes check ✅ Passed All changes are directly aligned with the issue objectives: integer-based float/double conversions, fixed-point JSON integration, conditional compilation gates for UI implementations, and corresponding test coverage.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-json-lowmem-float-gates

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
tests/fl/stl/json.cpp (1)

1602-1616: ⚡ Quick win

Exercise the fixed-point assignment overload too.

This covers construction and set(), but the new json& operator=(FP) path remains untested. A direct assignment check keeps the public fixed-point API covered.

Proposed test addition
     json value(original);
     auto extracted = value.as_fixed_point<FP>();
     FL_REQUIRE(extracted.has_value());
     FL_CHECK_EQ(extracted->raw(), original.raw());
 
+    json assigned;
+    assigned = original;
+    auto assigned_value = assigned.as_fixed_point<FP>();
+    FL_REQUIRE(assigned_value.has_value());
+    FL_CHECK_EQ(assigned_value->raw(), original.raw());
+
     json obj = json::object();
     obj.set("gain", original);
     auto object_value = obj["gain"].as_fixed_point<FP>();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fl/stl/json.cpp` around lines 1602 - 1616, The test currently covers
json construction from a fixed_point value and the set() method, but does not
test the direct assignment operator. Add a test case that exercises the json&
operator=(FP) assignment path by directly assigning a fixed_point value to a
json object using the subscript operator and assignment syntax, then verify the
value was correctly assigned by extracting and comparing it back to the
original.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/math/screenmap.cpp.hpp`:
- Line 373: Replace the `FL_WARN_F` macro call in the ScreenMap::toJson method
with the stream-style `FL_WARN` macro. Change from using `FL_WARN_F` with
formatted string syntax to using `FL_WARN` with the `<<` stream operator to
maintain consistency with the repository's warning logging guidelines.

In `@src/fl/stl/json.h`:
- Around line 334-341: The as_fixed_point() method currently uses
mValue->as_int() which performs automatic type conversions from strings, bools,
and floats, allowing non-integer values to be incorrectly extracted as
fixed-point types. Instead, access the raw i64 slot directly from mValue and
validate that the value exists in that slot and fits within the range of the
fixed-point raw type before calling FP::from_raw. This ensures fixed-point
values are only extracted when they were actually stored as raw integers in the
JSON i64 slot.

In `@src/fl/stl/json/types.h`:
- Around line 28-30: The macro FL_JSON_HAS_FLOAT uses the
FL_<COMPONENT>_HAS_<FEATURE> naming convention but is defined with a value
(0/1), which violates the capability-macro contract where such macros should be
defined-or-undefined with no assigned value. Either refactor FL_JSON_HAS_FLOAT
to be a proper capability macro by conditionally defining it without a value
(e.g., just `#define` FL_JSON_HAS_FLOAT) and update all checks from `#ifdef` or `#if`
FL_JSON_HAS_FLOAT to `#if` defined(FL_JSON_HAS_FLOAT), or rename the macro to a
different naming convention (like FL_JSON_FLOAT_ENABLED) if value-based
overrides with -DFL_JSON_HAS_FLOAT=0 semantics are required.

---

Nitpick comments:
In `@tests/fl/stl/json.cpp`:
- Around line 1602-1616: The test currently covers json construction from a
fixed_point value and the set() method, but does not test the direct assignment
operator. Add a test case that exercises the json& operator=(FP) assignment path
by directly assigning a fixed_point value to a json object using the subscript
operator and assignment syntax, then verify the value was correctly assigned by
extracting and comparing it back to the original.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 811f6b6e-1b89-46e0-8828-d29784d26119

📥 Commits

Reviewing files that changed from the base of the PR and between 4c877bb and a1ff4bd.

📒 Files selected for processing (7)
  • src/fl/math/screenmap.cpp.hpp
  • src/fl/stl/json.h
  • src/fl/stl/json/types.h
  • src/platforms/shared/ui/json/json_console.cpp.hpp
  • src/platforms/shared/ui/json/number_field.cpp.hpp
  • src/platforms/shared/ui/json/slider.cpp.hpp
  • tests/fl/stl/json.cpp

Comment thread src/fl/math/screenmap.cpp.hpp Resolved
Comment thread src/fl/stl/json.h Resolved
Comment thread src/fl/stl/json/types.h Resolved
@zackees
zackees force-pushed the codex/fix-json-lowmem-float-gates branch from a1ff4bd to 6bd2557 Compare June 18, 2026 00:25

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/fl/math/screenmap.cpp.hpp (1)

415-432: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Gate ScreenMap float JSON emission behind the float-support flag.

Lines 415/419/432 now always emit fl::json(float). That conflicts with the low-memory contract described for this PR (no float JSON paths when float support is disabled). Please guard this emission path with FL_JSON_FLOAT_ENABLED (or provide a fixed-point/integer emission fallback) so low-memory JSON builds remain float-free.

Proposed minimal guard pattern
 `#if` FASTLED_NO_JSON
     FL_WARN("ScreenMap::toJson called with FASTLED_NO_JSON");
     return;
 `#else`
+#if !FL_JSON_FLOAT_ENABLED
+    FL_WARN("ScreenMap::toJson called without JSON float support");
+    return;
+#endif
     if (!doc) {
         FL_WARN_F("ScreenMap::toJson called with nullptr doc");
         return;
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/math/screenmap.cpp.hpp` around lines 415 - 432, The code currently
unconditionally emits float values to JSON (the x and y array values via
segment[i].x and segment[i].y, and the diameter field) which conflicts with the
low-memory float-free contract when FL_JSON_FLOAT_ENABLED is disabled. Guard the
float emission paths using the FL_JSON_FLOAT_ENABLED preprocessor flag: wrap the
xArray and yArray population loops and the diameter field assignment in the
segmentObj with conditional compilation blocks, and provide integer or
fixed-point alternatives (or skip emission) when the flag is disabled to ensure
the low-memory JSON builds remain float-free.
🧹 Nitpick comments (1)
tests/fl/stl/json.cpp (1)

1602-1622: ⚡ Quick win

Add at least one non-float-exact raw sample to the fixed-point round-trip test.

The current raw sample (0x00018000) is float-exact, so this test can still pass under float-backed storage. Add a case like 0x01000001 to enforce true raw fidelity.

Proposed test extension
 FL_TEST_CASE("json fixed_point raw round-trip") {
     using FP = fl::fixed_point<16, 16>;
     const FP original = FP::from_raw(0x00018000);
+    const FP non_float_exact = FP::from_raw(0x01000001);

     json value(original);
     auto extracted = value.as_fixed_point<FP>();
     FL_REQUIRE(extracted.has_value());
     FL_CHECK_EQ(extracted->raw(), original.raw());
+
+    json precise(non_float_exact);
+    auto precise_extracted = precise.as_fixed_point<FP>();
+    FL_REQUIRE(precise_extracted.has_value());
+    FL_CHECK_EQ(precise_extracted->raw(), non_float_exact.raw());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fl/stl/json.cpp` around lines 1602 - 1622, The test function "json
fixed_point raw round-trip" currently only tests with a float-exact raw value
(0x00018000), which means the test could pass even if the implementation uses
float-backed storage and loses precision. Add an additional test case within
this function using a non-float-exact raw value like 0x01000001 to verify that
raw fixed-point values are preserved accurately through the json round-trip
conversion process. Apply the same test pattern (construct from raw, convert to
json, extract back, verify raw value matches) for this new non-float-exact
value.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/stl/json.h`:
- Around line 275-276: The float/double entry points in the json class (the
json(double d) constructor, operator=(double) assignment operator, and set
method overloads accepting double parameters) are not wrapped with the
FL_JSON_FLOAT_ENABLED preprocessor directive, making them always available
regardless of the macro's definition. Wrap these methods with `#ifdef`
FL_JSON_FLOAT_ENABLED and `#endif` directives to properly gate them. Apply this
gating to the json(double) constructor around line 275, the operator=(double)
method around lines 347-350, and the set(key, double) method around line 883 to
ensure these API surfaces are only exposed when FL_JSON_FLOAT_ENABLED is
explicitly enabled.
- Around line 276-277: The fixed-point constructor template json(FP v) at lines
276-277 and related assignment operators at lines 352-355 and 884-885 are
converting fixed-point values to float before storage, which loses precision for
values outside float mantissa range. Replace the float conversion call
detail::fixed_point_to_float(v) with extraction of the raw fixed-point integer
representation (using FP's underlying integer value or bit representation) and
store this raw value in the i64 JSON slot instead of the float conversion path.
Apply this change consistently across all three template instantiation locations
mentioned to maintain raw fixed-point storage semantics.

In `@src/fl/stl/json/types.h`:
- Around line 35-127: The newly added helper functions
json_round_shift_right_u64, json_floor_log2_u64,
json_ieee754_float_bits_from_scaled_u64,
json_ieee754_float_bits_from_double_bits, and json_double_to_float are defined
directly in the header file within the detail namespace, which violates the
coding guideline that header files in src/**/ should contain declarations only.
Move these function implementations to a corresponding .impl.hpp or .cpp.hpp
file and keep only their declarations in the header file, then include the
implementation file at the end of the header.

---

Outside diff comments:
In `@src/fl/math/screenmap.cpp.hpp`:
- Around line 415-432: The code currently unconditionally emits float values to
JSON (the x and y array values via segment[i].x and segment[i].y, and the
diameter field) which conflicts with the low-memory float-free contract when
FL_JSON_FLOAT_ENABLED is disabled. Guard the float emission paths using the
FL_JSON_FLOAT_ENABLED preprocessor flag: wrap the xArray and yArray population
loops and the diameter field assignment in the segmentObj with conditional
compilation blocks, and provide integer or fixed-point alternatives (or skip
emission) when the flag is disabled to ensure the low-memory JSON builds remain
float-free.

---

Nitpick comments:
In `@tests/fl/stl/json.cpp`:
- Around line 1602-1622: The test function "json fixed_point raw round-trip"
currently only tests with a float-exact raw value (0x00018000), which means the
test could pass even if the implementation uses float-backed storage and loses
precision. Add an additional test case within this function using a
non-float-exact raw value like 0x01000001 to verify that raw fixed-point values
are preserved accurately through the json round-trip conversion process. Apply
the same test pattern (construct from raw, convert to json, extract back, verify
raw value matches) for this new non-float-exact value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 73feee0e-fb18-47f5-b836-6d87afc4a1df

📥 Commits

Reviewing files that changed from the base of the PR and between a1ff4bd and 6bd2557.

📒 Files selected for processing (7)
  • src/fl/math/screenmap.cpp.hpp
  • src/fl/stl/json.h
  • src/fl/stl/json/types.h
  • src/platforms/shared/ui/json/json_console.cpp.hpp
  • src/platforms/shared/ui/json/number_field.cpp.hpp
  • src/platforms/shared/ui/json/slider.cpp.hpp
  • tests/fl/stl/json.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/platforms/shared/ui/json/number_field.cpp.hpp
  • src/platforms/shared/ui/json/slider.cpp.hpp
  • src/platforms/shared/ui/json/json_console.cpp.hpp

Comment thread src/fl/stl/json.h Resolved
Comment thread src/fl/stl/json.h Resolved
Comment thread src/fl/stl/json/types.h Resolved
@zackees
zackees force-pushed the codex/fix-json-lowmem-float-gates branch from 6bd2557 to 5c9f24c Compare June 18, 2026 00:40
@zackees zackees changed the title fix(json): gate float JSON writes on low-memory targets fix(json): use integer float conversion for low-memory JSON Jun 18, 2026
@zackees
zackees force-pushed the codex/fix-json-lowmem-float-gates branch from 5c9f24c to 02e6a65 Compare June 18, 2026 00:48
@zackees

zackees commented Jun 18, 2026

Copy link
Copy Markdown
Member Author

Latest update on the remaining CodeRabbit requested-change threads:

  • The implementation-heavy IEEE conversion helpers were moved out of types.h into types.impl.hpp in 02e6a65.
  • The float/double API gating and raw fixed-point storage comments are superseded by the updated requirement for this PR: keep fl::json(float), fl::json(double), and fixed-point JSON entry points available on low-memory targets, but route fixed-point/double conversion through integer IEEE bit construction instead of target floating-point conversion helpers.
  • Added coverage for oversized scaled fixed-point magnitude saturation and double NaN/overflow conversion.

Local validation for 02e6a65:

  • bash test --cpp tests/fl/stl/json.cpp
  • bash compile uno --examples Blink --backend fbuild
  • bash compile lpc845brk --examples AutoResearch --backend fbuild

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fl::json: FastLED-internal float callers + missing manual fixed-point extractor API leak soft-FP into Low-memory link (gap from #3022 phase 1 / #3027)

1 participant