Skip to content

Add integer constructors to fixed-point types to avoid soft-float - #2197

Closed
sutaburosu wants to merge 2 commits into
FastLED:masterfrom
sutaburosu:copilot/remove-softfloat
Closed

sutaburosu wants to merge 2 commits into
FastLED:masterfrom
sutaburosu:copilot/remove-softfloat

Conversation

@sutaburosu

@sutaburosu sutaburosu commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Now you can construct fixed_point from an int without pulling in soft float, without doing the .from_raw() dance.

Summary by CodeRabbit

  • New Features
    • Added integer constructors to all fixed-point numeric types, enabling exact construction from integer/unsigned values without intermediate floating-point math.

Copilot AI review requested due to automatic review settings March 13, 2026 07:35
@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a43a0a98-7c16-4c62-8812-174e229ec310

📥 Commits

Reviewing files that changed from the base of the PR and between 0046888 and 0a53eb6.

📒 Files selected for processing (1)
  • src/fl/stl/fixed_point/s16x16.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/fl/stl/fixed_point/s16x16.h

📝 Walkthrough

Walkthrough

Added integer-based constructors to many fixed-point types in src/fl/stl/fixed_point/, allowing exact construction from integers without float intermediates. Also updated src/calculator.py: added/modified coderabbit_formula signature and renamed a global variable.

Changes

Cohort / File(s) Summary
Fixed-point signed integer constructors
src/fl/stl/fixed_point/s12x4.h, src/fl/stl/fixed_point/s16x16.h, src/fl/stl/fixed_point/s24x8.h, src/fl/stl/fixed_point/s4x12.h, src/fl/stl/fixed_point/s8x24.h, src/fl/stl/fixed_point/s8x8.h
Added int constructors (e.g., constexpr sXXxYY(int)) that set internal mValue by casting the int to the appropriate signed type and multiplying by SCALE. No other behavioral changes.
Fixed-point unsigned integer constructors
src/fl/stl/fixed_point/u12x4.h, src/fl/stl/fixed_point/u16x16.h, src/fl/stl/fixed_point/u24x8.h, src/fl/stl/fixed_point/u4x12.h, src/fl/stl/fixed_point/u8x24.h, src/fl/stl/fixed_point/u8x8.h
Added unsigned constructors (e.g., constexpr uXXxYY(unsigned)) that set internal mValue by casting and multiplying by SCALE. Existing float constructors remain.
Calculator class updates
src/calculator.py
Added coderabbit_formula to Calculator and updated its signature to accept three parameters (coderabbit_formula(x, y, z)); renamed a global variable from old_global_var to new_global_var.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 I hopped in code with nimble paws,
I added scales without the flaws,
Integers snug in fixed-point bed,
No floats to fret, no rounding dread.
Hooray — precise math, carrot-fed! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 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 change: adding integer constructors to fixed-point types to avoid soft-float operations.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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

Tip

CodeRabbit can approve the review once all CodeRabbit's comments are resolved.

