/
fmt.zig
1694 lines (1496 loc) · 58.3 KB
/
fmt.zig
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std.zig");
const math = std.math;
const assert = std.debug.assert;
const mem = std.mem;
const builtin = @import("builtin");
const errol = @import("fmt/errol.zig");
const lossyCast = std.math.lossyCast;
pub const default_max_depth = 3;
pub const Alignment = enum {
Left,
Center,
Right,
};
pub const FormatOptions = struct {
precision: ?usize = null,
width: ?usize = null,
alignment: ?Alignment = null,
fill: u8 = ' ',
};
fn peekIsAlign(comptime fmt: []const u8) bool {
// Should only be called during a state transition to the format segment.
comptime assert(fmt[0] == ':');
inline for (([_]u8{ 1, 2 })[0..]) |i| {
if (fmt.len > i and (fmt[i] == '<' or fmt[i] == '^' or fmt[i] == '>')) {
return true;
}
}
return false;
}
/// Renders fmt string with args, calling output with slices of bytes.
/// If `output` returns an error, the error is returned from `format` and
/// `output` is not called again.
///
/// The format string must be comptime known and may contain placeholders following
/// this format:
/// `{[position][specifier]:[fill][alignment][width].[precision]}`
///
/// Each word between `[` and `]` is a parameter you have to replace with something:
///
/// - *position* is the index of the argument that should be inserted
/// - *specifier* is a type-dependent formatting option that determines how a type should formatted (see below)
/// - *fill* is a single character which is used to pad the formatted text
/// - *alignment* is one of the three characters `<`, `^` or `>`. they define if the text is *left*, *center*, or *right* aligned
/// - *width* is the total width of the field in characters
/// - *precision* specifies how many decimals a formatted number should have
///
/// Note that most of the parameters are optional and may be omitted. Also you can leave out separators like `:` and `.` when
/// all parameters after the separator are omitted.
/// Only exception is the *fill* parameter. If *fill* is required, one has to specify *alignment* as well, as otherwise
/// the digits after `:` is interpreted as *width*, not *fill*.
///
/// The *specifier* has several options for types:
/// - `x` and `X`:
/// - format the non-numeric value as a string of bytes in hexadecimal notation ("binary dump") in either lower case or upper case
/// - output numeric value in hexadecimal notation
/// - `s`: print a pointer-to-many as a c-string, use zero-termination
/// - `B` and `Bi`: output a memory size in either metric (1000) or power-of-two (1024) based notation. works for both float and integer values.
/// - `e`: output floating point value in scientific notation
/// - `d`: output numeric value in decimal notation
/// - `b`: output integer value in binary notation
/// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max.
/// - `*`: output the address of the value instead of the value itself.
///
/// If a formatted user type contains a function of the type
/// ```
/// fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, comptime Errors: type, output: fn (@TypeOf(context), []const u8) Errors!void) Errors!void
/// ```
/// with `?` being the type formatted, this function will be called instead of the default implementation.
/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.
///
/// A user type may be a `struct`, `union` or `enum` type.
pub fn format(
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
comptime fmt: []const u8,
args: var,
) Errors!void {
const ArgSetType = @IntType(false, 32);
if (@typeInfo(@TypeOf(args)) != .Struct) {
@compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));
}
if (args.len > ArgSetType.bit_count) {
@compileError("32 arguments max are supported per format call");
}
const State = enum {
Start,
Positional,
CloseBrace,
Specifier,
FormatFillAndAlign,
FormatWidth,
FormatPrecision,
};
comptime var start_index = 0;
comptime var state = State.Start;
comptime var maybe_pos_arg: ?comptime_int = null;
comptime var specifier_start = 0;
comptime var specifier_end = 0;
comptime var options = FormatOptions{};
comptime var arg_state: struct {
next_arg: usize = 0,
used_args: ArgSetType = 0,
args_len: usize = args.len,
fn hasUnusedArgs(comptime self: *@This()) bool {
return (@popCount(ArgSetType, self.used_args) != self.args_len);
}
fn nextArg(comptime self: *@This(), comptime pos_arg: ?comptime_int) comptime_int {
const next_idx = pos_arg orelse blk: {
const arg = self.next_arg;
self.next_arg += 1;
break :blk arg;
};
if (next_idx >= self.args_len) {
@compileError("Too few arguments");
}
// Mark this argument as used
self.used_args |= 1 << next_idx;
return next_idx;
}
} = .{};
inline for (fmt) |c, i| {
switch (state) {
.Start => switch (c) {
'{' => {
if (start_index < i) {
try output(context, fmt[start_index..i]);
}
start_index = i;
specifier_start = i + 1;
specifier_end = i + 1;
maybe_pos_arg = null;
state = .Positional;
options = FormatOptions{};
},
'}' => {
if (start_index < i) {
try output(context, fmt[start_index..i]);
}
state = .CloseBrace;
},
else => {},
},
.Positional => switch (c) {
'{' => {
state = .Start;
start_index = i;
},
':' => {
state = if (comptime peekIsAlign(fmt[i..])) State.FormatFillAndAlign else State.FormatWidth;
specifier_end = i;
},
'0'...'9' => {
if (maybe_pos_arg == null) {
maybe_pos_arg = 0;
}
maybe_pos_arg.? *= 10;
maybe_pos_arg.? += c - '0';
specifier_start = i + 1;
if (maybe_pos_arg.? >= args.len) {
@compileError("Positional value refers to non-existent argument");
}
},
'}' => {
const arg_to_print = comptime arg_state.nextArg(maybe_pos_arg);
try formatType(
args[arg_to_print],
fmt[0..0],
options,
context,
Errors,
output,
default_max_depth,
);
state = .Start;
start_index = i + 1;
},
else => {
state = .Specifier;
specifier_start = i;
},
},
.CloseBrace => switch (c) {
'}' => {
state = .Start;
start_index = i;
},
else => @compileError("Single '}' encountered in format string"),
},
.Specifier => switch (c) {
':' => {
specifier_end = i;
state = if (comptime peekIsAlign(fmt[i..])) State.FormatFillAndAlign else State.FormatWidth;
},
'}' => {
const arg_to_print = comptime arg_state.nextArg(maybe_pos_arg);
try formatType(
args[arg_to_print],
fmt[specifier_start..i],
options,
context,
Errors,
output,
default_max_depth,
);
state = .Start;
start_index = i + 1;
},
else => {},
},
// Only entered if the format string contains a fill/align segment.
.FormatFillAndAlign => switch (c) {
'<' => {
options.alignment = Alignment.Left;
state = .FormatWidth;
},
'^' => {
options.alignment = Alignment.Center;
state = .FormatWidth;
},
'>' => {
options.alignment = Alignment.Right;
state = .FormatWidth;
},
else => {
options.fill = c;
},
},
.FormatWidth => switch (c) {
'0'...'9' => {
if (options.width == null) {
options.width = 0;
}
options.width.? *= 10;
options.width.? += c - '0';
},
'.' => {
state = .FormatPrecision;
},
'}' => {
const arg_to_print = comptime arg_state.nextArg(maybe_pos_arg);
try formatType(
args[arg_to_print],
fmt[specifier_start..specifier_end],
options,
context,
Errors,
output,
default_max_depth,
);
state = .Start;
start_index = i + 1;
},
else => {
@compileError("Unexpected character in width value: " ++ [_]u8{c});
},
},
.FormatPrecision => switch (c) {
'0'...'9' => {
if (options.precision == null) {
options.precision = 0;
}
options.precision.? *= 10;
options.precision.? += c - '0';
},
'}' => {
const arg_to_print = comptime arg_state.nextArg(maybe_pos_arg);
try formatType(
args[arg_to_print],
fmt[specifier_start..specifier_end],
options,
context,
Errors,
output,
default_max_depth,
);
state = .Start;
start_index = i + 1;
},
else => {
@compileError("Unexpected character in precision value: " ++ [_]u8{c});
},
},
}
}
comptime {
if (comptime arg_state.hasUnusedArgs()) {
@compileError("Unused arguments");
}
if (state != State.Start) {
@compileError("Incomplete format string: " ++ fmt);
}
}
if (start_index < fmt.len) {
try output(context, fmt[start_index..]);
}
}
pub fn formatType(
value: var,
comptime fmt: []const u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
max_depth: usize,
) Errors!void {
if (comptime std.mem.eql(u8, fmt, "*")) {
try output(context, @typeName(@TypeOf(value).Child));
try output(context, "@");
try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, context, Errors, output);
return;
}
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.ComptimeInt, .Int, .Float => {
return formatValue(value, fmt, options, context, Errors, output);
},
.Void => {
return output(context, "void");
},
.Bool => {
return output(context, if (value) "true" else "false");
},
.Optional => {
if (value) |payload| {
return formatType(payload, fmt, options, context, Errors, output, max_depth);
} else {
return output(context, "null");
}
},
.ErrorUnion => {
if (value) |payload| {
return formatType(payload, fmt, options, context, Errors, output, max_depth);
} else |err| {
return formatType(err, fmt, options, context, Errors, output, max_depth);
}
},
.ErrorSet => {
try output(context, "error.");
return output(context, @errorName(value));
},
.Enum => {
if (comptime std.meta.trait.hasFn("format")(T)) {
return value.format(fmt, options, context, Errors, output);
}
try output(context, @typeName(T));
try output(context, ".");
return formatType(@tagName(value), "", options, context, Errors, output, max_depth);
},
.Union => {
if (comptime std.meta.trait.hasFn("format")(T)) {
return value.format(fmt, options, context, Errors, output);
}
try output(context, @typeName(T));
if (max_depth == 0) {
return output(context, "{ ... }");
}
const info = @typeInfo(T).Union;
if (info.tag_type) |UnionTagType| {
try output(context, "{ .");
try output(context, @tagName(@as(UnionTagType, value)));
try output(context, " = ");
inline for (info.fields) |u_field| {
if (@enumToInt(@as(UnionTagType, value)) == u_field.enum_field.?.value) {
try formatType(@field(value, u_field.name), "", options, context, Errors, output, max_depth - 1);
}
}
try output(context, " }");
} else {
try format(context, Errors, output, "@{x}", .{@ptrToInt(&value)});
}
},
.Struct => {
if (comptime std.meta.trait.hasFn("format")(T)) {
return value.format(fmt, options, context, Errors, output);
}
try output(context, @typeName(T));
if (max_depth == 0) {
return output(context, "{ ... }");
}
comptime var field_i = 0;
try output(context, "{");
inline while (field_i < @memberCount(T)) : (field_i += 1) {
if (field_i == 0) {
try output(context, " .");
} else {
try output(context, ", .");
}
try output(context, @memberName(T, field_i));
try output(context, " = ");
try formatType(@field(value, @memberName(T, field_i)), "", options, context, Errors, output, max_depth - 1);
}
try output(context, " }");
},
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => switch (@typeInfo(ptr_info.child)) {
builtin.TypeId.Array => |info| {
if (info.child == u8) {
return formatText(value, fmt, options, context, Errors, output);
}
return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
},
builtin.TypeId.Enum, builtin.TypeId.Union, builtin.TypeId.Struct => {
return formatType(value.*, fmt, options, context, Errors, output, max_depth);
},
else => return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }),
},
.Many, .C => {
if (ptr_info.child == u8) {
if (fmt.len > 0 and fmt[0] == 's') {
const len = mem.len(u8, value);
return formatText(value[0..len], fmt, options, context, Errors, output);
}
}
return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
},
.Slice => {
if (fmt.len > 0 and ((fmt[0] == 'x') or (fmt[0] == 'X'))) {
return formatText(value, fmt, options, context, Errors, output);
}
if (ptr_info.child == u8) {
return formatText(value, fmt, options, context, Errors, output);
}
return format(context, Errors, output, "{}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value.ptr) });
},
},
.Array => |info| {
const Slice = @Type(builtin.TypeInfo{
.Pointer = .{
.size = .Slice,
.is_const = true,
.is_volatile = false,
.is_allowzero = false,
.alignment = @alignOf(info.child),
.child = info.child,
.sentinel = null,
},
});
return formatType(@as(Slice, &value), fmt, options, context, Errors, output, max_depth);
},
.Fn => {
return format(context, Errors, output, "{}@{x}", .{ @typeName(T), @ptrToInt(value) });
},
.Type => return output(context, @typeName(T)),
else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"),
}
}
fn formatValue(
value: var,
comptime fmt: []const u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
if (comptime std.mem.eql(u8, fmt, "B")) {
return formatBytes(value, options, 1000, context, Errors, output);
} else if (comptime std.mem.eql(u8, fmt, "Bi")) {
return formatBytes(value, options, 1024, context, Errors, output);
}
const T = @TypeOf(value);
switch (@typeId(T)) {
.Float => return formatFloatValue(value, fmt, options, context, Errors, output),
.Int, .ComptimeInt => return formatIntValue(value, fmt, options, context, Errors, output),
else => comptime unreachable,
}
}
pub fn formatIntValue(
value: var,
comptime fmt: []const u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
comptime var radix = 10;
comptime var uppercase = false;
const int_value = if (@TypeOf(value) == comptime_int) blk: {
const Int = math.IntFittingRange(value, value);
break :blk @as(Int, value);
} else
value;
if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "d")) {
radix = 10;
uppercase = false;
} else if (comptime std.mem.eql(u8, fmt, "c")) {
if (@TypeOf(int_value).bit_count <= 8) {
return formatAsciiChar(@as(u8, int_value), options, context, Errors, output);
} else {
@compileError("Cannot print integer that is larger than 8 bits as a ascii");
}
} else if (comptime std.mem.eql(u8, fmt, "b")) {
radix = 2;
uppercase = false;
} else if (comptime std.mem.eql(u8, fmt, "x")) {
radix = 16;
uppercase = false;
} else if (comptime std.mem.eql(u8, fmt, "X")) {
radix = 16;
uppercase = true;
} else {
@compileError("Unknown format string: '" ++ fmt ++ "'");
}
return formatInt(int_value, radix, uppercase, options, context, Errors, output);
}
fn formatFloatValue(
value: var,
comptime fmt: []const u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "e")) {
return formatFloatScientific(value, options, context, Errors, output);
} else if (comptime std.mem.eql(u8, fmt, "d")) {
return formatFloatDecimal(value, options, context, Errors, output);
} else {
@compileError("Unknown format string: '" ++ fmt ++ "'");
}
}
pub fn formatText(
bytes: []const u8,
comptime fmt: []const u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
if (fmt.len == 0) {
return output(context, bytes);
} else if (comptime std.mem.eql(u8, fmt, "s")) {
return formatBuf(bytes, options, context, Errors, output);
} else if (comptime (std.mem.eql(u8, fmt, "x") or std.mem.eql(u8, fmt, "X"))) {
for (bytes) |c| {
try formatInt(c, 16, fmt[0] == 'X', FormatOptions{ .width = 2, .fill = '0' }, context, Errors, output);
}
return;
} else {
@compileError("Unknown format string: '" ++ fmt ++ "'");
}
}
pub fn formatAsciiChar(
c: u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
return output(context, @as(*const [1]u8, &c)[0..]);
}
pub fn formatBuf(
buf: []const u8,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
try output(context, buf);
const width = options.width orelse 0;
var leftover_padding = if (width > buf.len) (width - buf.len) else return;
const pad_byte: u8 = options.fill;
while (leftover_padding > 0) : (leftover_padding -= 1) {
try output(context, @as(*const [1]u8, &pad_byte)[0..1]);
}
}
// Print a float in scientific notation to the specified precision. Null uses full precision.
// It should be the case that every full precision, printed value can be re-parsed back to the
// same type unambiguously.
pub fn formatFloatScientific(
value: var,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
var x = @floatCast(f64, value);
// Errol doesn't handle these special cases.
if (math.signbit(x)) {
try output(context, "-");
x = -x;
}
if (math.isNan(x)) {
return output(context, "nan");
}
if (math.isPositiveInf(x)) {
return output(context, "inf");
}
if (x == 0.0) {
try output(context, "0");
if (options.precision) |precision| {
if (precision != 0) {
try output(context, ".");
var i: usize = 0;
while (i < precision) : (i += 1) {
try output(context, "0");
}
}
} else {
try output(context, ".0");
}
try output(context, "e+00");
return;
}
var buffer: [32]u8 = undefined;
var float_decimal = errol.errol3(x, buffer[0..]);
if (options.precision) |precision| {
errol.roundToPrecision(&float_decimal, precision, errol.RoundMode.Scientific);
try output(context, float_decimal.digits[0..1]);
// {e0} case prints no `.`
if (precision != 0) {
try output(context, ".");
var printed: usize = 0;
if (float_decimal.digits.len > 1) {
const num_digits = math.min(float_decimal.digits.len, precision + 1);
try output(context, float_decimal.digits[1..num_digits]);
printed += num_digits - 1;
}
while (printed < precision) : (printed += 1) {
try output(context, "0");
}
}
} else {
try output(context, float_decimal.digits[0..1]);
try output(context, ".");
if (float_decimal.digits.len > 1) {
const num_digits = if (@TypeOf(value) == f32) math.min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len;
try output(context, float_decimal.digits[1..num_digits]);
} else {
try output(context, "0");
}
}
try output(context, "e");
const exp = float_decimal.exp - 1;
if (exp >= 0) {
try output(context, "+");
if (exp > -10 and exp < 10) {
try output(context, "0");
}
try formatInt(exp, 10, false, FormatOptions{ .width = 0 }, context, Errors, output);
} else {
try output(context, "-");
if (exp > -10 and exp < 10) {
try output(context, "0");
}
try formatInt(-exp, 10, false, FormatOptions{ .width = 0 }, context, Errors, output);
}
}
// Print a float of the format x.yyyyy where the number of y is specified by the precision argument.
// By default floats are printed at full precision (no rounding).
pub fn formatFloatDecimal(
value: var,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
var x = @as(f64, value);
// Errol doesn't handle these special cases.
if (math.signbit(x)) {
try output(context, "-");
x = -x;
}
if (math.isNan(x)) {
return output(context, "nan");
}
if (math.isPositiveInf(x)) {
return output(context, "inf");
}
if (x == 0.0) {
try output(context, "0");
if (options.precision) |precision| {
if (precision != 0) {
try output(context, ".");
var i: usize = 0;
while (i < precision) : (i += 1) {
try output(context, "0");
}
} else {
try output(context, ".0");
}
} else {
try output(context, "0");
}
return;
}
// non-special case, use errol3
var buffer: [32]u8 = undefined;
var float_decimal = errol.errol3(x, buffer[0..]);
if (options.precision) |precision| {
errol.roundToPrecision(&float_decimal, precision, errol.RoundMode.Decimal);
// exp < 0 means the leading is always 0 as errol result is normalized.
var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0;
// the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this.
var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len);
if (num_digits_whole > 0) {
// We may have to zero pad, for instance 1e4 requires zero padding.
try output(context, float_decimal.digits[0..num_digits_whole_no_pad]);
var i = num_digits_whole_no_pad;
while (i < num_digits_whole) : (i += 1) {
try output(context, "0");
}
} else {
try output(context, "0");
}
// {.0} special case doesn't want a trailing '.'
if (precision == 0) {
return;
}
try output(context, ".");
// Keep track of fractional count printed for case where we pre-pad then post-pad with 0's.
var printed: usize = 0;
// Zero-fill until we reach significant digits or run out of precision.
if (float_decimal.exp <= 0) {
const zero_digit_count = @intCast(usize, -float_decimal.exp);
const zeros_to_print = math.min(zero_digit_count, precision);
var i: usize = 0;
while (i < zeros_to_print) : (i += 1) {
try output(context, "0");
printed += 1;
}
if (printed >= precision) {
return;
}
}
// Remaining fractional portion, zero-padding if insufficient.
assert(precision >= printed);
if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) {
try output(context, float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]);
return;
} else {
try output(context, float_decimal.digits[num_digits_whole_no_pad..]);
printed += float_decimal.digits.len - num_digits_whole_no_pad;
while (printed < precision) : (printed += 1) {
try output(context, "0");
}
}
} else {
// exp < 0 means the leading is always 0 as errol result is normalized.
var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0;
// the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this.
var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len);
if (num_digits_whole > 0) {
// We may have to zero pad, for instance 1e4 requires zero padding.
try output(context, float_decimal.digits[0..num_digits_whole_no_pad]);
var i = num_digits_whole_no_pad;
while (i < num_digits_whole) : (i += 1) {
try output(context, "0");
}
} else {
try output(context, "0");
}
// Omit `.` if no fractional portion
if (float_decimal.exp >= 0 and num_digits_whole_no_pad == float_decimal.digits.len) {
return;
}
try output(context, ".");
// Zero-fill until we reach significant digits or run out of precision.
if (float_decimal.exp < 0) {
const zero_digit_count = @intCast(usize, -float_decimal.exp);
var i: usize = 0;
while (i < zero_digit_count) : (i += 1) {
try output(context, "0");
}
}
try output(context, float_decimal.digits[num_digits_whole_no_pad..]);
}
}
pub fn formatBytes(
value: var,
options: FormatOptions,
comptime radix: usize,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
if (value == 0) {
return output(context, "0B");
}
const mags_si = " kMGTPEZY";
const mags_iec = " KMGTPEZY";
const magnitude = switch (radix) {
1000 => math.min(math.log2(value) / comptime math.log2(1000), mags_si.len - 1),
1024 => math.min(math.log2(value) / 10, mags_iec.len - 1),
else => unreachable,
};
const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, radix), lossyCast(f64, magnitude));
const suffix = switch (radix) {
1000 => mags_si[magnitude],
1024 => mags_iec[magnitude],
else => unreachable,
};
try formatFloatDecimal(new_value, options, context, Errors, output);
if (suffix == ' ') {
return output(context, "B");
}
const buf = switch (radix) {
1000 => &[_]u8{ suffix, 'B' },
1024 => &[_]u8{ suffix, 'i', 'B' },
else => unreachable,
};
return output(context, buf);
}
pub fn formatInt(
value: var,
base: u8,
uppercase: bool,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
const int_value = if (@TypeOf(value) == comptime_int) blk: {
const Int = math.IntFittingRange(value, value);
break :blk @as(Int, value);
} else
value;
if (@TypeOf(int_value).is_signed) {
return formatIntSigned(int_value, base, uppercase, options, context, Errors, output);
} else {
return formatIntUnsigned(int_value, base, uppercase, options, context, Errors, output);
}
}
fn formatIntSigned(
value: var,
base: u8,
uppercase: bool,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
const new_options = FormatOptions{
.width = if (options.width) |w| (if (w == 0) 0 else w - 1) else null,
.precision = options.precision,
.fill = options.fill,
};
const uint = @IntType(false, @TypeOf(value).bit_count);
if (value < 0) {
const minus_sign: u8 = '-';
try output(context, @as(*const [1]u8, &minus_sign)[0..]);
const new_value = @intCast(uint, -(value + 1)) + 1;
return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output);
} else if (options.width == null or options.width.? == 0) {
return formatIntUnsigned(@intCast(uint, value), base, uppercase, options, context, Errors, output);
} else {
const plus_sign: u8 = '+';
try output(context, @as(*const [1]u8, &plus_sign)[0..]);
const new_value = @intCast(uint, value);
return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output);
}
}
fn formatIntUnsigned(
value: var,
base: u8,
uppercase: bool,
options: FormatOptions,
context: var,
comptime Errors: type,
output: fn (@TypeOf(context), []const u8) Errors!void,
) Errors!void {
assert(base >= 2);
var buf: [math.max(@TypeOf(value).bit_count, 1)]u8 = undefined;
const min_int_bits = comptime math.max(@TypeOf(value).bit_count, @TypeOf(base).bit_count);
const MinInt = @IntType(@TypeOf(value).is_signed, min_int_bits);
var a: MinInt = value;
var index: usize = buf.len;
while (true) {
const digit = a % base;
index -= 1;
buf[index] = digitToChar(@intCast(u8, digit), uppercase);
a /= base;
if (a == 0) break;
}
const digits_buf = buf[index..];
const width = options.width orelse 0;
const padding = if (width > digits_buf.len) (width - digits_buf.len) else 0;
if (padding > index) {
const zero_byte: u8 = options.fill;
var leftover_padding = padding - index;
while (true) {
try output(context, @as(*const [1]u8, &zero_byte)[0..]);
leftover_padding -= 1;
if (leftover_padding == 0) break;
}
mem.set(u8, buf[0..index], options.fill);
return output(context, &buf);
} else {
const padded_buf = buf[index - padding ..];
mem.set(u8, padded_buf[0..padding], options.fill);
return output(context, padded_buf);
}
}
pub fn formatIntBuf(out_buf: []u8, value: var, base: u8, uppercase: bool, options: FormatOptions) usize {
var context = FormatIntBuf{
.out_buf = out_buf,
.index = 0,
};
formatInt(value, base, uppercase, options, &context, error{}, formatIntCallback) catch unreachable;
return context.index;
}
const FormatIntBuf = struct {
out_buf: []u8,
index: usize,
};