/
fmt.zig
2634 lines (2313 loc) · 95.9 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 unicode = std.unicode;
const meta = std.meta;
const builtin = @import("builtin");
const errol = @import("fmt/errol.zig");
const lossyCast = std.math.lossyCast;
const expectFmt = std.testing.expectFmt;
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 = .Right,
fill: u8 = ' ',
};
/// 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:
/// `{[argument][specifier]:[fill][alignment][width].[precision]}`
///
/// Each word between `[` and `]` is a parameter you have to replace with something:
///
/// - *argument* is either the index or the name 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`: output numeric value in hexadecimal notation
/// - `s`:
/// - for pointer-to-many and C pointers of u8, print as a C-string using zero-termination
/// - for slices of u8, print the entire slice as a string without zero-termination
/// - `e`: output floating point value in scientific notation
/// - `d`: output numeric value in decimal notation
/// - `b`: output integer value in binary notation
/// - `o`: output integer value in octal notation
/// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max.
/// - `u`: output integer as an UTF-8 sequence. Integer type must have 21 bits at max.
/// - `*`: output the address of the value instead of the value itself.
/// - `any`: output a value of any type using its default format
///
/// If a formatted user type contains a function of the type
/// ```
/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !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`, `vector`, `union` or `enum` type.
///
/// To print literal curly braces, escape them by writing them twice, e.g. `{{` or `}}`.
pub fn format(
writer: anytype,
comptime fmt: []const u8,
args: anytype,
) !void {
const ArgsType = @TypeOf(args);
const args_type_info = @typeInfo(ArgsType);
// XXX: meta.trait.is(.Struct)(ArgsType) doesn't seem to work...
if (args_type_info != .Struct) {
@compileError("Expected tuple or struct argument, found " ++ @typeName(ArgsType));
}
const fields_info = args_type_info.Struct.fields;
if (fields_info.len > max_format_args) {
@compileError("32 arguments max are supported per format call");
}
@setEvalBranchQuota(2000000);
comptime var arg_state: ArgState = .{ .args_len = fields_info.len };
comptime var i = 0;
inline while (i < fmt.len) {
const start_index = i;
inline while (i < fmt.len) : (i += 1) {
switch (fmt[i]) {
'{', '}' => break,
else => {},
}
}
comptime var end_index = i;
comptime var unescape_brace = false;
// Handle {{ and }}, those are un-escaped as single braces
if (i + 1 < fmt.len and fmt[i + 1] == fmt[i]) {
unescape_brace = true;
// Make the first brace part of the literal...
end_index += 1;
// ...and skip both
i += 2;
}
// Write out the literal
if (start_index != end_index) {
try writer.writeAll(fmt[start_index..end_index]);
}
// We've already skipped the other brace, restart the loop
if (unescape_brace) continue;
if (i >= fmt.len) break;
if (fmt[i] == '}') {
@compileError("Missing opening {");
}
// Get past the {
comptime assert(fmt[i] == '{');
i += 1;
const fmt_begin = i;
// Find the closing brace
inline while (i < fmt.len and fmt[i] != '}') : (i += 1) {}
const fmt_end = i;
if (i >= fmt.len) {
@compileError("Missing closing }");
}
// Get past the }
comptime assert(fmt[i] == '}');
i += 1;
const placeholder = comptime parsePlaceholder(fmt[fmt_begin..fmt_end].*);
const arg_pos = comptime switch (placeholder.arg) {
.none => null,
.number => |pos| pos,
.named => |arg_name| meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("No argument with name '" ++ arg_name ++ "'"),
};
const width = switch (placeholder.width) {
.none => null,
.number => |v| v,
.named => |arg_name| blk: {
const arg_i = comptime meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("No argument with name '" ++ arg_name ++ "'");
_ = comptime arg_state.nextArg(arg_i) orelse @compileError("Too few arguments");
break :blk @field(args, arg_name);
},
};
const precision = switch (placeholder.precision) {
.none => null,
.number => |v| v,
.named => |arg_name| blk: {
const arg_i = comptime meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("No argument with name '" ++ arg_name ++ "'");
_ = comptime arg_state.nextArg(arg_i) orelse @compileError("Too few arguments");
break :blk @field(args, arg_name);
},
};
const arg_to_print = comptime arg_state.nextArg(arg_pos) orelse
@compileError("Too few arguments");
try formatType(
@field(args, fields_info[arg_to_print].name),
placeholder.specifier_arg,
FormatOptions{
.fill = placeholder.fill,
.alignment = placeholder.alignment,
.width = width,
.precision = precision,
},
writer,
default_max_depth,
);
}
if (comptime arg_state.hasUnusedArgs()) {
const missing_count = arg_state.args_len - @popCount(ArgSetType, arg_state.used_args);
switch (missing_count) {
0 => unreachable,
1 => @compileError("Unused argument in '" ++ fmt ++ "'"),
else => @compileError((comptime comptimePrint("{d}", .{missing_count})) ++ " unused arguments in '" ++ fmt ++ "'"),
}
}
}
fn parsePlaceholder(comptime str: anytype) Placeholder {
comptime var parser = Parser{ .buf = &str };
// Parse the positional argument number
const arg = comptime parser.specifier() catch |err|
@compileError(@errorName(err));
// Parse the format specifier
const specifier_arg = comptime parser.until(':');
// Skip the colon, if present
if (comptime parser.char()) |ch| {
if (ch != ':') {
@compileError("Expected : or }, found '" ++ [1]u8{ch} ++ "'");
}
}
// Parse the fill character
// The fill parameter requires the alignment parameter to be specified
// too
const fill = comptime if (parser.peek(1)) |ch|
switch (ch) {
'<', '^', '>' => parser.char().?,
else => ' ',
}
else
' ';
// Parse the alignment parameter
const alignment: Alignment = comptime if (parser.peek(0)) |ch| init: {
switch (ch) {
'<', '^', '>' => _ = parser.char(),
else => {},
}
break :init switch (ch) {
'<' => .Left,
'^' => .Center,
else => .Right,
};
} else .Right;
// Parse the width parameter
const width = comptime parser.specifier() catch |err|
@compileError(@errorName(err));
// Skip the dot, if present
if (comptime parser.char()) |ch| {
if (ch != '.') {
@compileError("Expected . or }, found '" ++ [1]u8{ch} ++ "'");
}
}
// Parse the precision parameter
const precision = comptime parser.specifier() catch |err|
@compileError(@errorName(err));
if (comptime parser.char()) |ch| {
@compileError("Extraneous trailing character '" ++ [1]u8{ch} ++ "'");
}
return Placeholder{
.specifier_arg = cacheString(specifier_arg[0..specifier_arg.len].*),
.fill = fill,
.alignment = alignment,
.arg = arg,
.width = width,
.precision = precision,
};
}
fn cacheString(str: anytype) []const u8 {
return &str;
}
const Placeholder = struct {
specifier_arg: []const u8,
fill: u8,
alignment: Alignment,
arg: Specifier,
width: Specifier,
precision: Specifier,
};
const Specifier = union(enum) {
none,
number: usize,
named: []const u8,
};
const Parser = struct {
buf: []const u8,
pos: usize = 0,
// Returns a decimal number or null if the current character is not a
// digit
fn number(self: *@This()) ?usize {
var r: ?usize = null;
while (self.pos < self.buf.len) : (self.pos += 1) {
switch (self.buf[self.pos]) {
'0'...'9' => {
if (r == null) r = 0;
r.? *= 10;
r.? += self.buf[self.pos] - '0';
},
else => break,
}
}
return r;
}
// Returns a substring of the input starting from the current position
// and ending where `ch` is found or until the end if not found
fn until(self: *@This(), ch: u8) []const u8 {
const start = self.pos;
if (start >= self.buf.len)
return &[_]u8{};
while (self.pos < self.buf.len) : (self.pos += 1) {
if (self.buf[self.pos] == ch) break;
}
return self.buf[start..self.pos];
}
// Returns one character, if available
fn char(self: *@This()) ?u8 {
if (self.pos < self.buf.len) {
const ch = self.buf[self.pos];
self.pos += 1;
return ch;
}
return null;
}
fn maybe(self: *@This(), val: u8) bool {
if (self.pos < self.buf.len and self.buf[self.pos] == val) {
self.pos += 1;
return true;
}
return false;
}
// Returns a decimal number or null if the current character is not a
// digit
fn specifier(self: *@This()) !Specifier {
if (self.maybe('[')) {
const arg_name = self.until(']');
if (!self.maybe(']'))
return @field(anyerror, "Expected closing ]");
return Specifier{ .named = arg_name };
}
if (self.number()) |i|
return Specifier{ .number = i };
return Specifier{ .none = {} };
}
// Returns the n-th next character or null if that's past the end
fn peek(self: *@This(), n: usize) ?u8 {
return if (self.pos + n < self.buf.len) self.buf[self.pos + n] else null;
}
};
const ArgSetType = u32;
const max_format_args = @typeInfo(ArgSetType).Int.bits;
const ArgState = struct {
next_arg: usize = 0,
used_args: ArgSetType = 0,
args_len: usize,
fn hasUnusedArgs(self: *@This()) bool {
return @popCount(ArgSetType, self.used_args) != self.args_len;
}
fn nextArg(self: *@This(), arg_index: ?usize) ?usize {
const next_index = arg_index orelse init: {
const arg = self.next_arg;
self.next_arg += 1;
break :init arg;
};
if (next_index >= self.args_len) {
return null;
}
// Mark this argument as used
self.used_args |= @as(ArgSetType, 1) << @intCast(u5, next_index);
return next_index;
}
};
pub fn formatAddress(value: anytype, options: FormatOptions, writer: anytype) @TypeOf(writer).Error!void {
_ = options;
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Pointer => |info| {
try writer.writeAll(@typeName(info.child) ++ "@");
if (info.size == .Slice)
try formatInt(@ptrToInt(value.ptr), 16, .lower, FormatOptions{}, writer)
else
try formatInt(@ptrToInt(value), 16, .lower, FormatOptions{}, writer);
return;
},
.Optional => |info| {
if (@typeInfo(info.child) == .Pointer) {
try writer.writeAll(@typeName(info.child) ++ "@");
try formatInt(@ptrToInt(value), 16, .lower, FormatOptions{}, writer);
return;
}
},
else => {},
}
@compileError("Cannot format non-pointer type " ++ @typeName(T) ++ " with * specifier");
}
// This ANY const is a workaround for: https://github.com/ziglang/zig/issues/7948
const ANY = "any";
fn defaultSpec(comptime T: type) [:0]const u8 {
switch (@typeInfo(T)) {
.Array => |_| return ANY,
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => switch (@typeInfo(ptr_info.child)) {
.Array => |_| return "*",
else => {},
},
.Many, .C => return "*",
.Slice => return ANY,
},
.Optional => |info| return defaultSpec(info.child),
else => {},
}
return "";
}
pub fn formatType(
value: anytype,
comptime fmt: []const u8,
options: FormatOptions,
writer: anytype,
max_depth: usize,
) @TypeOf(writer).Error!void {
const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY)) defaultSpec(@TypeOf(value)) else fmt;
if (comptime std.mem.eql(u8, actual_fmt, "*")) {
return formatAddress(value, options, writer);
}
const T = @TypeOf(value);
if (comptime std.meta.trait.hasFn("format")(T)) {
return try value.format(actual_fmt, options, writer);
}
switch (@typeInfo(T)) {
.ComptimeInt, .Int, .ComptimeFloat, .Float => {
return formatValue(value, actual_fmt, options, writer);
},
.Void => {
return formatBuf("void", options, writer);
},
.Bool => {
return formatBuf(if (value) "true" else "false", options, writer);
},
.Optional => {
if (value) |payload| {
return formatType(payload, actual_fmt, options, writer, max_depth);
} else {
return formatBuf("null", options, writer);
}
},
.ErrorUnion => {
if (value) |payload| {
return formatType(payload, actual_fmt, options, writer, max_depth);
} else |err| {
return formatType(err, actual_fmt, options, writer, max_depth);
}
},
.ErrorSet => {
try writer.writeAll("error.");
return writer.writeAll(@errorName(value));
},
.Enum => |enumInfo| {
try writer.writeAll(@typeName(T));
if (enumInfo.is_exhaustive) {
try writer.writeAll(".");
try writer.writeAll(@tagName(value));
return;
}
// Use @tagName only if value is one of known fields
@setEvalBranchQuota(3 * enumInfo.fields.len);
inline for (enumInfo.fields) |enumField| {
if (@enumToInt(value) == enumField.value) {
try writer.writeAll(".");
try writer.writeAll(@tagName(value));
return;
}
}
try writer.writeAll("(");
try formatType(@enumToInt(value), actual_fmt, options, writer, max_depth);
try writer.writeAll(")");
},
.Union => |info| {
try writer.writeAll(@typeName(T));
if (max_depth == 0) {
return writer.writeAll("{ ... }");
}
if (info.tag_type) |UnionTagType| {
try writer.writeAll("{ .");
try writer.writeAll(@tagName(@as(UnionTagType, value)));
try writer.writeAll(" = ");
inline for (info.fields) |u_field| {
if (value == @field(UnionTagType, u_field.name)) {
try formatType(@field(value, u_field.name), ANY, options, writer, max_depth - 1);
}
}
try writer.writeAll(" }");
} else {
try format(writer, "@{x}", .{@ptrToInt(&value)});
}
},
.Struct => |info| {
if (info.is_tuple) {
// Skip the type and field names when formatting tuples.
if (max_depth == 0) {
return writer.writeAll("{ ... }");
}
try writer.writeAll("{");
inline for (info.fields) |f, i| {
if (i == 0) {
try writer.writeAll(" ");
} else {
try writer.writeAll(", ");
}
try formatType(@field(value, f.name), ANY, options, writer, max_depth - 1);
}
return writer.writeAll(" }");
}
try writer.writeAll(@typeName(T));
if (max_depth == 0) {
return writer.writeAll("{ ... }");
}
try writer.writeAll("{");
inline for (info.fields) |f, i| {
if (i == 0) {
try writer.writeAll(" .");
} else {
try writer.writeAll(", .");
}
try writer.writeAll(f.name);
try writer.writeAll(" = ");
try formatType(@field(value, f.name), ANY, options, writer, max_depth - 1);
}
try writer.writeAll(" }");
},
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => switch (@typeInfo(ptr_info.child)) {
.Array => |info| {
if (actual_fmt.len == 0)
@compileError("cannot format array ref without a specifier (i.e. {s} or {*})");
if (info.child == u8) {
switch (actual_fmt[0]) {
's', 'x', 'X', 'e', 'E' => {
comptime checkTextFmt(actual_fmt);
return formatBuf(value, options, writer);
},
else => {},
}
}
if (comptime std.meta.trait.isZigString(info.child)) {
for (value) |item, i| {
comptime checkTextFmt(actual_fmt);
if (i != 0) try formatBuf(", ", options, writer);
try formatBuf(item, options, writer);
}
return;
}
@compileError("Unknown format string: '" ++ actual_fmt ++ "' for type '" ++ @typeName(T) ++ "'");
},
.Enum, .Union, .Struct => {
return formatType(value.*, actual_fmt, options, writer, max_depth);
},
else => return format(writer, "{s}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value) }),
},
.Many, .C => {
if (actual_fmt.len == 0)
@compileError("cannot format pointer without a specifier (i.e. {s} or {*})");
if (ptr_info.sentinel) |_| {
return formatType(mem.span(value), actual_fmt, options, writer, max_depth);
}
if (ptr_info.child == u8) {
switch (actual_fmt[0]) {
's', 'x', 'X', 'e', 'E' => {
comptime checkTextFmt(actual_fmt);
return formatBuf(mem.span(value), options, writer);
},
else => {},
}
}
@compileError("Unknown format string: '" ++ actual_fmt ++ "' for type '" ++ @typeName(T) ++ "'");
},
.Slice => {
if (actual_fmt.len == 0)
@compileError("cannot format slice without a specifier (i.e. {s} or {any})");
if (max_depth == 0) {
return writer.writeAll("{ ... }");
}
if (ptr_info.child == u8) {
switch (actual_fmt[0]) {
's', 'x', 'X', 'e', 'E' => {
comptime checkTextFmt(actual_fmt);
return formatBuf(value, options, writer);
},
else => {},
}
}
try writer.writeAll("{ ");
for (value) |elem, i| {
try formatType(elem, actual_fmt, options, writer, max_depth - 1);
if (i != value.len - 1) {
try writer.writeAll(", ");
}
}
try writer.writeAll(" }");
},
},
.Array => |info| {
if (actual_fmt.len == 0)
@compileError("cannot format array without a specifier (i.e. {s} or {any})");
if (max_depth == 0) {
return writer.writeAll("{ ... }");
}
if (info.child == u8) {
switch (actual_fmt[0]) {
's', 'x', 'X', 'e', 'E' => {
comptime checkTextFmt(actual_fmt);
return formatBuf(&value, options, writer);
},
else => {},
}
}
try writer.writeAll("{ ");
for (value) |elem, i| {
try formatType(elem, actual_fmt, options, writer, max_depth - 1);
if (i < value.len - 1) {
try writer.writeAll(", ");
}
}
try writer.writeAll(" }");
},
.Vector => |info| {
try writer.writeAll("{ ");
var i: usize = 0;
while (i < info.len) : (i += 1) {
try formatValue(value[i], actual_fmt, options, writer);
if (i < info.len - 1) {
try writer.writeAll(", ");
}
}
try writer.writeAll(" }");
},
.Fn => {
return format(writer, "{s}@{x}", .{ @typeName(T), @ptrToInt(value) });
},
.Type => return formatBuf(@typeName(value), options, writer),
.EnumLiteral => {
const buffer = [_]u8{'.'} ++ @tagName(value);
return formatBuf(buffer, options, writer);
},
.Null => return formatBuf("null", options, writer),
else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"),
}
}
fn formatValue(
value: anytype,
comptime fmt: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
if (comptime std.mem.eql(u8, fmt, "B")) {
@compileError("specifier 'B' has been deprecated, wrap your argument in std.fmt.fmtIntSizeDec instead");
} else if (comptime std.mem.eql(u8, fmt, "Bi")) {
@compileError("specifier 'Bi' has been deprecated, wrap your argument in std.fmt.fmtIntSizeBin instead");
}
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Float, .ComptimeFloat => return formatFloatValue(value, fmt, options, writer),
.Int, .ComptimeInt => return formatIntValue(value, fmt, options, writer),
.Bool => return formatBuf(if (value) "true" else "false", options, writer),
else => comptime unreachable,
}
}
pub fn formatIntValue(
value: anytype,
comptime fmt: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
comptime var radix = 10;
comptime var case: Case = .lower;
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;
case = .lower;
} else if (comptime std.mem.eql(u8, fmt, "c")) {
if (@typeInfo(@TypeOf(int_value)).Int.bits <= 8) {
return formatAsciiChar(@as(u8, int_value), options, writer);
} else {
@compileError("Cannot print integer that is larger than 8 bits as an ASCII character");
}
} else if (comptime std.mem.eql(u8, fmt, "u")) {
if (@typeInfo(@TypeOf(int_value)).Int.bits <= 21) {
return formatUnicodeCodepoint(@as(u21, int_value), options, writer);
} else {
@compileError("Cannot print integer that is larger than 21 bits as an UTF-8 sequence");
}
} else if (comptime std.mem.eql(u8, fmt, "b")) {
radix = 2;
case = .lower;
} else if (comptime std.mem.eql(u8, fmt, "x")) {
radix = 16;
case = .lower;
} else if (comptime std.mem.eql(u8, fmt, "X")) {
radix = 16;
case = .upper;
} else if (comptime std.mem.eql(u8, fmt, "o")) {
radix = 8;
case = .lower;
} else {
@compileError("Unsupported format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'");
}
return formatInt(int_value, radix, case, options, writer);
}
fn formatFloatValue(
value: anytype,
comptime fmt: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
// this buffer should be enough to display all decimal places of a decimal f64 number.
var buf: [512]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);
if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "e")) {
formatFloatScientific(value, options, buf_stream.writer()) catch |err| switch (err) {
error.NoSpaceLeft => unreachable,
else => |e| return e,
};
} else if (comptime std.mem.eql(u8, fmt, "d")) {
formatFloatDecimal(value, options, buf_stream.writer()) catch |err| switch (err) {
error.NoSpaceLeft => unreachable,
else => |e| return e,
};
} else if (comptime std.mem.eql(u8, fmt, "x")) {
formatFloatHexadecimal(value, options, buf_stream.writer()) catch |err| switch (err) {
error.NoSpaceLeft => unreachable,
else => |e| return e,
};
} else {
@compileError("Unsupported format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'");
}
return formatBuf(buf_stream.getWritten(), options, writer);
}
pub const Case = enum { lower, upper };
fn formatSliceHexImpl(comptime case: Case) type {
const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef";
return struct {
pub fn f(
bytes: []const u8,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
var buf: [2]u8 = undefined;
for (bytes) |c| {
buf[0] = charset[c >> 4];
buf[1] = charset[c & 15];
try writer.writeAll(&buf);
}
}
};
}
const formatSliceHexLower = formatSliceHexImpl(.lower).f;
const formatSliceHexUpper = formatSliceHexImpl(.upper).f;
/// Return a Formatter for a []const u8 where every byte is formatted as a pair
/// of lowercase hexadecimal digits.
pub fn fmtSliceHexLower(bytes: []const u8) std.fmt.Formatter(formatSliceHexLower) {
return .{ .data = bytes };
}
/// Return a Formatter for a []const u8 where every byte is formatted as pair
/// of uppercase hexadecimal digits.
pub fn fmtSliceHexUpper(bytes: []const u8) std.fmt.Formatter(formatSliceHexUpper) {
return .{ .data = bytes };
}
fn formatSliceEscapeImpl(comptime case: Case) type {
const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef";
return struct {
pub fn f(
bytes: []const u8,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
var buf: [4]u8 = undefined;
buf[0] = '\\';
buf[1] = 'x';
for (bytes) |c| {
if (std.ascii.isPrint(c)) {
try writer.writeByte(c);
} else {
buf[2] = charset[c >> 4];
buf[3] = charset[c & 15];
try writer.writeAll(&buf);
}
}
}
};
}
const formatSliceEscapeLower = formatSliceEscapeImpl(.lower).f;
const formatSliceEscapeUpper = formatSliceEscapeImpl(.upper).f;
/// Return a Formatter for a []const u8 where every non-printable ASCII
/// character is escaped as \xNN, where NN is the character in lowercase
/// hexadecimal notation.
pub fn fmtSliceEscapeLower(bytes: []const u8) std.fmt.Formatter(formatSliceEscapeLower) {
return .{ .data = bytes };
}
/// Return a Formatter for a []const u8 where every non-printable ASCII
/// character is escaped as \xNN, where NN is the character in uppercase
/// hexadecimal notation.
pub fn fmtSliceEscapeUpper(bytes: []const u8) std.fmt.Formatter(formatSliceEscapeUpper) {
return .{ .data = bytes };
}
fn formatSizeImpl(comptime radix: comptime_int) type {
return struct {
fn f(
value: u64,
comptime fmt: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
_ = fmt;
if (value == 0) {
return writer.writeAll("0B");
}
const mags_si = " kMGTPEZY";
const mags_iec = " KMGTPEZY";
const log2 = math.log2(value);
const magnitude = switch (radix) {
1000 => math.min(log2 / comptime math.log2(1000), mags_si.len - 1),
1024 => math.min(log2 / 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, writer);
if (suffix == ' ') {
return writer.writeAll("B");
}
const buf = switch (radix) {
1000 => &[_]u8{ suffix, 'B' },
1024 => &[_]u8{ suffix, 'i', 'B' },
else => unreachable,
};
return writer.writeAll(buf);
}
};
}
const formatSizeDec = formatSizeImpl(1000).f;
const formatSizeBin = formatSizeImpl(1024).f;
/// Return a Formatter for a u64 value representing a file size.
/// This formatter represents the number as multiple of 1000 and uses the SI
/// measurement units (kB, MB, GB, ...).
pub fn fmtIntSizeDec(value: u64) std.fmt.Formatter(formatSizeDec) {
return .{ .data = value };
}
/// Return a Formatter for a u64 value representing a file size.
/// This formatter represents the number as multiple of 1024 and uses the IEC
/// measurement units (KiB, MiB, GiB, ...).
pub fn fmtIntSizeBin(value: u64) std.fmt.Formatter(formatSizeBin) {
return .{ .data = value };
}
fn checkTextFmt(comptime fmt: []const u8) void {
if (fmt.len != 1)
@compileError("Unsupported format string '" ++ fmt ++ "' when formatting text");
switch (fmt[0]) {
'x' => @compileError("specifier 'x' has been deprecated, wrap your argument in std.fmt.fmtSliceHexLower instead"),
'X' => @compileError("specifier 'X' has been deprecated, wrap your argument in std.fmt.fmtSliceHexUpper instead"),
'e' => @compileError("specifier 'e' has been deprecated, wrap your argument in std.fmt.fmtSliceEscapeLower instead"),
'E' => @compileError("specifier 'E' has been deprecated, wrap your argument in std.fmt.fmtSliceEscapeUpper instead"),
'z' => @compileError("specifier 'z' has been deprecated, wrap your argument in std.zig.fmtId instead"),
'Z' => @compileError("specifier 'Z' has been deprecated, wrap your argument in std.zig.fmtEscapes instead"),
else => {},
}
}
pub fn formatText(
bytes: []const u8,
comptime fmt: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
comptime checkTextFmt(fmt);
return formatBuf(bytes, options, writer);
}
pub fn formatAsciiChar(
c: u8,
options: FormatOptions,
writer: anytype,
) !void {
_ = options;
return writer.writeAll(@as(*const [1]u8, &c));
}
pub fn formatUnicodeCodepoint(
c: u21,
options: FormatOptions,
writer: anytype,
) !void {
var buf: [4]u8 = undefined;
const len = std.unicode.utf8Encode(c, &buf) catch |err| switch (err) {
error.Utf8CannotEncodeSurrogateHalf, error.CodepointTooLarge => {
// In case of error output the replacement char U+FFFD
return formatBuf(&[_]u8{ 0xef, 0xbf, 0xbd }, options, writer);
},
};
return formatBuf(buf[0..len], options, writer);
}
pub fn formatBuf(
buf: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
if (options.width) |min_width| {
// In case of error assume the buffer content is ASCII-encoded
const width = unicode.utf8CountCodepoints(buf) catch buf.len;
const padding = if (width < min_width) min_width - width else 0;
if (padding == 0)
return writer.writeAll(buf);
switch (options.alignment) {
.Left => {
try writer.writeAll(buf);
try writer.writeByteNTimes(options.fill, padding);
},
.Center => {