From 0065eb7c80c2bb68585e42b87131f374e1d3fcbc Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 23 May 2017 18:38:41 -0400 Subject: [PATCH] std.fmt can print nullables, errors, and error unions --- std/fmt.zig | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/std/fmt.zig b/std/fmt.zig index 555ed8b800..cccf9539e8 100644 --- a/std/fmt.zig +++ b/std/fmt.zig @@ -188,6 +188,25 @@ pub fn formatValue(value: var, context: var, output: fn(@typeOf(context), []cons builtin.TypeId.Bool => { return output(context, if (value) "true" else "false"); }, + builtin.TypeId.Nullable => { + if (value) |payload| { + return formatValue(payload, context, output); + } else { + return output(context, "null"); + } + }, + builtin.TypeId.ErrorUnion => { + if (value) |payload| { + return formatValue(payload, context, output); + } else |err| { + return formatValue(err, context, output); + } + }, + builtin.TypeId.Error => { + if (!output(context, "error.")) + return false; + return output(context, @errorName(value)); + }, else => if (@canImplicitCast([]const u8, value)) { const casted_value = ([]const u8)(value); return output(context, casted_value); @@ -407,3 +426,30 @@ test "parse unsigned comptime" { assert(%%parseUnsigned(usize, "2", 10) == 2); } } + +test "fmt.format" { + { + var buf1: [32]u8 = undefined; + const value: ?i32 = 1234; + const result = bufPrint(buf1[0..], "nullable: {}\n", value); + assert(mem.eql(u8, result, "nullable: 1234\n")); + } + { + var buf1: [32]u8 = undefined; + const value: ?i32 = null; + const result = bufPrint(buf1[0..], "nullable: {}\n", value); + assert(mem.eql(u8, result, "nullable: null\n")); + } + { + var buf1: [32]u8 = undefined; + const value: %i32 = 1234; + const result = bufPrint(buf1[0..], "error union: {}\n", value); + assert(mem.eql(u8, result, "error union: 1234\n")); + } + { + var buf1: [32]u8 = undefined; + const value: %i32 = error.InvalidChar; + const result = bufPrint(buf1[0..], "error union: {}\n", value); + assert(mem.eql(u8, result, "error union: error.InvalidChar\n")); + } +}