Enable the reviews.request_changes_workflow setting to automatically approve the review once all CodeRabbit's comments are resolved.

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/fl/stl/fixed_point/s24x8.h`:
- Around line 26-28: The integer constructor s24x8(int n) currently does the
multiplication in 32-bit signed space which can overflow; change it to perform
the multiply in a wider signed type (e.g., i64) and then narrow to i32 when
assigning to mValue using static_cast<i32>(static_cast<i64>(n) * SCALE) so the
intermediate product cannot overflow (follow the same pattern used elsewhere in
this class for safe widening).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 496349cc-077a-429c-9065-24535459577f

📥 Commits

Reviewing files that changed from the base of the PR and between 640f6c5 and 0046888.

📒 Files selected for processing (12)
  • src/fl/stl/fixed_point/s12x4.h
  • src/fl/stl/fixed_point/s16x16.h
  • src/fl/stl/fixed_point/s24x8.h
  • src/fl/stl/fixed_point/s4x12.h
  • src/fl/stl/fixed_point/s8x24.h
  • src/fl/stl/fixed_point/s8x8.h
  • src/fl/stl/fixed_point/u12x4.h
  • src/fl/stl/fixed_point/u16x16.h
  • src/fl/stl/fixed_point/u24x8.h
  • src/fl/stl/fixed_point/u4x12.h
  • src/fl/stl/fixed_point/u8x24.h
  • src/fl/stl/fixed_point/u8x8.h

Comment on lines +26 to +28
// Construct from an integer (exact, avoids float math / soft-float helpers).
constexpr s24x8(int n)
: mValue(static_cast<i32>(n) * SCALE) {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Verify constructor expression in this file.
rg -nP 'constexpr\s+s24x8\(int n\)|mValue\(static_cast<i32>\(n\)\s*\*\s*SCALE\)' src/fl/stl/fixed_point/s24x8.h

# Compute 32-bit signed safe range for n * SCALE (SCALE=256).
python - <<'PY'
INT32_MIN = -(1 << 31)
INT32_MAX = (1 << 31) - 1
SCALE = 1 << 8
print("safe_n_min:", INT32_MIN // SCALE)
print("safe_n_max:", INT32_MAX // SCALE)
print("overflow_example:", 8388608 * SCALE)
PY

Repository: FastLED/FastLED

Length of output: 210


🏁 Script executed:

# Check the header file for type definitions and context
cat -n src/fl/stl/fixed_point/s24x8.h | head -50

Repository: FastLED/FastLED

Length of output: 2057


🏁 Script executed:

# Look for SCALE definition and mValue type
rg -B5 -A10 'constexpr\s+s24x8\(int n\)' src/fl/stl/fixed_point/s24x8.h

Repository: FastLED/FastLED

Length of output: 650


🏁 Script executed:

# Search for the class definition and member variables
rg -B2 'mValue' src/fl/stl/fixed_point/s24x8.h | head -30

Repository: FastLED/FastLED

Length of output: 1277


Avoid signed-overflow UB in the integer constructor.

static_cast<i32>(n) * SCALE is evaluated as signed 32-bit multiplication. Since int can range from −2,147,483,648 to 2,147,483,647 but only values in [−8,388,608, 8,388,607] fit safely into the product before overflow, any n outside this range invokes undefined behavior. Use a wider intermediate before narrowing, consistent with the pattern already used in this class (e.g., line 41-42).

Proposed fix
     constexpr s24x8(int n)
-        : mValue(static_cast<i32>(n) * SCALE) {}
+        : mValue(static_cast<i32>(static_cast<i64>(n) * SCALE)) {}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fl/stl/fixed_point/s24x8.h` around lines 26 - 28, The integer constructor
s24x8(int n) currently does the multiplication in 32-bit signed space which can
overflow; change it to perform the multiply in a wider signed type (e.g., i64)
and then narrow to i32 when assigning to mValue using
static_cast<i32>(static_cast<i64>(n) * SCALE) so the intermediate product cannot
overflow (follow the same pattern used elsewhere in this class for safe
widening).

Copilot AI 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.

Pull request overview

Adds non-explicit integer constructors to all 12 fixed-point types (signed and unsigned) so that integer values can be converted to fixed-point without invoking soft-float helpers or using the verbose from_raw() pattern.

Changes:

  • Added implicit constexpr constructors taking unsigned (unsigned types) or int (signed types) across all fixed-point classes.
  • Removed explicit from the float constructor of s16x16 (likely unintentional).

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/fl/stl/fixed_point/u8x8.h Add unsigned constructor
src/fl/stl/fixed_point/u8x24.h Add unsigned constructor
src/fl/stl/fixed_point/u4x12.h Add unsigned constructor
src/fl/stl/fixed_point/u24x8.h Add unsigned constructor
src/fl/stl/fixed_point/u16x16.h Add unsigned constructor
src/fl/stl/fixed_point/u12x4.h Add unsigned constructor
src/fl/stl/fixed_point/s8x8.h Add int constructor
src/fl/stl/fixed_point/s8x24.h Add int constructor
src/fl/stl/fixed_point/s4x12.h Add int constructor
src/fl/stl/fixed_point/s24x8.h Add int constructor
src/fl/stl/fixed_point/s16x16.h Add int constructor; also drops explicit from float ctor
src/fl/stl/fixed_point/s12x4.h Add int constructor

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/fl/stl/fixed_point/s16x16.h Resolved
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@zackees

zackees commented Mar 13, 2026

Copy link
Copy Markdown
Member

So int it 16 bits on avr and 32 bytes on 32 machines. I'm going to have to ask the ai to investigate and see what the best way forward on this is.

@zackees

zackees commented Mar 13, 2026

Copy link
Copy Markdown
Member

we have complex template types will that will bind to any integer type so we can do the right thing for all integer types.

@zackees

zackees commented Mar 13, 2026

Copy link
Copy Markdown
Member

Hey, this is Clud, Zach's AI assistant. I investigated the int width issue and here is what we have decided on and why.

The approach: Template integer constructors using SFINAE instead of hardcoded int/unsigned. The constructor binds to any integer type (short, int, long, i16, i32, etc.) so it does the right thing regardless of platform int width. On AVR where int is 16 bits, passing 42 binds to a 16-bit int and works correctly. On 32-bit platforms it binds to a 32-bit int. No behavioral difference.

