-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLibFormatDecimalFloat.toDecimalString.t.sol
More file actions
609 lines (548 loc) · 32.4 KB
/
Copy pathLibFormatDecimalFloat.toDecimalString.t.sol
File metadata and controls
609 lines (548 loc) · 32.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity =0.8.25;
import {Test, stdError} from "forge-std-1.16.1/src/Test.sol";
import {Float, LibDecimalFloat} from "src/lib/LibDecimalFloat.sol";
import {LibFormatDecimalFloat} from "src/lib/format/LibFormatDecimalFloat.sol";
import {LibParseDecimalFloat} from "src/lib/parse/LibParseDecimalFloat.sol";
import {UnformatableExponent} from "src/error/ErrFormat.sol";
import {Strings} from "@openzeppelin-contracts-5.6.1/utils/Strings.sol";
/// @title LibFormatDecimalFloatToDecimalStringTest
/// @notice Test contract for verifying the functionality of LibFormatDecimalFloat
/// @dev Tests both the stack and memory versions of formatting functions and round-trip conversions
contract LibFormatDecimalFloatToDecimalStringTest is Test {
using LibDecimalFloat for Float;
using LibFormatDecimalFloat for Float;
function checkFormat(int256 signedCoefficient, int256 exponent, bool scientific, string memory expected)
internal
pure
{
string memory actual = LibFormatDecimalFloat.toDecimalString(
LibDecimalFloat.packLossless(signedCoefficient, exponent), scientific
);
assertEq(actual, expected, "Formatted value mismatch");
}
function checkRoundFromString(string memory s, Float expected, bool scientific) internal pure {
(bytes4 err, Float parsed) = LibParseDecimalFloat.parseDecimalFloat(s);
assertEq(err, 0, "Parse error");
assertTrue(expected.eq(parsed), "Round trip failed");
// Canonicalization: format(parse(s)) == s
string memory reFormatted = LibFormatDecimalFloat.toDecimalString(parsed, scientific);
assertEq(s, reFormatted, "Formatting not canonical");
}
/// Test round tripping examples.
function testFormatDecimalRoundTripExamples() external pure {
checkRoundFromString(
"1.2345678901234567890123456789e29", LibDecimalFloat.packLossless(123456789012345678901234567890, 0), true
);
checkRoundFromString("0", LibDecimalFloat.packLossless(0, 0), true);
checkRoundFromString("0", LibDecimalFloat.packLossless(0, 0), false);
checkRoundFromString(
"-1.2345678901234567890123456789e29", LibDecimalFloat.packLossless(-123456789012345678901234567890, 0), true
);
checkRoundFromString("1", LibDecimalFloat.packLossless(1, 0), false);
checkRoundFromString("1", LibDecimalFloat.packLossless(1, 0), true);
checkRoundFromString("-1", LibDecimalFloat.packLossless(-1, 0), false);
checkRoundFromString("-1", LibDecimalFloat.packLossless(-1, 0), true);
checkRoundFromString("100", LibDecimalFloat.packLossless(100, 0), false);
checkRoundFromString("1e2", LibDecimalFloat.packLossless(100, 0), true);
checkRoundFromString("-100", LibDecimalFloat.packLossless(-100, 0), false);
checkRoundFromString("-1e2", LibDecimalFloat.packLossless(-100, 0), true);
checkRoundFromString("0.01", LibDecimalFloat.packLossless(1, -2), false);
checkRoundFromString("1e-2", LibDecimalFloat.packLossless(1, -2), true);
checkRoundFromString("-0.01", LibDecimalFloat.packLossless(-1, -2), false);
checkRoundFromString("-1e-2", LibDecimalFloat.packLossless(-1, -2), true);
checkRoundFromString("0.1", LibDecimalFloat.packLossless(1, -1), false);
checkRoundFromString("1e-1", LibDecimalFloat.packLossless(1, -1), true);
checkRoundFromString("-1e-1", LibDecimalFloat.packLossless(-1, -1), true);
checkRoundFromString("-0.1", LibDecimalFloat.packLossless(-1, -1), false);
checkRoundFromString("0.101", LibDecimalFloat.packLossless(101, -3), false);
checkRoundFromString("1.01e-1", LibDecimalFloat.packLossless(101, -3), true);
checkRoundFromString("-0.101", LibDecimalFloat.packLossless(-101, -3), false);
checkRoundFromString("-1.01e-1", LibDecimalFloat.packLossless(-101, -3), true);
checkRoundFromString("1.1", LibDecimalFloat.packLossless(11, -1), false);
checkRoundFromString("1.1", LibDecimalFloat.packLossless(11, -1), true);
checkRoundFromString("-1.1", LibDecimalFloat.packLossless(-11, -1), false);
checkRoundFromString("-1.1", LibDecimalFloat.packLossless(-11, -1), true);
checkRoundFromString("123456789", LibDecimalFloat.packLossless(123456789, 0), false);
checkRoundFromString("1.23456789e8", LibDecimalFloat.packLossless(123456789, 0), true);
checkRoundFromString("-123456789", LibDecimalFloat.packLossless(-123456789, 0), false);
checkRoundFromString("-1.23456789e8", LibDecimalFloat.packLossless(-123456789, 0), true);
checkRoundFromString("1.23456789e9", LibDecimalFloat.packLossless(1234567890, 0), true);
checkRoundFromString("123456789", LibDecimalFloat.packLossless(123456789, 0), false);
checkRoundFromString("-1.23456789e9", LibDecimalFloat.packLossless(-1234567890, 0), true);
checkRoundFromString("-123456789", LibDecimalFloat.packLossless(-123456789, 0), false);
checkRoundFromString("1.019001501928e-6", LibDecimalFloat.packLossless(1019001501928, -18), true);
checkRoundFromString("0.000001019001501928", LibDecimalFloat.packLossless(1019001501928, -18), false);
checkRoundFromString("-1.019001501928e-6", LibDecimalFloat.packLossless(-1019001501928, -18), true);
checkRoundFromString("-0.000001019001501928", LibDecimalFloat.packLossless(-1019001501928, -18), false);
checkRoundFromString("1e9", LibDecimalFloat.packLossless(1000000000, 0), true);
checkRoundFromString("1000000000", LibDecimalFloat.packLossless(1000000000, 0), false);
checkRoundFromString("-1e9", LibDecimalFloat.packLossless(-1000000000, 0), true);
checkRoundFromString("-1000000000", LibDecimalFloat.packLossless(-1000000000, 0), false);
checkRoundFromString("1e-76", LibDecimalFloat.packLossless(1, -76), true);
checkRoundFromString("-1e-76", LibDecimalFloat.packLossless(-1, -76), true);
checkRoundFromString("1e76", LibDecimalFloat.packLossless(1, 76), true);
checkRoundFromString("-1e76", LibDecimalFloat.packLossless(-1, 76), true);
checkRoundFromString("1e200", LibDecimalFloat.packLossless(1, 200), true);
checkRoundFromString("-1e200", LibDecimalFloat.packLossless(-1, 200), true);
}
/// Test round tripping a value through parse and format.
function testFormatDecimalRoundTripNonNegative(uint256 value, bool scientific) external pure {
value = bound(value, 0, uint256(int256(type(int224).max)));
Float float = LibDecimalFloat.fromFixedDecimalLosslessPacked(value, 18);
string memory formatted = LibFormatDecimalFloat.toDecimalString(float, scientific);
(bytes4 errorCode, Float parsed) = LibParseDecimalFloat.parseDecimalFloat(formatted);
assertEq(errorCode, 0, "Parse error");
assertTrue(float.eq(parsed), "Round trip failed");
// Canonicalization: format(parse(format(x))) == format(x)
string memory reFormatted = LibFormatDecimalFloat.toDecimalString(parsed, scientific);
assertEq(formatted, reFormatted, "Formatting not canonical");
}
/// Negative matches positive.
function testFormatDecimalRoundTripNegative(int256 value, bool scientific) external pure {
value = bound(value, 1, int256(type(int128).max));
// value [1, int256(type(int128).max)]
// forge-lint: disable-next-line(unsafe-typecast)
Float float = LibDecimalFloat.fromFixedDecimalLosslessPacked(uint256(value), 18);
string memory formatted = float.toDecimalString(scientific);
float = float.minus();
string memory formattedNeg = float.toDecimalString(scientific);
assertEq(string.concat("-", formatted), formattedNeg, "Negative format mismatch");
// Parse/eq for negative path as well
(bytes4 err, Float parsedNeg) = LibParseDecimalFloat.parseDecimalFloat(formattedNeg);
assertEq(err, 0, "Parse error (neg)");
assertTrue(float.eq(parsedNeg), "Round trip failed (neg)");
// Canonicalization for negative: format(parse(s)) == s
string memory reFormattedNeg = LibFormatDecimalFloat.toDecimalString(parsedNeg, scientific);
assertEq(formattedNeg, reFormattedNeg, "Formatting not canonical (neg)");
}
/// Test some specific examples.
function testFormatDecimalExamples() external pure {
// pos decs
checkFormat(123456789012345678901234567890, 0, true, "1.2345678901234567890123456789e29");
checkFormat(123456789012345678901234567890, -1, true, "1.2345678901234567890123456789e28");
checkFormat(123456789012345678901234567890, -2, true, "1.2345678901234567890123456789e27");
checkFormat(123456789012345678901234567890, -3, true, "1.2345678901234567890123456789e26");
checkFormat(123456789012345678901234567890, -4, true, "1.2345678901234567890123456789e25");
checkFormat(123456789012345678901234567890, -5, true, "1.2345678901234567890123456789e24");
checkFormat(123456789012345678901234567890, -6, true, "1.2345678901234567890123456789e23");
// zeros
checkFormat(0, 0, true, "0");
checkFormat(0, -1, true, "0");
checkFormat(0, -2, true, "0");
checkFormat(0, -3, true, "0");
checkFormat(0, 1, true, "0");
checkFormat(0, 2, true, "0");
checkFormat(0, 3, true, "0");
// neg decs
checkFormat(-123456789012345678901234567890, 0, true, "-1.2345678901234567890123456789e29");
checkFormat(-123456789012345678901234567890, -1, true, "-1.2345678901234567890123456789e28");
checkFormat(-123456789012345678901234567890, -2, true, "-1.2345678901234567890123456789e27");
checkFormat(-123456789012345678901234567890, -3, true, "-1.2345678901234567890123456789e26");
checkFormat(-123456789012345678901234567890, -4, true, "-1.2345678901234567890123456789e25");
checkFormat(-123456789012345678901234567890, -5, true, "-1.2345678901234567890123456789e24");
checkFormat(-123456789012345678901234567890, -6, true, "-1.2345678901234567890123456789e23");
// one
checkFormat(1, 0, true, "1");
// 100
checkFormat(100, 0, false, "100");
checkFormat(10, 1, false, "100");
checkFormat(1, 2, false, "100");
checkFormat(1000, -1, false, "100");
// -100
checkFormat(-100, 0, false, "-100");
checkFormat(-10, 1, false, "-100");
checkFormat(-1, 2, false, "-100");
checkFormat(-1000, -1, false, "-100");
// 0.01
checkFormat(1, -2, false, "0.01");
checkFormat(10, -3, false, "0.01");
checkFormat(100, -4, false, "0.01");
checkFormat(1000, -5, false, "0.01");
// -0.01
checkFormat(-1, -2, false, "-0.01");
checkFormat(-10, -3, false, "-0.01");
checkFormat(-100, -4, false, "-0.01");
checkFormat(-1000, -5, false, "-0.01");
// 0.1
checkFormat(1, -1, false, "0.1");
checkFormat(10, -2, false, "0.1");
checkFormat(100, -3, false, "0.1");
checkFormat(1000, -4, false, "0.1");
// -0.1
checkFormat(-1, -1, false, "-0.1");
checkFormat(-10, -2, false, "-0.1");
checkFormat(-100, -3, false, "-0.1");
checkFormat(-1000, -4, false, "-0.1");
// 0.101
checkFormat(101, -3, false, "0.101");
checkFormat(1010, -4, false, "0.101");
checkFormat(10100, -5, false, "0.101");
checkFormat(101000, -6, false, "0.101");
// -0.101
checkFormat(-101, -3, false, "-0.101");
checkFormat(-1010, -4, false, "-0.101");
checkFormat(-10100, -5, false, "-0.101");
checkFormat(-101000, -6, false, "-0.101");
// 1.1
checkFormat(11, -1, false, "1.1");
checkFormat(110, -2, false, "1.1");
checkFormat(1100, -3, false, "1.1");
checkFormat(11000, -4, false, "1.1");
// -1.1
checkFormat(-11, -1, false, "-1.1");
checkFormat(-110, -2, false, "-1.1");
checkFormat(-1100, -3, false, "-1.1");
checkFormat(-11000, -4, false, "-1.1");
// 9 sig figs
checkFormat(123456789, 0, false, "123456789");
checkFormat(-123456789, 0, false, "-123456789");
checkFormat(123456789, -1, false, "12345678.9");
checkFormat(-123456789, -1, false, "-12345678.9");
checkFormat(12345678, 1, false, "123456780");
checkFormat(-12345678, 1, false, "-123456780");
// 10 sig figs
checkFormat(1234567890, 0, true, "1.23456789e9");
checkFormat(-1234567890, 0, true, "-1.23456789e9");
checkFormat(123456789, 1, true, "1.23456789e9");
checkFormat(-123456789, 1, true, "-1.23456789e9");
checkFormat(1, -10, true, "1e-10");
// examples from fuzz
checkFormat(1019001501928, -18, true, "1.019001501928e-6");
checkFormat(-1019001501928, -18, true, "-1.019001501928e-6");
// pure powers of 10 at the cutoff
checkFormat(1000000000, 0, true, "1e9");
checkFormat(-1000000000, 0, true, "-1e9");
// extreme small/large magnitudes still choose scientific
checkFormat(1, -76, true, "1e-76");
checkFormat(-1, -76, true, "-1e-76");
checkFormat(1, 76, true, "1e76");
checkFormat(-1, 76, true, "-1e76");
// impossible sig figs.
checkFormat(1, 200, true, "1e200");
// we can't actually fit 200 zeros into the binary representation so
// even though the threshold is 200 we still use scientific notation.
checkFormat(1, 200, true, "1e200");
}
function formatExternal(Float float, bool scientific) external pure returns (string memory) {
return LibFormatDecimalFloat.toDecimalString(float, scientific);
}
/// Fuzz: every Float round-trips through scientific format → parse → eq
/// across the full int224 coefficient domain, with exponent bounded to
/// avoid the display-exponent overflow guard added by #185.
///
/// Scientific format renders `coef × 10^exp` as `d.dddd × 10^displayExp`
/// where `displayExp = exp + 75 or 76` (after `maximizeFull` + scale).
/// The formatter now reverts `UnformatableExponent` when `displayExp`
/// falls outside `[int32.min, int32.max]`. The headroom below keeps the
/// fuzz in the round-trip-safe zone.
function testFormatParseRoundTripScientificFullDomain(int224 coefficient, int32 exponent) external pure {
int256 headroom = 80;
// `bound` to a sub-range of int32 that avoids triggering the int32
// display-exponent overflow guard.
// forge-lint: disable-next-line(unsafe-typecast)
exponent = int32(bound(exponent, int256(type(int32).min) + headroom, int256(type(int32).max) - headroom));
_checkRoundTrip(coefficient, exponent, true);
}
/// Scientific format reverts when the display exponent would overflow
/// int32 (positive side). With coefficient = int224.max (~68 digits),
/// maximizeFull extends it to ~78 digits, reducing the stored exponent
/// by ~10. displayExponent = storedExp + scaleExponent = (exp - 10) + 76
/// = exp + 66. For exp = int32.max - 50, displayExp = int32.max + 16,
/// which overflows int32.
function testFormatScientificRevertsNearPositiveInt32Limit() external {
int256 exp = int256(type(int32).max) - 50;
Float float = LibDecimalFloat.packLossless(int256(type(int224).max), exp);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, exp));
this.formatExternal(float, true);
}
/// Scientific format reverts when the display exponent would overflow
/// int32 (negative side). With coefficient = 1 (1 digit), maximizeFull
/// extends to ~77 digits, reducing stored exponent by ~76. displayExponent
/// = (exp - 76) + 76 = exp. For exp = int32.min, displayExp = int32.min,
/// which fits in int32 — so this boundary does NOT trigger for k=1. Use a
/// large negative coefficient so k > 1 and verify we remain safe.
function testFormatScientificNegativeBoundaryDoesNotRevert() external pure {
// (int224.max, int32.min + 80): headroom=80 ensures we stay in-range.
Float float = LibDecimalFloat.packLossless(int256(type(int224).max), int256(type(int32).min) + 80);
string memory s = LibFormatDecimalFloat.toDecimalString(float, true);
assertGt(bytes(s).length, 0);
}
/// Fuzz: every Float with non-positive exponent round-trips through
/// non-scientific format → parse → eq, across the full int224 coefficient
/// domain and exponent in `[-MAX_NON_SCIENTIFIC_EXPONENT, 0]`.
///
/// Positive exponents are NOT fuzzed here: the formatter reverts when
/// `absCoef * 10^exponent > int224.max` (the formatted integer would exceed
/// the parser's lossless range). See `testFormatParseRoundTripNonScientificSafePosExp`
/// for positive-exponent round-trip coverage within the safe range.
function testFormatParseRoundTripNonScientificNegExpFullDomain(int224 coefficient, int32 exponent) external pure {
int256 cap = LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT;
// `bound` returns a value in [-cap, 0]; cap fits int32 so the cast back
// cannot truncate.
// forge-lint: disable-next-line(unsafe-typecast)
exponent = int32(bound(exponent, -cap, 0));
_checkRoundTrip(coefficient, exponent, false);
}
function _checkRoundTrip(int256 coefficient, int256 exponent, bool scientific) internal pure {
Float original = LibDecimalFloat.packLossless(coefficient, exponent);
string memory formatted = LibFormatDecimalFloat.toDecimalString(original, scientific);
(bytes4 err, Float parsed) = LibParseDecimalFloat.parseDecimalFloat(formatted);
assertEq(err, bytes4(0), string.concat("Parse error on: ", formatted));
assertTrue(original.eq(parsed), string.concat("Round trip mismatch on: ", formatted));
string memory reFormatted = LibFormatDecimalFloat.toDecimalString(parsed, scientific);
assertEq(formatted, reFormatted, "Formatting not canonical");
}
/// Fuzz: two representations of the same numeric value format to identical
/// strings. Covers the formatter's canonicalization behavior (trailing
/// zeros in coefficient vs expressed via exponent) without going through
/// the parser. Runs for both scientific and non-scientific modes,
/// including the full non-scientific positive-exp range that the
/// round-trip fuzz cannot cover (see #184).
function testFormatCanonicalAcrossRepresentations(int128 base, uint8 shift, bool scientific) external pure {
vm.assume(base != 0);
int256 baseInt = int256(base);
int256 absBase = baseInt < 0 ? -baseInt : baseInt;
// Find the largest shift `s` such that `absBase * 10^s` fits int224.
uint256 maxShift = 0;
int256 scale = 1;
while (scale <= type(int224).max / 10 / absBase) {
scale *= 10;
maxShift++;
}
if (maxShift == 0) return;
uint256 s = bound(shift, 1, maxShift);
int256 scaled = baseInt * int256(10 ** s);
// Exponent pair chosen so both representations are well inside int32.
// forge-lint: disable-next-line(unsafe-typecast)
int256 baseExp = scientific ? int256(0) : -int256(s);
Float a = LibDecimalFloat.packLossless(baseInt, baseExp);
// forge-lint: disable-next-line(unsafe-typecast)
Float b = LibDecimalFloat.packLossless(scaled, baseExp - int256(s));
assertTrue(a.eq(b), "precondition: representations should be equal");
string memory formatA = LibFormatDecimalFloat.toDecimalString(a, scientific);
string memory formatB = LibFormatDecimalFloat.toDecimalString(b, scientific);
assertEq(formatA, formatB, "Different representations formatted to different strings");
}
/// Non-scientific format reverts at the positive exponent cap boundary:
/// MAX_NON_SCIENTIFIC_EXPONENT = 1000 >= 68, so 1 × 10^1000 >> int224.max
/// and the int224 overflow guard fires. Use scientific mode for such values.
function testFormatNonScientificExponentAtPositiveCapReverts() external {
int256 cap = LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT;
Float float = LibDecimalFloat.packLossless(1, cap);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, cap));
this.formatExternal(float, false);
}
function testFormatNonScientificExponentAtNegativeCap() external pure {
int256 cap = LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT;
Float float = LibDecimalFloat.packLossless(1, -cap);
string memory s = LibFormatDecimalFloat.toDecimalString(float, false);
// "0." + (cap - 1) leading zeros + "1".
// forge-lint: disable-next-line(unsafe-typecast)
assertEq(bytes(s).length, 2 + uint256(cap - 1) + 1);
assertEq(bytes(s)[0], bytes1("0"));
assertEq(bytes(s)[1], bytes1("."));
assertEq(bytes(s)[bytes(s).length - 1], bytes1("1"));
}
/// Non-scientific format on the int224 signed range boundaries.
function testFormatNonScientificInt224MaxCoefficient() external pure {
Float float = LibDecimalFloat.packLossless(int256(type(int224).max), 0);
string memory s = LibFormatDecimalFloat.toDecimalString(float, false);
assertEq(s, Strings.toString(uint256(int256(type(int224).max))));
}
function testFormatNonScientificInt224MinCoefficient() external pure {
Float float = LibDecimalFloat.packLossless(int256(type(int224).min), 0);
string memory s = LibFormatDecimalFloat.toDecimalString(float, false);
// int224.min negated fits uint256 (= 2^223).
assertEq(s, string.concat("-", Strings.toString(uint256(-int256(type(int224).min)))));
}
/// `_toNonScientific` branch coverage: effective exponent ends up exactly
/// at zero after trailing-zero stripping. Exercises the `effExp >= 0`
/// path with `uEffExp = 0`.
function testFormatNonScientificEffExpZero() external pure {
// (100, -2) has trailingZeros=2, sigK=1, effExp=0 → output "1".
checkFormat(100, -2, false, "1");
// (12340000, -4) → trailingZeros=4, sigK=4, effExp=0 → "1234".
checkFormat(12340000, -4, false, "1234");
}
/// `_toNonScientific` branch coverage: sigK == absEffExp, decimal point
/// lands exactly at the start of the significant digits.
function testFormatNonScientificDecimalAtStart() external pure {
// (123, -3) → sigK=3, absEffExp=3, so output = "0." + 0 leading zeros + "123".
checkFormat(123, -3, false, "0.123");
// Negative variant.
checkFormat(-123, -3, false, "-0.123");
}
/// `_toNonScientific` branch coverage: decimal point in the middle of the
/// significant digits.
function testFormatNonScientificDecimalInside() external pure {
// (12345, -2) → sigK=5, absEffExp=2, splitAt=3. Output "123.45".
checkFormat(12345, -2, false, "123.45");
checkFormat(-12345, -2, false, "-123.45");
}
/// `_toNonScientific` branch coverage: leading zeros after "0." (sigK <
/// absEffExp). This is the #182 shape.
function testFormatNonScientificLeadingZeros() external pure {
// (5, -5) → sigK=1, absEffExp=5, leadingZeros=4. Output "0.00005".
checkFormat(5, -5, false, "0.00005");
checkFormat(-5, -5, false, "-0.00005");
}
/// Fuzz: non-scientific format does not revert for any valid Float with
/// `|exponent| <= MAX_NON_SCIENTIFIC_EXPONENT` and non-positive exponent.
/// When exponent <= 0 the formatted integer equals absCoef / 10^|exponent|
/// which is at most absCoef <= int224.max, so the int224 overflow guard
/// never fires. Positive exponents may revert with `UnformatableExponent`
/// when `absCoef * 10^exponent > int224.max`.
function testFormatNonScientificSucceedsForNonPositiveExponents(int224 coefficient, int32 exponent) external pure {
int256 cap = LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT;
// Bound to [-cap, 0]; negative and zero exponents never trigger the
// int-digit-count guard.
// forge-lint: disable-next-line(unsafe-typecast)
exponent = int32(bound(exponent, -cap, 0));
Float float = LibDecimalFloat.packLossless(coefficient, exponent);
// Should not revert.
string memory s = LibFormatDecimalFloat.toDecimalString(float, false);
assertGt(bytes(s).length, 0);
}
/// The formatter reverts with `UnformatableExponent` when `exponent >= 68`
/// (10^68 > int224.max ≈ 1.34e67, so even coefficient 1 overflows).
/// Mutation test: remove the guard in `_toNonScientific` → this test
/// fails because the call no longer reverts.
function testFormatNonScientificRevertsOnLongPositiveExp() external {
// (1, 68): 1 × 10^68 > int224.max → reverts.
Float float = LibDecimalFloat.packLossless(1, 68);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, int256(68)));
this.formatExternal(float, false);
}
/// The largest positive exponent where coefficient=1 still passes the
/// int224 overflow guard: exponent=67 gives value 1×10^67 < int224.max
/// (≈1.34e67). The formatter succeeds and the output round-trips.
function testFormatNonScientificAtIntDigitBoundary() external pure {
// (1, 67): value = 1e67 < int224.max; limit = floor(int224.max / 10^67) = 1.
// absCoef=1 <= 1 → guard passes. Output: "1" + 67 zeros = 68 chars.
Float float = LibDecimalFloat.packLossless(1, 67);
string memory s = LibFormatDecimalFloat.toDecimalString(float, false);
assertEq(bytes(s).length, 68, "output length");
assertEq(bytes(s)[0], bytes1("1"), "leading digit");
(bytes4 err, Float parsed) = LibParseDecimalFloat.parseDecimalFloat(s);
assertEq(err, bytes4(0), "parse error");
assertTrue(float.eq(parsed), "round-trip mismatch");
}
/// Fuzz: for every non-zero int224 coefficient and positive exponent where
/// the formatter does NOT revert (i.e. absCoef × 10^exponent <= int224.max),
/// the output round-trips through parse. Uses the same limit computation as
/// the formatter to skip cases that correctly revert.
/// forge-config: default.fuzz.runs = 100
function testFormatParseRoundTripNonScientificSafePosExp(int224 coefficient, int32 exponent) external pure {
vm.assume(coefficient != 0);
vm.assume(exponent > 0);
// Mirror the formatter's guard: skip if exponent >= 68 or absCoef > limit.
// forge-lint: disable-next-line(unsafe-typecast)
uint256 uExp = uint256(uint32(exponent));
vm.assume(uExp < 68);
uint256 limit = uint256(int256(type(int224).max));
for (uint256 i = 0; i < uExp; i++) {
limit /= 10;
}
uint256 absCoef = coefficient < 0 ? uint256(-int256(coefficient)) : uint256(int256(coefficient));
vm.assume(absCoef <= limit);
Float float = LibDecimalFloat.packLossless(coefficient, exponent);
string memory s = LibFormatDecimalFloat.toDecimalString(float, false);
(bytes4 err, Float parsed) = LibParseDecimalFloat.parseDecimalFloat(s);
assertEq(err, bytes4(0), string.concat("Parse error on: ", s));
assertTrue(float.eq(parsed), string.concat("Round trip mismatch on: ", s));
}
/// Fuzz: output shape properties for non-scientific format.
/// - Never ends with "." (formatter always strips trailing zeros from the
/// fractional part; a lone "." would indicate a bug).
/// - If the output contains ".", no trailing zeros after it.
/// - If negative, leading character is "-" and remainder has same shape
/// as the positive case.
function testFormatNonScientificOutputShape(int224 coefficient, int32 exponent) external pure {
vm.assume(coefficient != 0);
// int224.min negated exceeds int224.max, so skip it for the
// negation-symmetry check below.
vm.assume(coefficient != type(int224).min);
int256 cap = LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT;
// Bound to [-cap, 0]: non-positive exponents never trigger the
// positive-exponent int224 overflow guard, so the formatter never
// reverts and shape assertions always apply.
// forge-lint: disable-next-line(unsafe-typecast)
exponent = int32(bound(exponent, -cap, 0));
Float float = LibDecimalFloat.packLossless(coefficient, exponent);
bytes memory s = bytes(LibFormatDecimalFloat.toDecimalString(float, false));
assertGt(s.length, 0);
// Never ends with ".".
assertNotEq(uint8(s[s.length - 1]), uint8(bytes1(".")));
// If a "." is present, no trailing zero after it.
bool hasDot;
for (uint256 i = 0; i < s.length; i++) {
if (s[i] == ".") {
hasDot = true;
break;
}
}
if (hasDot) {
assertNotEq(uint8(s[s.length - 1]), uint8(bytes1("0")), "trailing zero after decimal point");
}
// Negative outputs start with "-" and have the same shape as the
// positive counterpart.
if (coefficient < 0) {
assertEq(uint8(s[0]), uint8(bytes1("-")));
Float positive = LibDecimalFloat.packLossless(-int256(coefficient), exponent);
string memory pos = LibFormatDecimalFloat.toDecimalString(positive, false);
assertEq(string(s), string.concat("-", pos));
}
}
/// Constants format as expected in both modes.
function testFormatDecimalFloatConstants() external pure {
assertEq(LibFormatDecimalFloat.toDecimalString(LibDecimalFloat.FLOAT_ZERO, true), "0");
assertEq(LibFormatDecimalFloat.toDecimalString(LibDecimalFloat.FLOAT_ZERO, false), "0");
assertEq(LibFormatDecimalFloat.toDecimalString(LibDecimalFloat.FLOAT_ONE, true), "1");
assertEq(LibFormatDecimalFloat.toDecimalString(LibDecimalFloat.FLOAT_ONE, false), "1");
assertEq(LibFormatDecimalFloat.toDecimalString(LibDecimalFloat.FLOAT_HALF, true), "5e-1");
assertEq(LibFormatDecimalFloat.toDecimalString(LibDecimalFloat.FLOAT_HALF, false), "0.5");
}
/// Non-scientific format of (1, 77) now reverts: 1 × 10^77 far exceeds
/// int224.max (≈1.34e67), so the formatted integer cannot be parsed back
/// losslessly. The formatter reverts rather than silently producing a
/// non-round-trippable string.
function testFormatNonScientificLargePositiveExponent() external {
Float float = LibDecimalFloat.packLossless(1, 77);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, int256(77)));
this.formatExternal(float, false);
}
/// Non-scientific format of (int224.max, 10) reverts: int224.max × 10
/// exceeds int224.max, so the output cannot round-trip through the parser.
function testFormatNonScientificLargeCoefficientLargeExponent() external {
int256 c = int256(type(int224).max);
Float float = LibDecimalFloat.packLossless(c, 10);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, int256(10)));
this.formatExternal(float, false);
}
/// Non-scientific format reverts when `|exponent|` exceeds the policy cap.
function testFormatNonScientificExponentAboveCapReverts() external {
int256 exp = LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT + 1;
Float float = LibDecimalFloat.packLossless(1, exp);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, exp));
this.formatExternal(float, false);
}
function testFormatNonScientificExponentBelowCapReverts() external {
int256 exp = -LibFormatDecimalFloat.MAX_NON_SCIENTIFIC_EXPONENT - 1;
Float float = LibDecimalFloat.packLossless(1, exp);
vm.expectRevert(abi.encodeWithSelector(UnformatableExponent.selector, exp));
this.formatExternal(float, false);
}
/// The exact #182 reproduction: `add` of two near-cancelling values
/// produces a Float with exponent -77. The non-scientific formatter must
/// render this without reverting.
function testFormatNonScientificIssue182Reproduction() external pure {
Float net = LibDecimalFloat.packLossless(-9999999910959448, -17);
Float fill = LibDecimalFloat.packLossless(99999999, -9);
Float result = net.add(fill);
// Numeric value is -1.0959448e-10.
string memory formatted = result.toDecimalString(false);
assertEq(formatted, "-0.00000000010959448");
}
}