1//! String formatting and parsing.
2
3const builtin = @import("builtin");
4
5const std = @import("std.zig");
6const math = std.math;
7const assert = std.debug.assert;
8const mem = std.mem;
9const expectFmt = std.testing.expectFmt;
10const testing = std.testing;
11const Allocator = std.mem.Allocator;
12const Writer = std.Io.Writer;
13
14pub const float = @import("fmt/float.zig");
15
16pub const default_max_depth = 3;
17
18pub const Alignment = enum {
19 left,
20 center,
21 right,
22};
23
24pub const Case = enum { lower, upper };
25
26const default_alignment = .right;
27const default_fill_char = ' ';
28
29pub const Options = struct {
30 precision: ?usize = null,
31 width: ?usize = null,
32 alignment: Alignment = default_alignment,
33 fill: u8 = default_fill_char,
34
35 pub fn toNumber(o: Options, mode: Number.Mode, case: Case) Number {
36 return .{
37 .mode = mode,
38 .case = case,
39 .precision = o.precision,
40 .width = o.width,
41 .alignment = o.alignment,
42 .fill = o.fill,
43 };
44 }
45};
46
47pub const Number = struct {
48 mode: Mode = .decimal,
49 /// Affects hex digits as well as floating point "inf"/"INF".
50 case: Case = .lower,
51 precision: ?usize = null,
52 width: ?usize = null,
53 alignment: Alignment = default_alignment,
54 fill: u8 = default_fill_char,
55
56 pub const Mode = enum {
57 decimal,
58 binary,
59 octal,
60 hex,
61 scientific,
62
63 pub fn base(mode: Mode) ?u8 {
64 return switch (mode) {
65 .decimal => 10,
66 .binary => 2,
67 .octal => 8,
68 .hex => 16,
69 .scientific => null,
70 };
71 }
72 };
73};
74
75pub const Placeholder = struct {
76 specifier_arg: []const u8,
77 fill: u8,
78 alignment: Alignment,
79 arg: Specifier,
80 width: Specifier,
81 precision: Specifier,
82
83 pub fn parse(comptime bytes: []const u8) Placeholder {
84 var parser: Parser = .{ .bytes = bytes, .i = 0 };
85 const arg = parser.specifier() catch |err| @compileError(@errorName(err));
86 const specifier_arg = parser.until(':');
87 if (parser.char()) |b| {
88 if (b != ':') @compileError("expected : or }, found '" ++ &[1]u8{b} ++ "'");
89 }
90
91 // Parse the fill byte, if present.
92 //
93 // When the width field is also specified, the fill byte must
94 // be followed by an alignment specifier, unless it's '0' (zero)
95 // (in which case it's handled as part of the width specifier).
96 var fill: ?u8 = if (parser.peek(1)) |b|
97 switch (b) {
98 '<', '^', '>' => parser.char(),
99 else => null,
100 }
101 else
102 null;
103
104 // Parse the alignment parameter
105 const alignment: ?Alignment = if (parser.peek(0)) |b| init: {
106 switch (b) {
107 '<', '^', '>' => {
108 // consume the character
109 break :init switch (parser.char().?) {
110 '<' => .left,
111 '^' => .center,
112 else => .right,
113 };
114 },
115 else => break :init null,
116 }
117 } else null;
118
119 // When none of the fill character and the alignment specifier have
120 // been provided, check whether the width starts with a zero.
121 if (fill == null and alignment == null) {
122 fill = if (parser.peek(0) == '0') '0' else null;
123 }
124
125 // Parse the width parameter
126 const width = parser.specifier() catch |err| @compileError(@errorName(err));
127
128 // Skip the dot, if present
129 if (parser.char()) |b| {
130 if (b != '.') @compileError("expected . or }, found '" ++ &[1]u8{b} ++ "'");
131 }
132
133 // Parse the precision parameter
134 const precision = parser.specifier() catch |err| @compileError(@errorName(err));
135
136 if (parser.char()) |b| @compileError("extraneous trailing character '" ++ &[1]u8{b} ++ "'");
137
138 const specifier_array = specifier_arg[0..specifier_arg.len].*;
139
140 return .{
141 .specifier_arg = &specifier_array,
142 .fill = fill orelse default_fill_char,
143 .alignment = alignment orelse default_alignment,
144 .arg = arg,
145 .width = width,
146 .precision = precision,
147 };
148 }
149};
150
151pub const Specifier = union(enum) {
152 none,
153 number: usize,
154 named: []const u8,
155};
156
157/// A stream based parser for format strings.
158///
159/// Allows to implement formatters compatible with std.fmt without replicating
160/// the standard library behavior.
161pub const Parser = struct {
162 bytes: []const u8,
163 i: usize,
164
165 pub fn number(self: *@This()) ?usize {
166 var r: ?usize = null;
167 while (self.peek(0)) |byte| {
168 switch (byte) {
169 '0'...'9' => {
170 if (r == null) r = 0;
171 r.? *= 10;
172 r.? += byte - '0';
173 },
174 else => break,
175 }
176 self.i += 1;
177 }
178 return r;
179 }
180
181 pub fn until(self: *@This(), delimiter: u8) []const u8 {
182 const start = self.i;
183 self.i = std.mem.findScalarPos(u8, self.bytes, self.i, delimiter) orelse self.bytes.len;
184 return self.bytes[start..self.i];
185 }
186
187 pub fn char(self: *@This()) ?u8 {
188 const i = self.i;
189 if (self.bytes.len - i == 0) return null;
190 self.i = i + 1;
191 return self.bytes[i];
192 }
193
194 pub fn maybe(self: *@This(), byte: u8) bool {
195 if (self.peek(0) == byte) {
196 self.i += 1;
197 return true;
198 }
199 return false;
200 }
201
202 pub fn specifier(self: *@This()) !Specifier {
203 if (self.maybe('[')) {
204 const arg_name = self.until(']');
205 if (!self.maybe(']')) return error.@"Expected closing ]";
206 return .{ .named = arg_name };
207 }
208 if (self.number()) |i| return .{ .number = i };
209 return .{ .none = {} };
210 }
211
212 pub fn peek(self: *@This(), i: usize) ?u8 {
213 const peek_index = self.i + i;
214 if (peek_index >= self.bytes.len) return null;
215 return self.bytes[peek_index];
216 }
217};
218
219pub const ArgSetType = u32;
220
221pub const ArgState = struct {
222 next_arg: usize = 0,
223 used_args: ArgSetType = 0,
224 args_len: usize,
225
226 pub fn hasUnusedArgs(self: *@This()) bool {
227 return @popCount(self.used_args) != self.args_len;
228 }
229
230 pub fn nextArg(self: *@This(), arg_index: ?usize) ?usize {
231 const next_index = arg_index orelse init: {
232 const arg = self.next_arg;
233 self.next_arg += 1;
234 break :init arg;
235 };
236
237 if (next_index >= self.args_len) {
238 return null;
239 }
240
241 // Mark this argument as used
242 self.used_args |= @as(ArgSetType, 1) << @as(u5, @intCast(next_index));
243 return next_index;
244 }
245};
246
247/// Asserts the rendered integer value fits in `buffer`.
248/// Returns the end index within `buffer`.
249pub fn printInt(buffer: []u8, value: anytype, base: u8, case: Case, options: Options) usize {
250 var w: Writer = .fixed(buffer);
251 w.printInt(value, base, case, options) catch unreachable;
252 return w.end;
253}
254
255test printInt {
256 const x: i32 = -3;
257 var buffer: [64]u8 = undefined;
258 const s = buffer[0..printInt(&buffer, x, 10, .lower, .{})];
259 try testing.expectEqualStrings("-3", s);
260}
261
262/// Converts values in the range [0, 100) to a base 10 string.
263pub fn digits2(value: u8) [2]u8 {
264 if (builtin.mode == .small) {
265 return .{ @intCast('0' + value / 10), @intCast('0' + value % 10) };
266 } else {
267 return "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"[value * 2 ..][0..2].*;
268 }
269}
270
271/// Creates a type suitable for instantiating and passing to a "{f}" placeholder.
272pub fn Alt(
273 comptime Data: type,
274 comptime formatFn: fn (data: Data, writer: *Writer) Writer.Error!void,
275) type {
276 return struct {
277 data: Data,
278 pub inline fn format(self: @This(), writer: *Writer) Writer.Error!void {
279 try formatFn(self.data, writer);
280 }
281 };
282}
283
284/// Helper for calling alternate format methods besides one named "format".
285pub fn alt(
286 context: anytype,
287 comptime func_name: @EnumLiteral(),
288) Alt(@TypeOf(context), @field(@TypeOf(context), @tagName(func_name))) {
289 return .{ .data = context };
290}
291
292test alt {
293 const Example = struct {
294 number: u8,
295
296 pub fn other(ex: @This(), w: *Writer) Writer.Error!void {
297 try w.writeByte(ex.number);
298 }
299 };
300 const ex: Example = .{ .number = 'a' };
301 try expectFmt("a", "{f}", .{alt(ex, .other)});
302}
303
304pub const ParseIntError = error{
305 /// The result cannot fit in the type specified.
306 Overflow,
307 /// The input was empty or contained an invalid character.
308 InvalidCharacter,
309};
310
311/// Parses the string `buf` as signed or unsigned representation in the
312/// specified base of an integral value of type `T`.
313///
314/// When `base` is zero the string prefix is examined to detect the true base:
315/// * A prefix of "0b" implies base=2,
316/// * A prefix of "0o" implies base=8,
317/// * A prefix of "0x" implies base=16,
318/// * Otherwise base=10 is assumed.
319///
320/// Ignores '_' character in `buf`.
321/// See also `parseUnsigned`.
322pub fn parseInt(comptime T: type, buf: []const u8, base: u8) ParseIntError!T {
323 return parseIntWithGenericCharacter(T, u8, buf, base);
324}
325
326/// Like `parseInt`, but with a generic `Character` type.
327pub fn parseIntWithGenericCharacter(
328 comptime Result: type,
329 comptime Character: type,
330 buf: []const Character,
331 base: u8,
332) ParseIntError!Result {
333 if (buf.len == 0) return error.InvalidCharacter;
334 if (buf[0] == '+') return parseIntWithSign(Result, Character, buf[1..], base, .pos);
335 if (buf[0] == '-') return parseIntWithSign(Result, Character, buf[1..], base, .neg);
336 return parseIntWithSign(Result, Character, buf, base, .pos);
337}
338
339test parseInt {
340 try testing.expectEqual(-10, try parseInt(i32, "-10", 10));
341 try testing.expectEqual(10, try parseInt(i32, "+10", 10));
342 try testing.expectEqual(10, try parseInt(u32, "+10", 10));
343 try testing.expectError(error.Overflow, parseInt(u32, "-10", 10));
344 try testing.expectError(error.InvalidCharacter, parseInt(u32, " 10", 10));
345 try testing.expectError(error.InvalidCharacter, parseInt(u32, "10 ", 10));
346 try testing.expectError(error.InvalidCharacter, parseInt(u32, "_10_", 10));
347 try testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10_", 10));
348 try testing.expectError(error.InvalidCharacter, parseInt(u32, "0x10_", 10));
349 try testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10", 10));
350 try testing.expectEqual(255, try parseInt(u8, "255", 10));
351 try testing.expectError(error.Overflow, parseInt(u8, "256", 10));
352
353 // +0 and -0 should work for unsigned
354 try testing.expectEqual(0, try parseInt(u8, "-0", 10));
355 try testing.expectEqual(0, try parseInt(u8, "+0", 10));
356
357 // ensure minInt is parsed correctly
358 try testing.expectEqual(math.minInt(i1), try parseInt(i1, "-1", 10));
359 try testing.expectEqual(math.minInt(i8), try parseInt(i8, "-128", 10));
360 try testing.expectEqual(math.minInt(i43), try parseInt(i43, "-4398046511104", 10));
361
362 // empty string or bare +- is invalid
363 try testing.expectError(error.InvalidCharacter, parseInt(u32, "", 10));
364 try testing.expectError(error.InvalidCharacter, parseInt(i32, "", 10));
365 try testing.expectError(error.InvalidCharacter, parseInt(u32, "+", 10));
366 try testing.expectError(error.InvalidCharacter, parseInt(i32, "+", 10));
367 try testing.expectError(error.InvalidCharacter, parseInt(u32, "-", 10));
368 try testing.expectError(error.InvalidCharacter, parseInt(i32, "-", 10));
369
370 // autodectect the base
371 try testing.expectEqual(111, try parseInt(i32, "111", 0));
372 try testing.expectEqual(111, try parseInt(i32, "1_1_1", 0));
373 try testing.expectEqual(111, try parseInt(i32, "1_1_1", 0));
374 try testing.expectEqual(7, try parseInt(i32, "+0b111", 0));
375 try testing.expectEqual(7, try parseInt(i32, "+0B111", 0));
376 try testing.expectEqual(7, try parseInt(i32, "+0b1_11", 0));
377 try testing.expectEqual(73, try parseInt(i32, "+0o111", 0));
378 try testing.expectEqual(73, try parseInt(i32, "+0O111", 0));
379 try testing.expectEqual(73, try parseInt(i32, "+0o11_1", 0));
380 try testing.expectEqual(273, try parseInt(i32, "+0x111", 0));
381 try testing.expectEqual(-7, try parseInt(i32, "-0b111", 0));
382 try testing.expectEqual(-7, try parseInt(i32, "-0b11_1", 0));
383 try testing.expectEqual(-73, try parseInt(i32, "-0o111", 0));
384 try testing.expectEqual(-273, try parseInt(i32, "-0x111", 0));
385 try testing.expectEqual(-273, try parseInt(i32, "-0X111", 0));
386 try testing.expectEqual(-273, try parseInt(i32, "-0x1_11", 0));
387
388 // bare binary/octal/decimal prefix is invalid
389 try testing.expectError(error.InvalidCharacter, parseInt(u32, "0b", 0));
390 try testing.expectError(error.InvalidCharacter, parseInt(u32, "0o", 0));
391 try testing.expectError(error.InvalidCharacter, parseInt(u32, "0x", 0));
392
393 // edge cases which previously errored due to base overflowing T
394 try testing.expectEqual(@as(i2, -2), try std.fmt.parseInt(i2, "-10", 2));
395 try testing.expectEqual(@as(i4, -8), try std.fmt.parseInt(i4, "-10", 8));
396 try testing.expectEqual(@as(i5, -16), try std.fmt.parseInt(i5, "-10", 16));
397}
398
399fn parseIntWithSign(
400 comptime Result: type,
401 comptime Character: type,
402 buf: []const Character,
403 base: u8,
404 comptime sign: enum { pos, neg },
405) ParseIntError!Result {
406 if (buf.len == 0) return error.InvalidCharacter;
407
408 var buf_base = base;
409 var buf_start = buf;
410 if (base == 0) {
411 // Treat is as a decimal number by default.
412 buf_base = 10;
413 // Detect the base by looking at buf prefix.
414 if (buf.len > 2 and buf[0] == '0') {
415 if (math.cast(u8, buf[1])) |c| switch (std.ascii.toLower(c)) {
416 'b' => {
417 buf_base = 2;
418 buf_start = buf[2..];
419 },
420 'o' => {
421 buf_base = 8;
422 buf_start = buf[2..];
423 },
424 'x' => {
425 buf_base = 16;
426 buf_start = buf[2..];
427 },
428 else => {},
429 };
430 }
431 }
432
433 const add = switch (sign) {
434 .pos => math.add,
435 .neg => math.sub,
436 };
437
438 // accumulate into Accumulate which is always 8 bits or larger. this prevents
439 // `buf_base` from overflowing Result.
440 const info = @typeInfo(Result);
441 const Accumulate = @Int(info.int.signedness, @max(8, info.int.bits));
442 var accumulate: Accumulate = 0;
443
444 if (buf_start[0] == '_' or buf_start[buf_start.len - 1] == '_') return error.InvalidCharacter;
445
446 for (buf_start) |c| {
447 if (c == '_') continue;
448 const digit = try charToDigit(math.cast(u8, c) orelse return error.InvalidCharacter, buf_base);
449 if (accumulate != 0) {
450 accumulate = try math.mul(Accumulate, accumulate, math.cast(Accumulate, buf_base) orelse return error.Overflow);
451 } else if (sign == .neg) {
452 // The first digit of a negative number.
453 // Consider parsing "-4" as an i3.
454 // This should work, but positive 4 overflows i3, so we can't cast the digit to T and subtract.
455 accumulate = math.cast(Accumulate, -@as(i8, @intCast(digit))) orelse return error.Overflow;
456 continue;
457 }
458 accumulate = try add(Accumulate, accumulate, math.cast(Accumulate, digit) orelse return error.Overflow);
459 }
460
461 return if (Result == Accumulate)
462 accumulate
463 else
464 math.cast(Result, accumulate) orelse return error.Overflow;
465}
466
467/// Parses the string `buf` as unsigned representation in the specified base
468/// of an integral value of type `T`.
469///
470/// When `base` is zero the string prefix is examined to detect the true base:
471/// * A prefix of "0b" implies base=2,
472/// * A prefix of "0o" implies base=8,
473/// * A prefix of "0x" implies base=16,
474/// * Otherwise base=10 is assumed.
475///
476/// Ignores '_' character in `buf`.
477/// See also `parseInt`.
478pub fn parseUnsigned(comptime T: type, buf: []const u8, base: u8) ParseIntError!T {
479 return parseIntWithSign(T, u8, buf, base, .pos);
480}
481
482test parseUnsigned {
483 try testing.expectEqual(50124, try parseUnsigned(u16, "050124", 10));
484 try testing.expectEqual(65535, try parseUnsigned(u16, "65535", 10));
485 try testing.expectEqual(65535, try parseUnsigned(u16, "65_535", 10));
486 try testing.expectError(error.Overflow, parseUnsigned(u16, "65536", 10));
487
488 try testing.expectEqual(0xffffffffffffffff, try parseUnsigned(u64, "0ffffffffffffffff", 16));
489 try testing.expectEqual(0xffffffffffffffff, try parseUnsigned(u64, "0f_fff_fff_fff_fff_fff", 16));
490 try testing.expectError(error.Overflow, parseUnsigned(u64, "10000000000000000", 16));
491
492 try testing.expectEqual(0xDEADBEEF, try parseUnsigned(u32, "DeadBeef", 16));
493
494 try testing.expectEqual(1, try parseUnsigned(u7, "1", 10));
495 try testing.expectEqual(8, try parseUnsigned(u7, "1000", 2));
496
497 try testing.expectError(error.InvalidCharacter, parseUnsigned(u32, "f", 10));
498 try testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "109", 8));
499
500 try testing.expectEqual(1442151747, try parseUnsigned(u32, "NUMBER", 36));
501
502 // these numbers should fit even though the base itself doesn't fit in the destination type
503 try testing.expectEqual(0, try parseUnsigned(u1, "0", 10));
504 try testing.expectEqual(1, try parseUnsigned(u1, "1", 10));
505 try testing.expectError(error.Overflow, parseUnsigned(u1, "2", 10));
506 try testing.expectEqual(1, try parseUnsigned(u1, "001", 16));
507 try testing.expectEqual(3, try parseUnsigned(u2, "3", 16));
508 try testing.expectError(error.Overflow, parseUnsigned(u2, "4", 16));
509
510 // parseUnsigned does not expect a sign
511 try testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "+0", 10));
512 try testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "-0", 10));
513
514 // test empty string error
515 try testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "", 10));
516}
517
518/// Parses a number like '2G', '2Gi', or '2GiB'.
519pub fn parseIntSizeSuffix(buf: []const u8, digit_base: u8) ParseIntError!usize {
520 var without_B = buf;
521 if (mem.endsWith(u8, buf, "B")) without_B.len -= 1;
522 var without_i = without_B;
523 var magnitude_base: usize = 1000;
524 if (mem.endsWith(u8, without_B, "i")) {
525 without_i.len -= 1;
526 magnitude_base = 1024;
527 }
528 if (without_i.len == 0) return error.InvalidCharacter;
529 const orders_of_magnitude: usize = switch (without_i[without_i.len - 1]) {
530 'k', 'K' => 1,
531 'M' => 2,
532 'G' => 3,
533 'T' => 4,
534 'P' => 5,
535 'E' => 6,
536 'Z' => 7,
537 'Y' => 8,
538 'R' => 9,
539 'Q' => 10,
540 else => 0,
541 };
542 var without_suffix = without_i;
543 if (orders_of_magnitude > 0) {
544 without_suffix.len -= 1;
545 } else if (without_i.len != without_B.len) {
546 return error.InvalidCharacter;
547 }
548 const multiplier = math.powi(usize, magnitude_base, orders_of_magnitude) catch |err| switch (err) {
549 error.Underflow => unreachable,
550 error.Overflow => |e| return e,
551 };
552 const number = try std.fmt.parseInt(usize, without_suffix, digit_base);
553 return math.mul(usize, number, multiplier);
554}
555
556test parseIntSizeSuffix {
557 try testing.expectEqual(2, try parseIntSizeSuffix("2", 10));
558 try testing.expectEqual(2, try parseIntSizeSuffix("2B", 10));
559 try testing.expectEqual(2000, try parseIntSizeSuffix("2kB", 10));
560 try testing.expectEqual(2000, try parseIntSizeSuffix("2k", 10));
561 try testing.expectEqual(2048, try parseIntSizeSuffix("2KiB", 10));
562 try testing.expectEqual(2048, try parseIntSizeSuffix("2Ki", 10));
563 try testing.expectEqual(10240, try parseIntSizeSuffix("aKiB", 16));
564 try testing.expectError(error.InvalidCharacter, parseIntSizeSuffix("", 10));
565 try testing.expectError(error.InvalidCharacter, parseIntSizeSuffix("2iB", 10));
566}
567
568pub const parseFloat = @import("fmt/parse_float.zig").parseFloat;
569pub const ParseFloatError = @import("fmt/parse_float.zig").ParseFloatError;
570
571test {
572 _ = &parseFloat;
573}
574
575pub fn charToDigit(c: u8, base: u8) (error{InvalidCharacter}!u8) {
576 const value = switch (c) {
577 '0'...'9' => c - '0',
578 'A'...'Z' => c - 'A' + 10,
579 'a'...'z' => c - 'a' + 10,
580 else => return error.InvalidCharacter,
581 };
582
583 if (value >= base) return error.InvalidCharacter;
584
585 return value;
586}
587
588pub fn digitToChar(digit: u8, case: Case) u8 {
589 return switch (digit) {
590 0...9 => digit + '0',
591 10...35 => digit + ((if (case == .upper) @as(u8, 'A') else @as(u8, 'a')) - 10),
592 else => unreachable,
593 };
594}
595
596/// Deprecated in favor of `mem.PrintError`.
597pub const BufPrintError = mem.PrintError;
598
599/// Deprecated in favor of `mem.print`.
600pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![]u8 {
601 return mem.print(buf, fmt, args);
602}
603
604/// Deprecated in favor of `mem.printSentinel`.
605pub fn bufPrintSentinel(
606 buf: []u8,
607 comptime fmt: []const u8,
608 args: anytype,
609 comptime sentinel: u8,
610) BufPrintError![:sentinel]u8 {
611 return mem.printSentinel(buf, fmt, args, sentinel);
612}
613
614/// Count the characters needed for format.
615pub fn count(comptime fmt: []const u8, args: anytype) usize {
616 var trash_buffer: [64]u8 = undefined;
617 var dw: Writer.Discarding = .init(&trash_buffer);
618 dw.writer.print(fmt, args) catch |err| switch (err) {
619 error.WriteFailed => unreachable,
620 };
621 return @intCast(dw.count + dw.writer.end);
622}
623
624/// Deprecated in favor of `Allocator.print`.
625pub fn allocPrint(gpa: Allocator, comptime fmt: []const u8, args: anytype) Allocator.Error![]u8 {
626 return gpa.print(fmt, args);
627}
628
629/// Deprecated in favor of `Allocator.printSentinel`.
630pub fn allocPrintSentinel(
631 gpa: Allocator,
632 comptime fmt: []const u8,
633 args: anytype,
634 comptime sentinel: u8,
635) Allocator.Error![:sentinel]u8 {
636 return gpa.printSentinel(fmt, args, sentinel);
637}
638
639pub inline fn comptimePrint(comptime fmt: []const u8, args: anytype) *const [count(fmt, args):0]u8 {
640 comptime {
641 var buf: [count(fmt, args):0]u8 = undefined;
642 _ = mem.print(&buf, fmt, args) catch unreachable;
643 buf[buf.len] = 0;
644 const final = buf;
645 return &final;
646 }
647}
648
649test comptimePrint {
650 @setEvalBranchQuota(2000);
651 try testing.expectEqual(*const [3:0]u8, @TypeOf(comptimePrint("{}", .{100})));
652 try testing.expectEqualSlices(u8, "100", comptimePrint("{}", .{100}));
653 try testing.expectEqualStrings("30", comptimePrint("{d}", .{30.0}));
654 try testing.expectEqualStrings("30.0", comptimePrint("{d:3.1}", .{30.0}));
655 try testing.expectEqualStrings("0.05", comptimePrint("{d}", .{0.05}));
656 try testing.expectEqualStrings("5e-2", comptimePrint("{e}", .{0.05}));
657}
658
659test "parse u64 digit too big" {
660 _ = parseUnsigned(u64, "123a", 10) catch |err| {
661 if (err == error.InvalidCharacter) return;
662 unreachable;
663 };
664 unreachable;
665}
666
667test "parse unsigned comptime" {
668 comptime {
669 try testing.expectEqual(2, try parseUnsigned(usize, "2", 10));
670 }
671}
672
673test "escaped braces" {
674 try expectFmt("escaped: {{foo}}\n", "escaped: {{{{foo}}}}\n", .{});
675 try expectFmt("escaped: {foo}\n", "escaped: {{foo}}\n", .{});
676}
677
678test "optional" {
679 {
680 const value: ?i32 = 1234;
681 try expectFmt("optional: 1234\n", "optional: {?}\n", .{value});
682 try expectFmt("optional: 1234\n", "optional: {?d}\n", .{value});
683 try expectFmt("optional: 4d2\n", "optional: {?x}\n", .{value});
684 }
685 {
686 const value: ?[]const u8 = "string";
687 try expectFmt("optional: string\n", "optional: {?s}\n", .{value});
688 }
689 {
690 const value: ?i32 = null;
691 try expectFmt("optional: null\n", "optional: {?}\n", .{value});
692 }
693 {
694 const value = @as(?*i32, @ptrFromInt(0xf000d000));
695 try expectFmt("optional: *i32@f000d000\n", "optional: {*}\n", .{value});
696 }
697}
698
699test "error" {
700 {
701 const value: anyerror!i32 = 1234;
702 try expectFmt("error union: 1234\n", "error union: {!}\n", .{value});
703 try expectFmt("error union: 1234\n", "error union: {!d}\n", .{value});
704 try expectFmt("error union: 4d2\n", "error union: {!x}\n", .{value});
705 }
706 {
707 const value: anyerror![]const u8 = "string";
708 try expectFmt("error union: string\n", "error union: {!s}\n", .{value});
709 }
710 {
711 const value: anyerror!i32 = error.InvalidChar;
712 try expectFmt("error union: error.InvalidChar\n", "error union: {!}\n", .{value});
713 }
714}
715
716test "int.small" {
717 {
718 const value: u3 = 0b101;
719 try expectFmt("u3: 5\n", "u3: {}\n", .{value});
720 }
721}
722
723test "int.specifier" {
724 {
725 const value: u8 = 'a';
726 try expectFmt("u8: a\n", "u8: {c}\n", .{value});
727 }
728 {
729 const value: u8 = 0b1100;
730 try expectFmt("u8: 0b1100\n", "u8: 0b{b}\n", .{value});
731 }
732 {
733 const value: u16 = 0o1234;
734 try expectFmt("u16: 0o1234\n", "u16: 0o{o}\n", .{value});
735 }
736 {
737 const value: u8 = 'a';
738 try expectFmt("UTF-8: a\n", "UTF-8: {u}\n", .{value});
739 }
740 {
741 const value: u21 = 0x1F310;
742 try expectFmt("UTF-8: 🌐\n", "UTF-8: {u}\n", .{value});
743 }
744 {
745 const value: u21 = 0xD800;
746 try expectFmt("UTF-8: �\n", "UTF-8: {u}\n", .{value});
747 }
748 {
749 const value: u21 = 0x110001;
750 try expectFmt("UTF-8: �\n", "UTF-8: {u}\n", .{value});
751 }
752}
753
754test "int.padded" {
755 try expectFmt("u8: ' 1'", "u8: '{:4}'", .{@as(u8, 1)});
756 try expectFmt("u8: '1000'", "u8: '{:0<4}'", .{@as(u8, 1)});
757 try expectFmt("u8: '0001'", "u8: '{:0>4}'", .{@as(u8, 1)});
758 try expectFmt("u8: '0100'", "u8: '{:0^4}'", .{@as(u8, 1)});
759 try expectFmt("i8: '-1 '", "i8: '{:<4}'", .{@as(i8, -1)});
760 try expectFmt("i8: ' -1'", "i8: '{:>4}'", .{@as(i8, -1)});
761 try expectFmt("i8: ' -1 '", "i8: '{:^4}'", .{@as(i8, -1)});
762 try expectFmt("i16: '-1234'", "i16: '{:4}'", .{@as(i16, -1234)});
763 try expectFmt("i16: '+1234'", "i16: '{:4}'", .{@as(i16, 1234)});
764 try expectFmt("i16: '-12345'", "i16: '{:4}'", .{@as(i16, -12345)});
765 try expectFmt("i16: '+12345'", "i16: '{:4}'", .{@as(i16, 12345)});
766 try expectFmt("u16: '12345'", "u16: '{:4}'", .{@as(u16, 12345)});
767}
768
769test "buffer" {
770 {
771 var buf1: [32]u8 = undefined;
772 var w: Writer = .fixed(&buf1);
773 try w.printValue("", .{}, 1234, std.options.fmt_max_depth);
774 try testing.expectEqualStrings("1234", w.buffered());
775
776 w = .fixed(&buf1);
777 try w.printValue("c", .{}, 'a', std.options.fmt_max_depth);
778 try testing.expectEqualStrings("a", w.buffered());
779
780 w = .fixed(&buf1);
781 try w.printValue("b", .{}, 0b1100, std.options.fmt_max_depth);
782 try testing.expectEqualStrings("1100", w.buffered());
783 }
784}
785
786// Test formatting of arrays by value, by single-item pointer, and as a slice
787fn expectArrayFmt(expected: []const u8, comptime template: []const u8, comptime array_value: anytype) !void {
788 try expectFmt(expected, template, .{array_value});
789 try expectFmt(expected, template, .{&array_value});
790 var runtime_zero: usize = 0;
791 _ = &runtime_zero;
792 try expectFmt(expected, template, .{array_value[runtime_zero..]});
793}
794
795test "array" {
796 const value: [3]u8 = "abc".*;
797 try expectArrayFmt("array: abc\n", "array: {s}\n", value);
798 try expectArrayFmt("array: 616263\n", "array: {x}\n", value);
799 try expectArrayFmt("array: { 97, 98, 99 }\n", "array: {any}\n", value);
800
801 var buf: [100]u8 = undefined;
802 try expectFmt(
803 try mem.print(buf[0..], "array: [3]u8@{x}\n", .{@intFromPtr(&value)}),
804 "array: {*}\n",
805 .{&value},
806 );
807}
808
809test "slice" {
810 {
811 const value: []const u8 = "abc";
812 try expectFmt("slice: abc\n", "slice: {s}\n", .{value});
813 try expectFmt("slice: 616263\n", "slice: {x}\n", .{value});
814 try expectFmt("slice: { 97, 98, 99 }\n", "slice: {any}\n", .{value});
815 }
816 {
817 var runtime_zero: usize = 0;
818 _ = &runtime_zero;
819 const value = @as([*]align(1) const []const u8, @ptrFromInt(0xdeadbeef))[runtime_zero..runtime_zero];
820 try expectFmt("slice: []const u8@deadbeef\n", "slice: {*}\n", .{value});
821 }
822 {
823 const null_term_slice: [:0]const u8 = "\x00hello\x00";
824 try expectFmt("buf: \x00hello\x00\n", "buf: {s}\n", .{null_term_slice});
825 }
826
827 try expectFmt("buf: Test\n Other text", "buf: {s}\n Other text", .{"Test"});
828
829 {
830 var int_slice = [_]u32{ 1, 4096, 391891, 1111111111 };
831 const input: []const u32 = &int_slice;
832 try expectFmt("int: { 1, 4096, 391891, 1111111111 }", "int: {any}", .{input});
833 }
834 {
835 const S1 = struct {
836 x: u8,
837 };
838 const struct_slice: []const S1 = &[_]S1{ S1{ .x = 8 }, S1{ .x = 42 } };
839 try expectFmt("slice: { .{ .x = 8 }, .{ .x = 42 } }", "slice: {any}", .{struct_slice});
840 }
841 {
842 const S2 = struct {
843 x: u8,
844
845 pub fn format(s: @This(), writer: *Writer) Writer.Error!void {
846 try writer.print("S2({})", .{s.x});
847 }
848 };
849 const struct_slice: []const S2 = &[_]S2{ S2{ .x = 8 }, S2{ .x = 42 } };
850 try expectFmt("slice: { .{ .x = 8 }, .{ .x = 42 } }", "slice: {any}", .{struct_slice});
851 }
852}
853
854test "pointer" {
855 {
856 const value = @as(*align(1) i32, @ptrFromInt(0xdeadbeef));
857 try expectFmt("pointer: i32@deadbeef\n", "pointer: {}\n", .{value});
858 try expectFmt("pointer: i32@deadbeef\n", "pointer: {*}\n", .{value});
859 }
860 const FnPtr = *align(1) const fn () void;
861 {
862 const value = @as(FnPtr, @ptrFromInt(0xdeadbeef));
863 try expectFmt("pointer: fn () void@deadbeef\n", "pointer: {}\n", .{value});
864 }
865 {
866 const value = @as(FnPtr, @ptrFromInt(0xdeadbeef));
867 try expectFmt("pointer: fn () void@deadbeef\n", "pointer: {}\n", .{value});
868 }
869}
870
871test "cstr" {
872 try expectFmt(
873 "cstr: Test C\n",
874 "cstr: {s}\n",
875 .{@as([*c]const u8, @ptrCast("Test C"))},
876 );
877}
878
879test "struct" {
880 {
881 const Struct = struct {
882 field: u8,
883 };
884 const value = Struct{ .field = 42 };
885 try expectFmt("struct: .{ .field = 42 }\n", "struct: {}\n", .{value});
886 try expectFmt("struct: .{ .field = 42 }\n", "struct: {}\n", .{&value});
887 }
888 {
889 const Struct = struct {
890 a: u0,
891 b: u1,
892 };
893 const value = Struct{ .a = 0, .b = 1 };
894 try expectFmt("struct: .{ .a = 0, .b = 1 }\n", "struct: {}\n", .{value});
895 }
896
897 const S = struct {
898 a: u32,
899 b: anyerror,
900 };
901
902 const inst = S{
903 .a = 456,
904 .b = error.Unused,
905 };
906
907 try expectFmt(".{ .a = 456, .b = error.Unused }", "{}", .{inst});
908 // Tuples
909 try expectFmt(".{ }", "{}", .{.{}});
910 try expectFmt(".{ -1 }", "{}", .{.{-1}});
911 try expectFmt(".{ -1, 42, 25000 }", "{}", .{.{ -1, 42, 0.25e5 }});
912}
913
914test "enum" {
915 const Enum = enum {
916 One,
917 Two,
918 };
919 const value = Enum.Two;
920 try expectFmt("enum: .Two\n", "enum: {}\n", .{value});
921 try expectFmt("enum: .Two\n", "enum: {}\n", .{&value});
922 try expectFmt("enum: .One\n", "enum: {}\n", .{Enum.One});
923 try expectFmt("enum: .Two\n", "enum: {}\n", .{Enum.Two});
924
925 // test very large enum to verify ct branch quota is large enough
926 // TODO: https://github.com/ziglang/zig/issues/15609
927 if (!((builtin.cpu.arch == .wasm32) and builtin.mode == .debug)) {
928 try expectFmt("enum: .INVALID_FUNCTION\n", "enum: {}\n", .{std.os.windows.Win32Error.INVALID_FUNCTION});
929 }
930
931 const E = enum {
932 One,
933 Two,
934 Three,
935 };
936
937 const inst = E.Two;
938
939 try expectFmt(".Two", "{}", .{inst});
940}
941
942test "non-exhaustive enum" {
943 const Enum = enum(u16) {
944 One = 0x000f,
945 Two = 0xbeef,
946 _,
947 };
948 try expectFmt("enum: .One\n", "enum: {}\n", .{Enum.One});
949 try expectFmt("enum: .Two\n", "enum: {}\n", .{Enum.Two});
950 try expectFmt("enum: @enumFromInt(4660)\n", "enum: {}\n", .{@as(Enum, @fromBackingInt(@intCast(0x1234)))});
951 try expectFmt("enum: f\n", "enum: {x}\n", .{Enum.One});
952 try expectFmt("enum: beef\n", "enum: {x}\n", .{Enum.Two});
953 try expectFmt("enum: BEEF\n", "enum: {X}\n", .{Enum.Two});
954 try expectFmt("enum: 1234\n", "enum: {x}\n", .{@as(Enum, @fromBackingInt(@intCast(0x1234)))});
955
956 try expectFmt("enum: 15\n", "enum: {d}\n", .{Enum.One});
957 try expectFmt("enum: 48879\n", "enum: {d}\n", .{Enum.Two});
958 try expectFmt("enum: 4660\n", "enum: {d}\n", .{@as(Enum, @fromBackingInt(@intCast(0x1234)))});
959}
960
961test "float.scientific" {
962 try expectFmt("f32: 1.34e0", "f32: {e}", .{@as(f32, 1.34)});
963 try expectFmt("f32: 1.234e1", "f32: {e}", .{@as(f32, 12.34)});
964 try expectFmt("f64: -1.234e11", "f64: {e}", .{@as(f64, -12.34e10)});
965 try expectFmt("f64: 9.99996e-40", "f64: {e}", .{@as(f64, 9.999960e-40)});
966}
967
968test "float.scientific.precision" {
969 try expectFmt("f64: 1.40971e-42", "f64: {e:.5}", .{@as(f64, 1.409706e-42)});
970 try expectFmt("f64: 1.00000e-9", "f64: {e:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 814313563))))});
971 try expectFmt("f64: 7.81250e-3", "f64: {e:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1006632960))))});
972 // libc rounds 1.000005e5 to 1.00000e5 but zig does 1.00001e5.
973 // In fact, libc doesn't round a lot of 5 cases up when one past the precision point.
974 try expectFmt("f64: 1.00001e5", "f64: {e:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1203982400))))});
975}
976
977test "float.special" {
978 try expectFmt("f64: nan", "f64: {}", .{math.nan(f64)});
979 // negative nan is not defined by IEE 754,
980 // and ARM thus normalizes it to positive nan
981 if (builtin.target.cpu.arch != .arm) {
982 try expectFmt("f64: -nan", "f64: {}", .{-math.nan(f64)});
983 }
984 try expectFmt("f64: inf", "f64: {}", .{math.inf(f64)});
985 try expectFmt("f64: -inf", "f64: {}", .{-math.inf(f64)});
986}
987
988test "float.hexadecimal.special" {
989 try expectFmt("f64: nan", "f64: {x}", .{math.nan(f64)});
990 // negative nan is not defined by IEE 754,
991 // and ARM thus normalizes it to positive nan
992 if (builtin.target.cpu.arch != .arm) {
993 try expectFmt("f64: -nan", "f64: {x}", .{-math.nan(f64)});
994 }
995 try expectFmt("f64: inf", "f64: {x}", .{math.inf(f64)});
996 try expectFmt("f64: -inf", "f64: {x}", .{-math.inf(f64)});
997
998 try expectFmt("f64: 0x0.0p0", "f64: {x}", .{@as(f64, 0)});
999 try expectFmt("f64: -0x0.0p0", "f64: {x}", .{-@as(f64, 0)});
1000}
1001
1002test "float.hexadecimal" {
1003 try expectFmt("f16: 0x1.554p-2", "f16: {x}", .{@as(f16, 1.0 / 3.0)});
1004 try expectFmt("f32: 0x1.555556p-2", "f32: {x}", .{@as(f32, 1.0 / 3.0)});
1005 try expectFmt("f64: 0x1.5555555555555p-2", "f64: {x}", .{@as(f64, 1.0 / 3.0)});
1006 try expectFmt("f80: 0x1.5555555555555556p-2", "f80: {x}", .{@as(f80, 1.0 / 3.0)});
1007 try expectFmt("f128: 0x1.5555555555555555555555555555p-2", "f128: {x}", .{@as(f128, 1.0 / 3.0)});
1008
1009 try expectFmt("f16: 0x1p-14", "f16: {x}", .{math.floatMin(f16)});
1010 try expectFmt("f32: 0x1p-126", "f32: {x}", .{math.floatMin(f32)});
1011 try expectFmt("f64: 0x1p-1022", "f64: {x}", .{math.floatMin(f64)});
1012 try expectFmt("f80: 0x1p-16382", "f80: {x}", .{math.floatMin(f80)});
1013 try expectFmt("f128: 0x1p-16382", "f128: {x}", .{math.floatMin(f128)});
1014
1015 try expectFmt("f16: 0x0.004p-14", "f16: {x}", .{math.floatTrueMin(f16)});
1016 try expectFmt("f32: 0x0.000002p-126", "f32: {x}", .{math.floatTrueMin(f32)});
1017 try expectFmt("f64: 0x0.0000000000001p-1022", "f64: {x}", .{math.floatTrueMin(f64)});
1018 try expectFmt("f80: 0x0.0000000000000002p-16382", "f80: {x}", .{math.floatTrueMin(f80)});
1019 try expectFmt("f128: 0x0.0000000000000000000000000001p-16382", "f128: {x}", .{math.floatTrueMin(f128)});
1020
1021 try expectFmt("f16: 0x1.ffcp15", "f16: {x}", .{math.floatMax(f16)});
1022 try expectFmt("f32: 0x1.fffffep127", "f32: {x}", .{math.floatMax(f32)});
1023 try expectFmt("f64: 0x1.fffffffffffffp1023", "f64: {x}", .{math.floatMax(f64)});
1024 try expectFmt("f80: 0x1.fffffffffffffffep16383", "f80: {x}", .{math.floatMax(f80)});
1025 try expectFmt("f128: 0x1.ffffffffffffffffffffffffffffp16383", "f128: {x}", .{math.floatMax(f128)});
1026}
1027
1028test "float.hexadecimal.precision" {
1029 try expectFmt("f16: 0x1.5p-2", "f16: {x:.1}", .{@as(f16, 1.0 / 3.0)});
1030 try expectFmt("f32: 0x1.555p-2", "f32: {x:.3}", .{@as(f32, 1.0 / 3.0)});
1031 try expectFmt("f64: 0x1.55555p-2", "f64: {x:.5}", .{@as(f64, 1.0 / 3.0)});
1032 try expectFmt("f80: 0x1.5555555p-2", "f80: {x:.7}", .{@as(f80, 1.0 / 3.0)});
1033 try expectFmt("f128: 0x1.555555555p-2", "f128: {x:.9}", .{@as(f128, 1.0 / 3.0)});
1034
1035 try expectFmt("f16: 0x1.00000p0", "f16: {x:.5}", .{@as(f16, 1.0)});
1036 try expectFmt("f32: 0x1.00000p0", "f32: {x:.5}", .{@as(f32, 1.0)});
1037 try expectFmt("f64: 0x1.00000p0", "f64: {x:.5}", .{@as(f64, 1.0)});
1038 try expectFmt("f80: 0x1.00000p0", "f80: {x:.5}", .{@as(f80, 1.0)});
1039 try expectFmt("f128: 0x1.00000p0", "f128: {x:.5}", .{@as(f128, 1.0)});
1040}
1041
1042test "float.decimal" {
1043 try expectFmt("f64: 152314000000000000000000000000", "f64: {d}", .{@as(f64, 1.52314e29)});
1044 try expectFmt("f32: 0", "f32: {d}", .{@as(f32, 0.0)});
1045 try expectFmt("f32: 0", "f32: {d:.0}", .{@as(f32, 0.0)});
1046 try expectFmt("f32: 1.1", "f32: {d:.1}", .{@as(f32, 1.1234)});
1047 try expectFmt("f32: 1234.57", "f32: {d:.2}", .{@as(f32, 1234.567)});
1048 // -11.1234 is converted to f64 -11.12339... internally (errol3() function takes f64).
1049 // -11.12339... is rounded back up to -11.1234
1050 try expectFmt("f32: -11.1234", "f32: {d:.4}", .{@as(f32, -11.1234)});
1051 try expectFmt("f32: 91.12345", "f32: {d:.5}", .{@as(f32, 91.12345)});
1052 try expectFmt("f64: 91.1234567890", "f64: {d:.10}", .{@as(f64, 91.12345678901235)});
1053 try expectFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 0.0)});
1054 try expectFmt("f64: 6", "f64: {d:.0}", .{@as(f64, 5.700)});
1055 try expectFmt("f64: 10.0", "f64: {d:.1}", .{@as(f64, 9.999)});
1056 try expectFmt("f64: 1.000", "f64: {d:.3}", .{@as(f64, 1.0)});
1057 try expectFmt("f64: 0.00030000", "f64: {d:.8}", .{@as(f64, 0.0003)});
1058 try expectFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 1.40130e-45)});
1059 try expectFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 9.999960e-40)});
1060 try expectFmt("f64: 10000000000000.00", "f64: {d:.2}", .{@as(f64, 9999999999999.999)});
1061 try expectFmt("f64: 10000000000000000000000000000000000000", "f64: {d}", .{@as(f64, 1e37)});
1062 try expectFmt("f64: 100000000000000000000000000000000000000", "f64: {d}", .{@as(f64, 1e38)});
1063}
1064
1065test "float.libc.sanity" {
1066 try expectFmt("f64: 0.00001", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 916964781))))});
1067 try expectFmt("f64: 0.00001", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 925353389))))});
1068 try expectFmt("f64: 0.10000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1036831278))))});
1069 try expectFmt("f64: 1.00000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1065353133))))});
1070 try expectFmt("f64: 10.00000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1092616192))))});
1071
1072 // libc differences
1073 //
1074 // This is 0.015625 exactly according to gdb. We thus round down,
1075 // however glibc rounds up for some reason. This occurs for all
1076 // floats of the form x.yyyy25 on a precision point.
1077 try expectFmt("f64: 0.01563", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1015021568))))});
1078 // errol3 rounds to ... 630 but libc rounds to ...632. Grisu3
1079 // also rounds to 630 so I'm inclined to believe libc is not
1080 // optimal here.
1081 try expectFmt("f64: 18014400656965630.00000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1518338049))))});
1082}
1083
1084test "union" {
1085 const TU = union(enum) {
1086 float: f32,
1087 int: u32,
1088 };
1089
1090 const UU = union {
1091 float: f32,
1092 int: u32,
1093 };
1094
1095 const EU = extern union {
1096 float: f32,
1097 int: u32,
1098 };
1099
1100 const tu_inst: TU = .{ .int = 123 };
1101 const uu_inst: UU = .{ .int = 456 };
1102 const eu_inst: EU = .{ .float = 321.123 };
1103
1104 try expectFmt(".{ .int = 123 }", "{}", .{tu_inst});
1105 try expectFmt(".{ ... }", "{}", .{uu_inst});
1106 try expectFmt(".{ .float = 321.123, .int = 1134596030 }", "{}", .{eu_inst});
1107}
1108
1109test "struct.self-referential" {
1110 const S = struct {
1111 const SelfType = @This();
1112 a: ?*SelfType,
1113 };
1114
1115 var inst = S{
1116 .a = null,
1117 };
1118 inst.a = &inst;
1119
1120 try expectFmt(".{ .a = .{ .a = .{ .a = .{ ... } } } }", "{}", .{inst});
1121}
1122
1123test "struct.zero-size" {
1124 const A = struct {
1125 fn foo() void {}
1126 };
1127 const B = struct {
1128 a: A,
1129 c: i32,
1130 };
1131
1132 const a = A{};
1133 const b = B{ .a = a, .c = 0 };
1134
1135 try expectFmt(".{ .a = .{ }, .c = 0 }", "{}", .{b});
1136}
1137
1138/// Encodes a sequence of bytes as hexadecimal digits.
1139/// Returns an array containing the encoded bytes.
1140pub fn bytesToHex(input: anytype, case: Case) [input.len * 2]u8 {
1141 if (input.len == 0) return [_]u8{};
1142 comptime assert(@TypeOf(input[0]) == u8); // elements to encode must be unsigned bytes
1143
1144 const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef";
1145 var result: [input.len * 2]u8 = undefined;
1146 for (input, 0..) |b, i| {
1147 result[i * 2 + 0] = charset[b >> 4];
1148 result[i * 2 + 1] = charset[b & 15];
1149 }
1150 return result;
1151}
1152
1153/// Decodes the sequence of bytes represented by the specified string of
1154/// hexadecimal characters.
1155/// Returns a slice of the output buffer containing the decoded bytes.
1156pub fn hexToBytes(out: []u8, input: []const u8) ![]u8 {
1157 // Expect 0 or n pairs of hexadecimal digits.
1158 if (input.len & 1 != 0)
1159 return error.InvalidLength;
1160 if (out.len * 2 < input.len)
1161 return error.NoSpaceLeft;
1162
1163 var in_i: usize = 0;
1164 while (in_i < input.len) : (in_i += 2) {
1165 const hi = try charToDigit(input[in_i], 16);
1166 const lo = try charToDigit(input[in_i + 1], 16);
1167 out[in_i / 2] = (hi << 4) | lo;
1168 }
1169
1170 return out[0 .. in_i / 2];
1171}
1172
1173test bytesToHex {
1174 const input = "input slice";
1175 const encoded = bytesToHex(input, .lower);
1176 var decoded: [input.len]u8 = undefined;
1177 try testing.expectEqualSlices(u8, input, try hexToBytes(&decoded, &encoded));
1178}
1179
1180test hexToBytes {
1181 const repeated: []const u8 = repeated: {
1182 const buf: [32][2]u8 = @splat("90".*);
1183 break :repeated @ptrCast(&buf);
1184 };
1185 var buf: [32]u8 = undefined;
1186 try expectFmt(repeated, "{X}", .{try hexToBytes(&buf, repeated)});
1187 try expectFmt("ABCD", "{X}", .{try hexToBytes(&buf, "ABCD")});
1188 try expectFmt("", "{X}", .{try hexToBytes(&buf, "")});
1189 try testing.expectError(error.InvalidCharacter, hexToBytes(&buf, "012Z"));
1190 try testing.expectError(error.InvalidLength, hexToBytes(&buf, "AAA"));
1191 try testing.expectError(error.NoSpaceLeft, hexToBytes(buf[0..1], "ABAB"));
1192}
1193
1194test "positional" {
1195 try expectFmt("2 1 0", "{2} {1} {0}", .{ @as(usize, 0), @as(usize, 1), @as(usize, 2) });
1196 try expectFmt("2 1 0", "{2} {1} {}", .{ @as(usize, 0), @as(usize, 1), @as(usize, 2) });
1197 try expectFmt("0 0", "{0} {0}", .{@as(usize, 0)});
1198 try expectFmt("0 1", "{} {1}", .{ @as(usize, 0), @as(usize, 1) });
1199 try expectFmt("1 0 0 1", "{1} {} {0} {}", .{ @as(usize, 0), @as(usize, 1) });
1200}
1201
1202test "positional with specifier" {
1203 try expectFmt("10.0", "{0d:.1}", .{@as(f64, 9.999)});
1204}
1205
1206test "positional/alignment/width/precision" {
1207 try expectFmt("10.0", "{0d: >3.1}", .{@as(f64, 9.999)});
1208}
1209
1210test "vector" {
1211 const vbool: @Vector(4, bool) = [_]bool{ true, false, true, false };
1212 const vi64: @Vector(4, i64) = [_]i64{ -2, -1, 0, 1 };
1213 const vu64: @Vector(4, u64) = [_]u64{ 1000, 2000, 3000, 4000 };
1214
1215 try expectFmt("{ true, false, true, false }", "{}", .{vbool});
1216 try expectFmt("{ -2, -1, 0, 1 }", "{}", .{vi64});
1217 try expectFmt("{ -2, -1, +0, +1 }", "{d:5}", .{vi64});
1218 try expectFmt("{ 1000, 2000, 3000, 4000 }", "{}", .{vu64});
1219 try expectFmt("{ 3e8, 7d0, bb8, fa0 }", "{x}", .{vu64});
1220
1221 const x: [4]u64 = undefined;
1222 const vp: @Vector(4, *const u64) = [_]*const u64{ &x[0], &x[1], &x[2], &x[3] };
1223 const vop: @Vector(4, ?*const u64) = [_]?*const u64{ &x[0], null, null, &x[3] };
1224
1225 var expect_buffer: [@sizeOf(usize) * 2 * 4 + 64]u8 = undefined;
1226 try expectFmt(try mem.print(
1227 &expect_buffer,
1228 "{{ {}, {}, {}, {} }}",
1229 .{ &x[0], &x[1], &x[2], &x[3] },
1230 ), "{}", .{vp});
1231 try expectFmt(try mem.print(
1232 &expect_buffer,
1233 "{{ {?}, null, null, {?} }}",
1234 .{ &x[0], &x[3] },
1235 ), "{any}", .{vop});
1236}
1237
1238test "enum-literal" {
1239 try expectFmt(".hello_world", "{}", .{.hello_world});
1240 try expectFmt("hello_world", "{t}", .{.hello_world});
1241}
1242
1243test "padding" {
1244 try expectFmt("Simple", "{s}", .{"Simple"});
1245 try expectFmt(" 1234", "{:10}", .{1234});
1246 try expectFmt(" 1234", "{:>10}", .{1234});
1247 try expectFmt("======1234", "{:=>10}", .{1234});
1248 try expectFmt("1234======", "{:=<10}", .{1234});
1249 try expectFmt(" 1234 ", "{:^10}", .{1234});
1250 try expectFmt("===1234===", "{:=^10}", .{1234});
1251 try expectFmt("====a", "{c:=>5}", .{'a'});
1252 try expectFmt("==a==", "{c:=^5}", .{'a'});
1253 try expectFmt("a====", "{c:=<5}", .{'a'});
1254}
1255
1256test "decimal float padding" {
1257 const number: f32 = 3.1415;
1258 try expectFmt("left-pad: **3.142\n", "left-pad: {d:*>7.3}\n", .{number});
1259 try expectFmt("center-pad: *3.142*\n", "center-pad: {d:*^7.3}\n", .{number});
1260 try expectFmt("right-pad: 3.142**\n", "right-pad: {d:*<7.3}\n", .{number});
1261}
1262
1263test "sci float padding" {
1264 const number: f32 = 3.1415;
1265 try expectFmt("left-pad: ****3.142e0\n", "left-pad: {e:*>11.3}\n", .{number});
1266 try expectFmt("center-pad: **3.142e0**\n", "center-pad: {e:*^11.3}\n", .{number});
1267 try expectFmt("right-pad: 3.142e0****\n", "right-pad: {e:*<11.3}\n", .{number});
1268}
1269
1270test "padding.zero" {
1271 try expectFmt("zero-pad: '0042'", "zero-pad: '{:04}'", .{42});
1272 try expectFmt("std-pad: ' 42'", "std-pad: '{:10}'", .{42});
1273 try expectFmt("std-pad-1: '001'", "std-pad-1: '{:0>3}'", .{1});
1274 try expectFmt("std-pad-2: '911'", "std-pad-2: '{:1<03}'", .{9});
1275 try expectFmt("std-pad-3: ' 1'", "std-pad-3: '{:>03}'", .{1});
1276 try expectFmt("center-pad: '515'", "center-pad: '{:5^03}'", .{1});
1277}
1278
1279test "null" {
1280 const inst = null;
1281 try expectFmt("null", "{}", .{inst});
1282}
1283
1284test "type" {
1285 try expectFmt("u8", "{}", .{u8});
1286 try expectFmt("?f32", "{}", .{?f32});
1287 try expectFmt("[]const u8", "{}", .{[]const u8});
1288}
1289
1290test "named arguments" {
1291 try expectFmt("hello world!", "{s} world{c}", .{ "hello", '!' });
1292 try expectFmt("hello world!", "{[greeting]s} world{[punctuation]c}", .{ .punctuation = '!', .greeting = "hello" });
1293 try expectFmt("hello world!", "{[1]s} world{[0]c}", .{ '!', "hello" });
1294}
1295
1296test "runtime width specifier" {
1297 const width: usize = 9;
1298 try expectFmt("~~12345~~", "{d:~^[1]}", .{ 12345, width });
1299 try expectFmt("~~12345~~", "{d:~^[width]}", .{ .string = 12345, .width = width });
1300 try expectFmt(" 12345", "{d:[1]}", .{ 12345, width });
1301 try expectFmt("42 12345", "{d} {d:[2]}", .{ 42, 12345, width });
1302}
1303
1304test "runtime precision specifier" {
1305 const number: f32 = 3.1415;
1306 const precision: usize = 2;
1307 try expectFmt("3.14e0", "{e:1.[1]}", .{ number, precision });
1308 try expectFmt("3.14e0", "{e:1.[precision]}", .{ .number = number, .precision = precision });
1309}
1310
1311test "recursive format function" {
1312 const R = union(enum) {
1313 const R = @This();
1314 Leaf: i32,
1315 Branch: struct { left: *const R, right: *const R },
1316
1317 pub fn format(self: R, writer: *Writer) Writer.Error!void {
1318 return switch (self) {
1319 .Leaf => |n| writer.print("Leaf({})", .{n}),
1320 .Branch => |b| writer.print("Branch({f}, {f})", .{ b.left, b.right }),
1321 };
1322 }
1323 };
1324
1325 var r: R = .{ .Leaf = 1 };
1326 try expectFmt("Leaf(1)\n", "{f}\n", .{&r});
1327}
1328
1329pub const hex_charset = "0123456789abcdef";
1330
1331/// Converts an unsigned integer of any multiple of u8 to an array of lowercase
1332/// hex bytes, little endian.
1333pub fn hex(x: anytype) [@typeInfo(@TypeOf(x)).int.bits / 4]u8 {
1334 comptime assert(@typeInfo(@TypeOf(x)).int.signedness == .unsigned);
1335 var result: [@typeInfo(@TypeOf(x)).int.bits / 4]u8 = undefined;
1336 var i: usize = 0;
1337 while (i < result.len / 2) : (i += 1) {
1338 const byte: u8 = @truncate(x >> @intCast(8 * i));
1339 result[i * 2 + 0] = hex_charset[byte >> 4];
1340 result[i * 2 + 1] = hex_charset[byte & 15];
1341 }
1342 return result;
1343}
1344
1345test hex {
1346 {
1347 const x = hex(@as(u32, 0xdeadbeef));
1348 try testing.expect(x.len == 8);
1349 try testing.expectEqualStrings("efbeadde", &x);
1350 }
1351 {
1352 const s = "[" ++ hex(@as(u48, 0x12345678_abcd)) ++ "]";
1353 try testing.expect(s.len == 14);
1354 try testing.expectEqualStrings("[cdab78563412]", s);
1355 }
1356 {
1357 const s = "[" ++ hex(@as(u64, 0x12345678_abcdef00)) ++ "]";
1358 try testing.expect(s.len == 18);
1359 try testing.expectEqualStrings("[00efcdab78563412]", s);
1360 }
1361}
1362
1363test "parser until" {
1364 { // return substring till ':'
1365 var parser: Parser = .{ .bytes = "abc:1234", .i = 0 };
1366 try testing.expectEqualStrings("abc", parser.until(':'));
1367 }
1368
1369 { // return the entire string - `ch` not found
1370 var parser: Parser = .{ .bytes = "abc1234", .i = 0 };
1371 try testing.expectEqualStrings("abc1234", parser.until(':'));
1372 }
1373
1374 { // substring is empty - `ch` is the only character
1375 var parser: Parser = .{ .bytes = ":", .i = 0 };
1376 try testing.expectEqualStrings("", parser.until(':'));
1377 }
1378
1379 { // empty string and `ch` not found
1380 var parser: Parser = .{ .bytes = "", .i = 0 };
1381 try testing.expectEqualStrings("", parser.until(':'));
1382 }
1383
1384 { // substring starts at index 2 and goes upto `ch`
1385 var parser: Parser = .{ .bytes = "abc:1234", .i = 2 };
1386 try testing.expectEqualStrings("c", parser.until(':'));
1387 }
1388
1389 { // substring starts at index 4 and goes upto the end - `ch` not found
1390 var parser: Parser = .{ .bytes = "abc1234", .i = 4 };
1391 try testing.expectEqualStrings("234", parser.until(':'));
1392 }
1393}
1394
1395test "parser peek" {
1396 { // start iteration from the first index
1397 var parser: Parser = .{ .bytes = "hello world", .i = 0 };
1398 try testing.expectEqual('h', parser.peek(0));
1399 try testing.expectEqual('e', parser.peek(1));
1400 try testing.expectEqual(' ', parser.peek(5));
1401 try testing.expectEqual('d', parser.peek(10));
1402 try testing.expectEqual(null, parser.peek(11));
1403 }
1404
1405 { // start iteration from the second last index
1406 var parser: Parser = .{ .bytes = "hello world!", .i = 10 };
1407
1408 try testing.expectEqual('d', parser.peek(0));
1409 try testing.expectEqual('!', parser.peek(1));
1410 try testing.expectEqual(null, parser.peek(5));
1411 }
1412
1413 { // start iteration beyond the length of the string
1414 var parser: Parser = .{ .bytes = "hello", .i = 5 };
1415
1416 try testing.expectEqual(null, parser.peek(0));
1417 try testing.expectEqual(null, parser.peek(1));
1418 }
1419
1420 { // empty string
1421 var parser: Parser = .{ .bytes = "", .i = 0 };
1422
1423 try testing.expectEqual(null, parser.peek(0));
1424 try testing.expectEqual(null, parser.peek(2));
1425 }
1426}
1427
1428test "parser char" {
1429 // character exists - iterator at 0
1430 var parser: Parser = .{ .bytes = "~~hello", .i = 0 };
1431 try testing.expectEqual('~', parser.char());
1432
1433 // character exists - iterator in the middle
1434 parser = .{ .bytes = "~~hello", .i = 3 };
1435 try testing.expectEqual('e', parser.char());
1436
1437 // character exists - iterator at the end
1438 parser = .{ .bytes = "~~hello", .i = 6 };
1439 try testing.expectEqual('o', parser.char());
1440
1441 // character doesn't exist - iterator beyond the length of the string
1442 parser = .{ .bytes = "~~hello", .i = 7 };
1443 try testing.expectEqual(null, parser.char());
1444}
1445
1446test "parser maybe" {
1447 // character exists - iterator at 0
1448 var parser: Parser = .{ .bytes = "hello world", .i = 0 };
1449 try testing.expect(parser.maybe('h'));
1450
1451 // character exists - iterator at space
1452 parser = .{ .bytes = "hello world", .i = 5 };
1453 try testing.expect(parser.maybe(' '));
1454
1455 // character exists - iterator at the end
1456 parser = .{ .bytes = "hello world", .i = 10 };
1457 try testing.expect(parser.maybe('d'));
1458
1459 // character doesn't exist - iterator beyond the length of the string
1460 parser = .{ .bytes = "hello world", .i = 11 };
1461 try testing.expect(!parser.maybe('e'));
1462}
1463
1464test "parser number" {
1465 // input is a single digit natural number - iterator at 0
1466 var parser: Parser = .{ .bytes = "7", .i = 0 };
1467 try testing.expect(7 == parser.number());
1468
1469 // input is a two digit natural number - iterator at 1
1470 parser = .{ .bytes = "29", .i = 1 };
1471 try testing.expect(9 == parser.number());
1472
1473 // input is a two digit natural number - iterator beyond the length of the string
1474 parser = .{ .bytes = "32", .i = 2 };
1475 try testing.expectEqual(null, parser.number());
1476
1477 // input is an integer
1478 parser = .{ .bytes = "0", .i = 0 };
1479 try testing.expect(0 == parser.number());
1480
1481 // input is a negative integer
1482 parser = .{ .bytes = "-2", .i = 0 };
1483 try testing.expectEqual(null, parser.number());
1484
1485 // input is a string
1486 parser = .{ .bytes = "no_number", .i = 2 };
1487 try testing.expectEqual(null, parser.number());
1488
1489 // input is a single character string
1490 parser = .{ .bytes = "n", .i = 0 };
1491 try testing.expectEqual(null, parser.number());
1492
1493 // input is an empty string
1494 parser = .{ .bytes = "", .i = 0 };
1495 try testing.expectEqual(null, parser.number());
1496}
1497
1498test "parser specifier" {
1499 { // input string is a digit; iterator at 0
1500 const expected: Specifier = Specifier{ .number = 1 };
1501 var parser: Parser = .{ .bytes = "1", .i = 0 };
1502
1503 const result = try parser.specifier();
1504 try testing.expect(expected.number == result.number);
1505 }
1506
1507 { // input string is a two digit number; iterator at 0
1508 const digit: Specifier = Specifier{ .number = 42 };
1509 var parser: Parser = .{ .bytes = "42", .i = 0 };
1510
1511 const result = try parser.specifier();
1512 try testing.expect(digit.number == result.number);
1513 }
1514
1515 { // input string is a two digit number digit; iterator at 1
1516 const digit: Specifier = Specifier{ .number = 8 };
1517 var parser: Parser = .{ .bytes = "28", .i = 1 };
1518
1519 const result = try parser.specifier();
1520 try testing.expect(digit.number == result.number);
1521 }
1522
1523 { // input string is a two digit number with square brackets; iterator at 0
1524 const digit: Specifier = Specifier{ .named = "15" };
1525 var parser: Parser = .{ .bytes = "[15]", .i = 0 };
1526
1527 const result = try parser.specifier();
1528 try testing.expectEqualStrings(digit.named, result.named);
1529 }
1530
1531 { // input string is not a number and contains square brackets; iterator at 0
1532 const digit: Specifier = Specifier{ .named = "hello" };
1533 var parser: Parser = .{ .bytes = "[hello]", .i = 0 };
1534
1535 const result = try parser.specifier();
1536 try testing.expectEqualStrings(digit.named, result.named);
1537 }
1538
1539 { // input string is not a number and doesn't contain closing square bracket; iterator at 0
1540 var parser: Parser = .{ .bytes = "[hello", .i = 0 };
1541
1542 const result = parser.specifier();
1543 try testing.expectError(@field(anyerror, "Expected closing ]"), result);
1544 }
1545
1546 { // input string is not a number and doesn't contain closing square bracket; iterator at 2
1547 var parser: Parser = .{ .bytes = "[[[[hello", .i = 2 };
1548
1549 const result = parser.specifier();
1550 try testing.expectError(@field(anyerror, "Expected closing ]"), result);
1551 }
1552
1553 { // input string is not a number and contains unbalanced square brackets; iterator at 0
1554 const digit: Specifier = Specifier{ .named = "[[hello" };
1555 var parser: Parser = .{ .bytes = "[[[hello]", .i = 0 };
1556
1557 const result = try parser.specifier();
1558 try testing.expectEqualStrings(digit.named, result.named);
1559 }
1560
1561 { // input string is not a number and contains unbalanced square brackets; iterator at 1
1562 const digit: Specifier = Specifier{ .named = "[[hello" };
1563 var parser: Parser = .{ .bytes = "[[[[hello]]]]]", .i = 1 };
1564
1565 const result = try parser.specifier();
1566 try testing.expectEqualStrings(digit.named, result.named);
1567 }
1568
1569 { // input string is neither a digit nor a named argument
1570 const char: Specifier = Specifier{ .none = {} };
1571 var parser: Parser = .{ .bytes = "hello", .i = 0 };
1572
1573 const result = try parser.specifier();
1574 try testing.expectEqual(char.none, result.none);
1575 }
1576}
1577
1578test {
1579 _ = float;
1580}