From 68c9430f1960f54e0d587b4a36a209991e091dd0 Mon Sep 17 00:00:00 2001 From: Brandon Mitchell Date: Mon, 9 Aug 2021 14:21:54 -0700 Subject: [PATCH] Add compile-time checked variants of writef and writefln to std.outbuffer. --- std/outbuffer.d | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/std/outbuffer.d b/std/outbuffer.d index 584f9c20f..9590238c7 100644 --- a/std/outbuffer.d +++ b/std/outbuffer.d @@ -13,6 +13,7 @@ Serialize data to `ubyte` arrays. module std.outbuffer; import core.stdc.stdarg; +import std.traits : isSomeString; /********************************************* * OutBuffer provides a way to build up an array of bytes out @@ -323,6 +324,25 @@ class OutBuffer assert(b.toString() == "a16b"); } + /// ditto + void writef(alias fmt, A...)(A args) + if (isSomeString!(typeof(fmt))) + { + import std.format : checkFormatException; + + alias e = checkFormatException!(fmt, A); + static assert(!e, e.msg); + return this.writef(fmt, args); + } + + /// + @safe unittest + { + OutBuffer b = new OutBuffer(); + b.writef!"a%sb"(16); + assert(b.toString() == "a16b"); + } + /** * Formats and writes its arguments in text format to the OutBuffer, * followed by a newline. @@ -350,6 +370,25 @@ class OutBuffer assert(b.toString() == "a16b\n"); } + /// ditto + void writefln(alias fmt, A...)(A args) + if (isSomeString!(typeof(fmt))) + { + import std.format : checkFormatException; + + alias e = checkFormatException!(fmt, A); + static assert(!e, e.msg); + return this.writefln(fmt, args); + } + + /// + @safe unittest + { + OutBuffer b = new OutBuffer(); + b.writefln!"a%sb"(16); + assert(b.toString() == "a16b\n"); + } + /***************************************** * At offset index into buffer, create nbytes of space by shifting upwards * all data past index.