Reduce stack usage

Open
#9 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Refactor
Clarity
Mostly clear
Activity status
Active
Tech stack
c
Domain
performance

Research direction

Start by reading the formatting and buffer construction paths in the single-header implementation, especially the scopy section and the float conversion paths described in the issue. Check the internal buffer overrun reported in #1792 alongside the proposed size reductions. Done means reducing stack use while preserving formatting behavior across integer, float, padding, comma, and suffix cases, with the buffer overrun fixed.

Written by the indexing model from the issue text.

Description

(moved from https://github.com/nothings/stb/issues/1795)

The library uses two internal buffers: the one in stbsp__context, to buffer data to be sent to the callback, which is STB_SPRINTF_MIN chars long; and the internal 'num' buffer for converting integers and floats, which is STBSP__NUMSZ chars long (512).
STB_SPRINTF_MIN can be changed by the user, and it is safe to use a buffer as small as 4 bytes (because the library performs optimized 4-byte accesses, at times).
It would be good to reduce the size of 'num' as well. In constrained systems, 512 bytes of stack consumption is too much (especially in a multithreaded scenario) -- vsprintfcb takes at least STBSP__NUMSZ + STB_SPRINTF_MIN + (more or less) 150 bytes, for a total of at least 650.

Here is my analysis of the internal buffer size actually needed by the library.

The internal (stack-allocated) temporary buffer needs to be able to hold the string representation of integers and/or floats.
The sign and leading/trailing padding are not stored in this buffer. The longest string for integers results from the all-1 64-bit number represented in base 2, which requires 64 bytes ("111...").
If STBSP__TRIPLET_COMMA is enabled, then the length grows by ( floor((64-1)/8)=7 ) bytes, for a total of 71 bytes.

The longest string for %f floats results from the highest-magnitude float (roughly +-1.8e+308) printed with commas.
We convert the significant digits to string using stbsp__real_to_str(). From non-exhaustive testing, it seems that it returns at most 19 digits/bytes.
The theoretical value would be 17 (the most significant decimal digits that a 64-bit float can contain), and this is in line with that (we don't guarantee shortest-length representation).
These digits are stored in the first 64 bytes of the temporary buffer. It's unclear why not just the first 20 or 32; maybe the value of 64 could come in handy for extensions to binary representation, or it gives ample margin for non-shortest-length representations.
The digits are then copied over to the second half of the buffer, from byte 64 onwards. During the copy, the decimal point is added, as well as the triplet commas.
We have no trailing-zeros-in-the-integral-part optimization, so the worst case for that is having 1+308 digits plus the commas -- ie 309+102=411 bytes (+1 for the dot).
We have no leading-zeros-in-the-decimal-part optimization either, so the worst case for that is having 324 digits (the exponent of the smallest f64 denormal number) plus 19 digits (the most significant digits we ever emit, though denormals have less) plus 1 (the dot).
The two cases above cannot occur simultaneously.
We also have <=3 bytes for the SI/JEDEC suffix.
Overall, we need ( max(412, 336) + 3 = 415 ) bytes for the second half of the buffer, ie 479 bytes for the whole buffer.

The longest string for %e floats results from getting 19 digits from stbsp__real_to_str(), plus the decimal point, plus 0 commas (we always have exactly 1 integral digit), plus the exponent.
For this format, too, we get the stbsp__real_to_str() result into the initial 64-byte chunk, and then copy it to the rest of the buffer.
The exponent part is at most "e+308" or "e-307", so no more than 5 bytes long.
Overall, we need ( 19 + 1 + 5 = 25 ) bytes.

%g is equivalent to %f or %e, depending on the actual value (there are small differences in how the precision is handled, but this does not impact the buffer requirements), so their limits apply.
To be more precise, %g is equivalent to %f if:
P > X >= -4
where P = max(1, specified_precision), and X is the exponent that the %e representation would have.
So, for non-small numbers (exponent >= -4) and for large precision (which the user controls), we get a %f-type representation, which is the largest possible one, as described above. That is, using %g does not always guarantee a compact representation.

%a is like %e in hexadecimal rather than decimal, so it cannot be longer than that (to be true, the exponent for %a can be one digits longer than for %e). We use a separate code path for this format, which only uses the second half of the temporary buffer (from byte 64 onwards).

Summary of the space requirements:

  • integers: 64
  • integers with commas: 71
  • floats: 378
  • floats with commas: 479

Now, to reduce the stack usage, when the NOFLOAT option is used, we can simply conditionally reduce STBSP__NUMSZ to 64 or 72 bytes (also depending on STBSP__TRIPLET_COMMA).
We could also remove commas completely from the buffer, and apply them on-the-fly as the characters are outputted. But this seems a bit complicated, and saves no more than 8 bytes.

Then, to reduce the buffer size when floats are enabled, the trailing-0s-and-commas-in-the-integral-part, and the leading-0s-in-the-fractional-part should be outputted directly, without storing them in the internal buffer first.
This implies splitting the "copy-bulk-of-string" code path in multiple steps. I mean, the "scopy" section does this:

  1. copy leading spaces
  2. copy leader (ie sign, "0x", etc.)
  3. copy leading zeros (and commas)
  4. copy leader (for the case of no space/0 padding)
  5. copy the string (ie the content of the internal 'num' buffer, taken as an indivisible unit, already with the decimal point, if needed)
  6. copy trailing zeros (only for float fractional part)
  7. copy tail (float exponent, SI suffix)
  8. handle left justify (ie trailing spaces)

We need to split step 5 so that it performs this:
5.1) copy the integral part
5.2) add trailing zeros (and commas) to the integral part
5.3) add the decimal point (if needed; also mind what the '#' modifier mandates)
5.4) add leading zeros for the fractional part
5.5) copy the fractional part

There is never a case where both the integral part and the fractional part (5.1 and 5.5) are non-empty. That is, they cannot be both empty and still require in-between zeros. If they are both non-empty, they are contiguous, and can be treated as a single unit, exactly as is already done now for all cases.
So, the code paths that put characters into the internal buffer can keep using it as a single unit (I mean the second part of it; the first part can still be used for their temporary conversions). What such code paths need to do is to mark the buffer as belonging to 5.1 or 5.5, and to calculate the length of 5.2, 5.3 and 5.4.

In the end, the buffer requirements for floats could be as low as 20 bytes (for the first-half buffer) plus (20 * 4/3 = 27) bytes (this includes the possible decimal point and the commas), for a total of 47 bytes, which is less than the 71 needed for integers.
The total stack requirement would be in the order of 72+150+STB_SPRINTF_MIN, saving about 450 bytes compared to now.

Note: reducing the internal buffer also requires fixing the "internal buffer overrun" bug already reported in #1792

Dominant language
C
Stars
18
Forks
5
Avg merge
1m
Merged PRs (30d)
3

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from nothings/stb_sprintf

All issues in nothings/stb_sprintf

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.