Key differences from this PR:

  1. Template vs int/unsigned: This PR uses s24x8(int n) and u24x8(unsigned n). Our version uses template <typename IntT, detail::enable_if_integer_t<IntT> = 0> explicit constexpr s24x8(IntT n). This fixes the core portability problem where int is 16 bits on AVR but 32 bits elsewhere.

  2. explicit: This PR makes the integer constructors implicit (no explicit keyword). We made them explicit to match the float constructor and avoid ambiguity with operator*(i32 scalar). Otherwise s24x8 x(1.0f); x * 2 becomes ambiguous because the compiler could convert 2 to s24x8 and use the fixed-point multiply, or use the scalar multiply. Users write s24x8(5) instead of s24x8 x = 5, which is fine since they already do the same for floats.

  3. No 64-bit widening: This PR does static_cast<i32>(n) * SCALE which is signed overflow UB for the 32-bit storage types when inputs are near the edge. We use unsigned arithmetic (static_cast<u32>(n) * static_cast<u32>(SCALE)) for the 32-bit types, matching the same pattern already used in operator+ and operator- throughout the codebase. This avoids both UB and expensive 64-bit multiply on 32-bit MCUs.

  4. Float constructor left alone: This PR accidentally dropped explicit from the s16x16 float constructor. Our version does not touch the float constructors at all.

The semantic: s24x8(5) means "the number five in fixed-point". The constructor multiplies by SCALE internally so the user never thinks about fractional bits. If someone wants to inject pre-formatted raw bits, from_raw() is the API for that. This is consistent across all 12 fixed-point types.

The helper trait lives in src/fl/stl/fixed_point/traits.h as detail::enable_if_integer_t<T> so the constructors themselves are readable (three lines each). All 309 tests pass including new integer constructor tests that verify equivalence with float constructors for whole numbers.

@zackees

zackees commented Mar 13, 2026

Copy link
Copy Markdown
Member

This has been implemented on master in commit 40b3b52 with the template-based approach described above. The implementation includes constexpr range checking, boundary tests for all 12 types, and signed-to-unsigned integer handling. Closing this PR since the feature has landed.

@zackees zackees closed this Mar 13, 2026
@sutaburosu
sutaburosu deleted the copilot/remove-softfloat branch March 13, 2026 20:44
@sutaburosu

Copy link
Copy Markdown
Contributor Author

Thanks, man. I knew you'd do it better.

zackees added a commit that referenced this pull request Jun 16, 2026
…art of #3130, meta #3127)

First extraction in the fixed_point.cpp split (#3130). Moves the misc
section (lines 4818-5226) into its own file:
  - Fixed-point scalar type alignment tests
  - Constexpr scalar multiply/divide tests (s0x32, u0x32)
  - Integer constructor tests (PR #2197 int width portability)
  - pow boundary regression tests (#2969)

Also extends ci/hooks/check_test_file_pairing.py to allow sibling-split
test files. The original 1:1 pairing rule rejected fixed_point_misc.cpp
because there is no src/fl/math/fixed_point_misc.h. The new sibling-split
allowance walks back the base name via underscore separators and allows
the write when the longest base prefix has both an existing paired test
file and a matching src header. This unblocks the rest of #3127's splits
without weakening the convention for genuinely unpaired test files.

Tests pass: bash test fl_math_fixed_point --cpp (1/1, 17/17 build steps).

fixed_point.cpp: 5,230 -> 4,816 LOC
fixed_point_misc.cpp (new): 440 LOC

Part of #3130. Meta tracking issue: #3127.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 16, 2026
…art of #3130, meta #3127) (#3135)

First extraction in the fixed_point.cpp split (#3130). Moves the misc
section (lines 4818-5226) into its own file:
  - Fixed-point scalar type alignment tests
  - Constexpr scalar multiply/divide tests (s0x32, u0x32)
  - Integer constructor tests (PR #2197 int width portability)
  - pow boundary regression tests (#2969)

Also extends ci/hooks/check_test_file_pairing.py to allow sibling-split
test files. The original 1:1 pairing rule rejected fixed_point_misc.cpp
because there is no src/fl/math/fixed_point_misc.h. The new sibling-split
allowance walks back the base name via underscore separators and allows
the write when the longest base prefix has both an existing paired test
file and a matching src header. This unblocks the rest of #3127's splits
without weakening the convention for genuinely unpaired test files.

Tests pass: bash test fl_math_fixed_point --cpp (1/1, 17/17 build steps).

fixed_point.cpp: 5,230 -> 4,816 LOC
fixed_point_misc.cpp (new): 440 LOC

Part of #3130. Meta tracking issue: #3127.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants