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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
/* 
   Copyright (c) 2015, 2016, 2020 Andreas F. Borchert
   All rights reserved.

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
*/

/*
   This header-only C++11 package provides fmt::printf which
   is intended as a type-safe and extensible drop-in replacement
   for std::printf. The principal idea is to replace

      #include <cstdio>
      // ...
      std::printf(...)

   by

      #include "printf.hpp"       or        #include <printf.hpp>
      // ...
      fmt::printf(...)

   and likewise:

      std::fprintf(fp, ...)       by        fmt::printf(out, ...)
      std::snprintf(s, n, ...)    by        fmt::snprintf(s, n, ...)
      std::wprintf(...)           by        fmt::printf(...)

   where out is an ostream, not a FILE*. As fmt::printf is
   based on variadic template constructs of C++11, this
   is possible in a typesafe way. Consequently, it no
   longer matters for fmt::printf whether you use "%f",
   "%lf", or "%Lf" as format. And all operands are supported
   for which an <<-operator exists.

   fmt::printf uses C++ I/O format flags but makes sure
   that the previous state of manipulators and flags of
   the output stream is restored to its original state
   after its invocation. Any previous state is ignored,
   i.e. fmt::printf("%x", val) will print val in hex
   even if std::cout << std::oct has been used before,
   and the previous octal conversion preference will stay
   in effect for <<-operators after the invocation of fmt::printf.

   Please note that the output format of %p is not
   standardized. As the <<-operator for void* may
   differ from the std::printf behaviour for %p, results
   can be different.

   Wide characters, wide strings, and wide streams and
   their mix are supported. However, the type of the
   format string must match that of the stream.

   Restrictions:
      - The combination of hexfloat with a precision (e.g. "%.2a") 
        is not supported by C++11 (see 22.4.2.2.2 in ISO 14882:2011)
        but supported by std::printf (see 7.21.6.1 in ISO 9899:2011).
        As this implementation depends on the C++11 library, it
        appears hard to find a reasonable workaround for this
        diverting behaviour.

   Alternatives:

   This is not the first attempt to provide printf look
   and feel in a type-safe way for C++:

    - In 1994, Cay S. Horstmann published an article about
      extending the iostreams library in C++ Report where he
      proposed a setformat. Example from his paper:

         cout << "(" << setformat("%8.2f") << x << "," 
                   << setformat("8.2f") << y << ")" << endl;

      Note that he used one setformat per placeholder as
      C++ at that time did not support variadic templates.
      This paper is available at
         http://horstmann.com/cpp/iostreams.html

    - The Boost Format library has created an approach
      that does not depend on variadic templates. The
      %-operator is used instead:

      std::cout << boost::format("(x, y) = (%4f, %4f)\n" % x % y;

      See http://www.boost.org/doc/libs/1_59_0/libs/format/doc/format.html

    - There is a proposal by Zhihao Yuan for a printf-like interface for the
      C++ streams library:

      std::cout << std::putf("(x, y) = (%4f, %4f)\n", x, y);

      See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3506.html
      and https://github.com/lichray/formatxx

    - http://codereview.stackexchange.com/questions/63578/printf-like-formatting-for-stdostream-not-exactly-boostformat
*/

#ifndef FMT_PRINTF_HPP
#define FMT_PRINTF_HPP

#if __cplusplus < 201103L
#error This file requires compiler and library support for the \
ISO C++ 2011 standard.
#else

#include <cassert>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <exception>
#include <iomanip>
#include <iostream>
#include <limits>
#include <locale>
#include <sstream>
#include <streambuf>
#include <string>
#include <tuple>
#include <type_traits>

namespace fmt {

namespace impl {

/* type trait to recognize char types which can be distinguished
   from regular numerical types, see also
   http://stackoverflow.com/questions/20958262/char16-t-and-char32-t-types-in-c11
*/
template<typename T> struct is_char : public std::false_type {};
template<> struct is_char<char> : public std::true_type {};
template<> struct is_char<wchar_t> : public std::true_type {};
template<> struct is_char<char16_t> : public std::true_type {};
template<> struct is_char<char32_t> : public std::true_type {};

/* printf is expected to return the number of bytes written;
   the following extensions direct all output to the given
   output stream and count all bytes written */
template<typename CharT, typename Traits = std::char_traits<CharT>>
class counting_ostreambuf : public std::basic_streambuf<CharT, Traits> {
   public:
      counting_ostreambuf(std::basic_streambuf<CharT, Traits>& sbuf) :
         sbuf(sbuf), nbytes(0) {
      }
      std::streamsize get_count() const {
         return nbytes;
      }
   protected:
      using Base = std::basic_streambuf<CharT, Traits>;
      using char_type = typename Base::char_type;
      using int_type = typename Base::int_type;
      using traits_type = typename Base::traits_type;

      virtual std::streamsize xsputn(const char_type* s,
            std::streamsize count) {
         std::streamsize result = sbuf.sputn(s, count);
         if (result > 0) nbytes += result;
         return result;
      }
      virtual int_type overflow(int_type ch) {
         /* modeled after
            http://stackoverflow.com/questions/10921761/extending-c-ostream */
         if (ch == traits_type::eof()) {
            return traits_type::eof();
         } else {
            char_type c = traits_type::to_char_type(ch);
            return xsputn(&c, 1) == 1? ch: traits_type::eof();
         }
      }
      virtual int sync() {
         return sbuf.pubsync();
      }
   private:
      std::basic_streambuf<CharT, Traits>& sbuf;
      std::streamsize nbytes;
};

template<typename CharT, typename Traits = std::char_traits<CharT>>
class counting_ostream : public std::basic_ostream<CharT, Traits> {
   public:
      using Base = std::basic_ostream<CharT, Traits>;
      counting_ostream(std::basic_ostream<CharT, Traits>& out) :
            Base(&sbuf), sbuf(*(out.rdbuf())) {
         /* inherit locale from our base stream */
         this->imbue(out.getloc());
      }
      std::streamsize get_count() const {
         return sbuf.get_count();
      }
   private:
      counting_ostreambuf<CharT, Traits> sbuf;
};

template<typename CharT, typename Traits = std::char_traits<CharT>>
class uppercase_ostreambuf : public std::basic_streambuf<CharT, Traits> {
   public:
      uppercase_ostreambuf(std::basic_streambuf<CharT, Traits>& sbuf) :
         sbuf(sbuf) {
      }
   protected:
      using Base = std::basic_streambuf<CharT, Traits>;
      using char_type = typename Base::char_type;
      using int_type = typename Base::int_type;
      using traits_type = typename Base::traits_type;

      virtual std::streamsize xsputn(const char_type* s,
            std::streamsize count) {
         for (std::streamsize i = 0; i < count; ++i) {
            char_type ch = s[i];
            if (std::islower(ch, this->getloc())) {
               ch = std::toupper(ch, this->getloc());
            }
            if (sbuf.sputc(ch) == traits_type::eof()) {
               return i;
            }
         }
         return count;
      }

      virtual int_type overflow(int_type ch) {
         if (ch == traits_type::eof()) {
            return traits_type::eof();
         } else {
            char_type c = traits_type::to_char_type(ch);
            return xsputn(&c, 1) == 1? ch: traits_type::eof();
         }
      }
      virtual int sync() {
         return sbuf.pubsync();
      }
   private:
      std::basic_streambuf<CharT, Traits>& sbuf;
};

template<typename CharT, typename Traits = std::char_traits<CharT>>
class uppercase_ostream : public std::basic_ostream<CharT, Traits> {
   public:
      using Base = std::basic_ostream<CharT, Traits>;
      uppercase_ostream(std::basic_ostream<CharT, Traits>& out) :
            Base(&sbuf), sbuf(*(out.rdbuf())) {
         this->copyfmt(out);
         /* inherit locale from our base stream */
         this->imbue(out.getloc());
      }
   private:
      uppercase_ostreambuf<CharT, Traits> sbuf;
};

/* std::numpunct extension for the format flag '\''
   that explicitly asks for thousands' grouping characters */
struct thousands_grouping : std::numpunct<char> {
   std::string do_grouping() const {
      return "\3";
   }
};

/* std::numpunct extension that suppresses the
   use of grouping characters,
   this is necessary to conform to std::printf behaviour */
struct suppress_grouping : std::numpunct<char> {
   std::string do_grouping() const {
      return "\0";
   }
};

/* RAII object that saves the current formatting state of the stream
   and makes sure that the state is restored on destruction */
template<typename CharT, typename Traits>
struct format_saver {
   format_saver(std::basic_ios<CharT, Traits>& s) :
      s(s), format_keeper(nullptr) {
      format_keeper.copyfmt(s);
   }
   ~format_saver() {
      s.copyfmt(format_keeper);
   }
   std::basic_ios<CharT, Traits>& s;
   std::basic_ios<CharT, Traits> format_keeper;
};

/* reset the entire format state to its default */
template<typename CharT, typename Traits>
inline void reset_format(std::basic_ios<CharT, Traits>& s) {
   std::basic_ios<CharT, Traits> dflt(nullptr);
   s.copyfmt(dflt);
}

/* some compilers like icpc or nvcc deliver a warning even
   for template parameters that we have a "pointless comparison
   of unsigned with zero"; the function is_negative is used
   to circumvent this */
template<typename Value>
typename std::enable_if<
      std::is_integral<typename std::remove_reference<Value>::type>::value &&
      std::is_signed<typename std::remove_reference<Value>::type>::value,
      bool>::type
is_negative(Value value) {
   return value < 0;
}

template<typename Value>
typename std::enable_if<
      std::is_integral<typename std::remove_reference<Value>::type>::value &&
      !std::is_signed<typename std::remove_reference<Value>::type>::value,
      bool>::type
is_negative(Value value) {
   return false;
}

/* internal signed integer type which is used for indices and byte counts */
using integer = std::make_signed<std::size_t>::type;

using flagset = unsigned short;
constexpr flagset is_pointer = 1<<0;
constexpr flagset is_charval = 1<<1;
constexpr flagset is_integer = 1<<2;
constexpr flagset is_unsigned = 1<<3;
constexpr flagset toupper = 1<<4; // when std::uppercase won't cut it
constexpr flagset space_flag = 1<<5; // add space, if non-negative
constexpr flagset plus_flag = 1<<6;
constexpr flagset dyn_width = 1<<7;
constexpr flagset precision = 1<<8; // precision was given
constexpr flagset dyn_precision = 1<<9;
constexpr flagset zero_fill = 1<<10;
constexpr flagset minus_flag = 1<<11;
constexpr flagset special_flag = 1<<12;
constexpr flagset grouping_flag = 1<<13;

/* this structure represents a segment of a format string
   up to and including at most one placeholder */
template<typename CharT>
struct format_segment {
   constexpr format_segment() :
      valid(false),
      beginp(nullptr), endp(nullptr), nextp(nullptr),
      fmtflags(), flags(0), base(0), nof_args(0),
      width(0), precision(0),
      width_index(-1), precision_index(-1), value_index(-1),
      conversion(0) {
   }
   /* valid is set to false when format parsing failed */
   bool valid;
   /* stretch of the format string which is to be
      printed in verbatim; if beginp == endp
      nothing is to be printed */
   const CharT* beginp; const CharT* endp;
   /* where to continue parsing */
   const CharT* nextp;
   /* preliminary set of flags that are to be set
      on the output stream */
   std::ios_base::fmtflags fmtflags;
   /* internal flags */
   flagset flags;
   /* base in case of numerical conversions */
   integer base;
   /* number of arguments that are to be consumed,
      this is between 0 and 2 */
   unsigned short int nof_args;
   /* width and precision, if given within the format */
   std::streamsize width;
   std::streamsize precision;
   /* indices of arguments, where required */
   integer width_index;
   integer precision_index;
   integer value_index;
   /* conversion character, i.e. d o x u etc. */
   CharT conversion;
};

/* parse integer value from format string;
   return false in case of overflows */
template<typename CharT, typename T>
bool parse_integer(const CharT*& format, T& val) {
   T v{};
   CharT ch = *format;
   constexpr T maxval = std::numeric_limits<T>::max();
   constexpr T maxval10 = maxval / 10;
   while (ch >= '0' && ch <= '9') {
      T digit = ch - '0';
      if (v > maxval10) return false;
      v *= 10;
      if (v > maxval - digit) return false;
      v += digit;
      ch = *++format;
   }
   val = v;
   return true;
}

/* parse up to one format specification and
   invoke the respective manipulators for out
   and/or set the corresponding flags */
template<typename CharT>
inline format_segment<CharT>
parse_format_segment(const CharT* format, integer arg_index) {
   format_segment<CharT> result;
   if (!format) return result;

   /* skip everything until we encounter a placeholder
      or the end of the format string */
   result.beginp = format;
   CharT ch = *format;
   while (ch && ch != '%') {
      ch = *++format;
   }
   result.endp = format;

   /* end of format string reached? */
   if (!ch) {
      result.valid = true;
      return result;
   }

   ch = *++format;
   if (!ch) return result; /* format ends with '%' */

   /* process %% */
   if (ch == '%') {
      result.valid = true;
      ++result.endp; /* include first '%' */
      result.nextp = format+1;
      return result;
   }

   /* check if we have an argument index */
   if (ch >= '1' && ch <= '9') {
      const CharT* begin = format;
      integer index;
      if (parse_integer(format, index) && *format == '$') {
         /* accept argument index */
         result.value_index = index - 1;
         ch = *++format;
      } else {
         /* reset parsing */
         format = begin; ch = *format;
      }
   }

   /* process conversion flags */
   while (ch == '\'' || ch == '-' || ch == '0' || ch == '+' ||
         ch == ' ' || ch == '#') {
      switch (ch) {
         case '\'':
            result.flags |= grouping_flag;
            break;
         case '-':
            result.flags |= minus_flag;
            result.fmtflags |= std::ios_base::left;
            break;
         case '0': result.flags |= zero_fill; break;
         case '+':
            result.flags |= plus_flag;
            result.fmtflags |= std::ios_base::showpos;
            break;
         case ' ': result.flags |= space_flag; break;
         case '#':
            result.flags |= special_flag;
            result.fmtflags |= (std::ios_base::showbase |
               std::ios_base::showpoint);
            break;
      }
      ch = *++format;
   }

   if ((result.flags & minus_flag) && (result.flags & zero_fill)) {
      /* if the 0 and - flags both appear, the 0 flag is ignored */
      result.flags &= ~zero_fill;
   }
   if ((result.flags & plus_flag) && (result.flags & space_flag)) {
      /* if the ' ' and '+' flags both appear,
         the <space> flag shall be ignored */
      result.flags &= ~space_flag;
   }
   /* minimum field width */
   std::streamsize width = 0;
   if (ch == '*') {
      result.flags |= dyn_width; ch = *++format;
      if (ch >= '1' && ch <= '9') {
         integer index;
         if (!parse_integer(format, index) || *format != '$') return result;
         ch = *++format;
         result.width_index = index - 1;
      } else {
         result.width_index = arg_index + result.nof_args;
      }
      result.nof_args++;
   } else {
      if (!parse_integer(format, width)) return result;
      ch = *format;
      result.width = width;
   }
   /* precision */
   if (ch == '.') {
      result.flags |= precision;
      ch = *++format;
      std::streamsize precision = 0;
      if (ch == '*') {
         result.flags |= dyn_precision; ch = *++format;
         if (ch >= '1' && ch <= '9') {
            integer index;
            if (!parse_integer(format, index) || *format != '$') return result;
            ch = *++format;
            result.precision_index = index - 1;
         } else {
            result.precision_index = arg_index + result.nof_args;
         }
         result.nof_args++;
      } else {
         if (ch >= '0' && ch <= '9') {
            if (!parse_integer(format, precision)) return result;
            ch = *format;
         }
         result.precision = precision;
      }
      if (result.flags & zero_fill) {
         /* if a precision is specified, the 0 flag is ignored */
         result.flags &= ~zero_fill;
      }
   }
   /* skip size specification */
   while (ch == 'l' || ch == 'L' || ch == 'h' ||
         ch == 'j' || ch == 'z' || ch == 't') {
      ch = *++format;
   }
   /* conversion operation */
   result.conversion = ch;
   switch (ch) {
      case 'u':
         result.flags |= is_unsigned;
      case 'd':
      case 'i':
         result.flags |= is_integer;
         result.base = 10;
         break;
      case 'o':
         result.flags |= is_integer;
         result.base = 8;
         break;
      case 'x':
         result.flags |= is_integer;
         result.base = 16;
         break;
      case 'X':
         result.fmtflags |= std::ios_base::uppercase;
         result.flags |= is_integer;
         result.base = 16;
         break;
      case 'f':
         result.fmtflags |= std::ios_base::fixed;
         result.base = 10;
         break;
      case 'F':
         result.fmtflags |= (std::ios_base::fixed | std::ios_base::uppercase);
         result.flags |= toupper;
         result.base = 10;
         break;
      case 'e':
         result.fmtflags |= std::ios_base::scientific;
         result.base = 10;
         break;
      case 'E':
         result.fmtflags |=
            std::ios_base::scientific | std::ios_base::uppercase;
         result.flags |= toupper;
         result.base = 10;
         break;
      case 'g':
         /* default behaviour */
         result.base = 10;
         break;
      case 'G':
         result.fmtflags |= std::ios_base::uppercase;
         result.flags |= toupper;
         result.base = 10;
         break;
      case 'a':
         result.fmtflags |= std::ios_base::scientific | std::ios_base::fixed;
         result.base = 16;
         break;
      case 'A':
         result.fmtflags |= std::ios_base::scientific |
            std::ios_base::fixed | std::ios_base::uppercase;
         result.flags |= toupper;
         result.base = 16;
         break;
      case 'p':
         result.base = 16;
         result.flags |= is_pointer;
         break;
      case 'C':
         /* POSIX extension, equivalent to 'lc' */
      case 'c':
         result.flags |= is_charval;
         break;
      case 'S':
         /* POSIX extension, equivalent to 'ls' */
      case 's':
         /* when boolean values are printed with %s, we get
            more readable results; idea taken from N3506 */
         result.fmtflags |= std::ios_base::boolalpha;
         break;
      case 'n':
         /* nothing to be done here */
         break;
      default:
         return result;
   }
   if ((result.flags & grouping_flag) && (result.base != 10)) {
      /* grouping is just supported for %i, %d, %u, %f, %F,
         %g, and %G, i.e. all cases with base == 10 */
      result.flags &= ~grouping_flag;
   }
   result.valid = true;
   if (result.value_index < 0) {
      result.value_index = arg_index + result.nof_args;
   }
   result.nof_args++;
   ch = *++format;
   if (ch) {
      result.nextp = format;
   }
   return result;
}

/* similar to std::integer_sequence of C++14 */
template<integer... Is> struct seq {
   typedef seq<Is..., sizeof...(Is)> next;
};
template<integer N> struct gen_seq {
   typedef typename gen_seq<N-1>::type::next type;
};
template<> struct gen_seq<0> {
   typedef seq<> type;
};

/* idea taken from
   http://stackoverflow.com/questions/21062864/optimal-way-to-access-stdtuple-element-in-runtime-by-index
*/

/* apply f on the n-th element of a tuple for compile-time n */
template<integer N, typename Tuple, typename Function>
inline auto apply(const Tuple& tuple, Function&& f)
      -> decltype(f(std::get<N>(tuple))) {
   return f(std::get<N>(tuple));
}

/* helper to apply f on the n-th element of a tuple for runtime n */
template<typename Tuple, typename Function, integer... Is>
inline auto apply(const Tuple& tuple, integer index, Function&& f, seq<Is...>)
      -> decltype(f(std::get<0>(tuple))) {
   using apply_t = decltype(&apply<0, Tuple, Function>);
   static const apply_t apply_functions[] = {&apply<Is, Tuple, Function>...};
   return apply_functions[index](tuple, std::forward<Function>(f));
}

/* apply f on the n-th element of a tuple for runtime n */
template<typename Tuple, typename Function>
inline auto apply(const Tuple& tuple, integer index, Function&& f)
      -> decltype(f(std::get<0>(tuple))) {
   return apply(tuple, index, std::forward<Function>(f),
      typename gen_seq<std::tuple_size<Tuple>::value>::type());
}

/* function object class to extract an integer value by index
   from a tuple */
struct get_value_f {
   template<typename Value>
   typename std::enable_if<std::is_integral<Value>::value, integer>::type
   operator()(Value value) {
      return static_cast<integer>(value);
   }
   /* return -1 when the value is not of integral type */
   template<typename Value>
   typename std::enable_if<!std::is_integral<Value>::value, integer>::type
   operator()(Value value) {
      return -1;
   }
};

/* extract an integer value by index from a tuple,
   -1 is returned in case of failures */
template<typename Tuple>
inline integer get_value(const Tuple& tuple, integer index) {
   if (index >= 0 &&
         index < static_cast<integer>(std::tuple_size<Tuple>::value)) {
      return apply(tuple, index, get_value_f());
   } else {
      return -1;
   }
}

/* set offset value in case of %n */
struct set_value_f {
   set_value_f(std::streamsize offset) : offset(offset) {
   }
   integer operator()(int* ptr) {
      *ptr = static_cast<int>(offset);
      return 0;
   }
   template<typename Value>
   integer operator()(Value ptr) {
      return -1;
   }
   std::streamsize offset;
};

template<typename Tuple>
inline integer set_value(const Tuple& tuple, integer index,
      std::streamsize offset) {
   if (index >= 0 &&
         index < static_cast<integer>(std::tuple_size<Tuple>::value)) {
      return apply(tuple, index, set_value_f(offset));
   } else {
      return -1;
   }
}

/* general formatted output route */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<
      !std::is_integral<
         typename std::remove_reference<Value>::type>::value &&
      !std::is_floating_point<
         typename std::remove_reference<Value>::type>::value &&
      !std::is_pointer<
         typename std::remove_reference<Value>::type>::value, bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, Value&& value) {
   out << value;
   return !!out;
}

/* formatted output of floating point values */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<
      std::is_floating_point<
         typename std::remove_reference<Value>::type>::value,
      bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, Value&& value) {
   if ((fseg.flags & zero_fill) && std::isfinite(value)) {
      out << std::setfill(static_cast<CharT>('0'));
      out.setf(std::ios_base::internal);
   }
   if ((fseg.flags & space_flag) && !std::signbit(value)) {
      if (!out.put(' ')) return false;
      if (fseg.width > 0) {
         out.width(fseg.width-1);
      }
   }
   if (fseg.flags & toupper) {
      /* the default output operators fail to
         use uppercase characters in some cases */
      impl::uppercase_ostream<CharT, Traits> fpout(out);
      fpout << value;
   } else {
      out << value;
   }
   return !!out;
}

template<typename Value>
inline integer count_digits(Value value, integer base) {
   if (value == 0) {
      return 1;
   } else {
      integer digits = 0;
      while (value != 0) {
         value /= base; ++digits;
      }
      return digits;
   }
}

/* formatted output of character values (in case of %c)
   where we got a non-char-type numerical value */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<!is_char<Value>::value, bool>::type
print_char_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, Value value) {
   out << static_cast<CharT>(value);
   return !!out;
}

/* formatted output of character values (in case of %c)
   without conversion */
template<typename CharT, typename Traits>
inline bool print_char_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, CharT value) {
   out << value;
   return !!out;
}

/* formatted output of character values (in case of %c)
   that needs to be widened */
template<typename CharT, typename Traits>
inline typename std::enable_if<!std::is_same<char, CharT>::value,
      bool>::type
print_char_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, char value) {
   out << out.widen(value);
   return !!out;
}

/* formatted output of character values (in case of %c)
   where we got a non-char-type numerical value */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<
      is_char<Value>::value &&
      !std::is_same<Value, char>::value &&
      !std::is_same<Value, CharT>::value,
      bool>::type
print_char_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, Value value) {
   auto& f = std::use_facet<std::codecvt<Value, CharT, std::mbstate_t>>(
      out.getloc());
   std::mbstate_t state{};
   std::basic_string<CharT> converted(f.max_length(), 0);
   const Value* from_next;
   CharT* to_next;
   auto result = f.out(state,
      /* from */ &value, &value + 1, from_next,
      /* to */ &converted[0], &converted[converted.size()], to_next);
   if (result == std::codecvt_base::ok) {
      converted.resize(to_next - &converted[0]);
      out << converted;
   } else {
      out.setstate(std::ios_base::failbit);
   }
   return !!out;
}

/* formatted output of integral values
   which possibly need to be converted to characters first
   (in case of %c) */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<
      std::is_integral<typename std::remove_reference<Value>::type>::value,
      bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, Value&& value) {
   integer padding = 0;
   if (fseg.flags & is_charval) {
      print_char_value(out, fseg, value);
   } else if (fseg.flags & is_integer) {
      if (fseg.flags & zero_fill) {
         out << std::internal << std::setfill(out.widen('0'));
      } else if (fseg.flags & precision) {
         integer digits = count_digits(value, fseg.base);
         integer signwidth = is_negative(value) ||
            (fseg.flags & (plus_flag | space_flag));
         integer extra = signwidth;
         if (value != 0 && (fseg.flags & special_flag) && fseg.base == 16) {
            extra += 2; /* '0x' */
         }
         if (fseg.flags & grouping_flag) {
            extra += digits / 3;
         }
         if (fseg.precision > digits) {
            /* padding with 0s required */
            if (fseg.width > fseg.precision + extra) {
               /* manual filling is required */
               if ((out.flags() & std::ios_base::adjustfield) ==
                     std::ios_base::left) {
                  /* padding has to be postponed */
                  padding = fseg.width - fseg.precision - extra;
               } else {
                  for (int i = 0; i < fseg.width - fseg.precision - extra;
                        ++i) {
                     out.put(out.widen(' '));
                  }
               }
            }
            out << std::internal << std::setfill(out.widen('0')) <<
               std::setw(fseg.precision + extra);
         }
      }
      if ((fseg.flags & space_flag) && !is_negative(value)) {
         if (!out.put(' ')) return false;
         auto width = out.width(0);
         if (width > 0) {
            out.width(width-1);
         }
      }
      /* convert character types to a corresponding integer type */
      using integer = decltype(value + 0);
      if (!(out << static_cast<integer>(value))) return false;
      /* print padding now when it is left adjusted */
      for (int i = 0; i < padding; ++i) {
         out.put(out.widen(' '));
      }
   } else {
      /* neither %c, %d, %o, %x etc. has been given as expected,
         we proceed with default behaviour */
      out << value;
   }
   return !!out;
}

/* special case for bool
   which helps to suppress -Wbool-compare warnings of gcc */
template<typename CharT, typename Traits>
bool print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, bool value) {
   return print_value(out, fseg, static_cast<unsigned int>(value));
}

/* formatted output of CharT strings;
   precision is honoured */
template<typename CharT, typename Traits>
inline bool print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, const CharT* value) {
   if (fseg.flags & is_pointer) {
      /* %p given: print pointer value */
      out << static_cast<const void*>(value);
   } else if (fseg.flags & is_unsigned) {
      /* print it as an unsigned integer value */
      print_value(out, fseg, reinterpret_cast<std::uintptr_t>(value));
   } else if (fseg.flags & is_integer) {
      /* print it as a signed integer value */
      print_value(out, fseg, reinterpret_cast<std::intptr_t>(value));
   } else {
      if (fseg.flags & precision) {
         integer precision = fseg.precision;
         for (integer i = 0; i < precision; ++i) {
            if (!value[i]) {
               precision = i; break;
            }
         }
         integer padding = 0;
         if (fseg.width > precision) {
            padding = fseg.width - precision;
         }
         bool left = (out.flags() & std::ios_base::adjustfield) ==
                  std::ios_base::left;
         if (!left) {
            for (integer i = 0; i < padding; ++i) {
               out.put(out.widen(' '));
            }
         }
         if (precision > 0) {
            out.write(value, precision);
         }
         if (left) {
            for (integer i = 0; i < padding; ++i) {
               out.put(out.widen(' '));
            }
         }
      } else {
         out << value;
      }
   }
   return !!out;
}

/* formatted output of std::nullptr_t strings;
   unfortunately we have no output operator for this type in C++11 */
template<typename CharT, typename Traits>
inline bool print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, std::nullptr_t value) {
   if (fseg.flags & is_pointer) {
      /* %p given: print pointer value */
      out << static_cast<const void*>(value);
      return !!out;
   } else if (fseg.flags & is_unsigned) {
      /* print it as an unsigned integer value */
      print_value(out, fseg, reinterpret_cast<std::uintptr_t>(value));
      return !!out;
   } else if (fseg.flags & is_integer) {
      /* print it as a signed integer value */
      print_value(out, fseg, reinterpret_cast<std::intptr_t>(value));
      return !!out;
   } else {
      /* fail otherwise */
      return false;
   }
}

/* formatted output of char strings that need to be widened;
   precision is honoured */
template<typename CharT, typename Traits>
inline typename std::enable_if<!std::is_same<CharT, char>::value, bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, const char* value) {
   if (fseg.flags & is_pointer) {
      /* %p given: print pointer value */
      out << static_cast<const void*>(value);
   } else if (fseg.flags & is_unsigned) {
      /* print it as an unsigned integer value */
      print_value(out, fseg, reinterpret_cast<std::uintptr_t>(value));
   } else if (fseg.flags & is_integer) {
      /* print it as a signed integer value */
      print_value(out, fseg, reinterpret_cast<std::intptr_t>(value));
   } else {
      integer padding = 0;
      integer len = 0;
      bool left = (out.flags() & std::ios_base::adjustfield) ==
               std::ios_base::left;
      if (fseg.flags & precision) {
         len = fseg.precision;
         for (integer i = 0; i < len; ++i) {
            if (!value[i]) {
               len = i; break;
            }
         }
      } else {
         while (value[len]) ++len;
      }
      if (fseg.width > len) {
         padding = fseg.width - len;
      }
      if (!left) {
         for (integer i = 0; i < padding; ++i) {
            out.put(out.widen(' '));
         }
      }
      for (integer i = 0; i < len; ++i) {
         out.put(out.widen(value[i]));
      }
      if (left) {
         for (integer i = 0; i < padding; ++i) {
            out.put(out.widen(' '));
         }
      }
   }
   return !!out;
}

/* formatted output of strings that need to be converted;
   precision is honoured */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<
   !std::is_same<CharT, Value>::value && is_char<Value>::value,
   bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, const Value* value) {
   if (fseg.flags & is_pointer) {
      /* %p given: print pointer value */
      out << static_cast<const void*>(value);
   } else if (fseg.flags & is_unsigned) {
      /* print it as an unsigned integer value */
      print_value(out, fseg, reinterpret_cast<std::uintptr_t>(value));
   } else if (fseg.flags & is_integer) {
      /* print it as a signed integer value */
      print_value(out, fseg, reinterpret_cast<std::intptr_t>(value));
   } else {
      integer len = 0;
      if (fseg.flags & precision) {
         len = fseg.precision;
         for (integer i = 0; i < len; ++i) {
            if (!value[i]) {
               len = i; break;
            }
         }
      } else {
         while (value[len]) ++len;
      }
      auto& f = std::use_facet<std::codecvt<Value, CharT, std::mbstate_t>>(
         out.getloc());
      std::mbstate_t state{};
      std::basic_string<CharT> converted(len * f.max_length(), 0);
      const Value* from_next;
      CharT* to_next;
      auto result = f.out(state,
         /* from */ value, value + len, from_next,
         /* to */ &converted[0], &converted[converted.size()], to_next);
      if (result == std::codecvt_base::ok) {
         converted.resize(to_next - &converted[0]);
         out << converted;
      } else {
         out.setstate(std::ios_base::failbit);
      }
   }
   return !!out;
}

/* formatted output of non-char pointers that
   have possibly a %p conversion */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<!is_char<Value>::value, bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, const Value* value) {
   if (fseg.flags & is_pointer) {
      /* print the value of the pointer */
      out << static_cast<const void*>(value);
   } else if (fseg.flags & is_unsigned) {
      /* print it as an unsigned integer value */
      print_value(out, fseg, reinterpret_cast<std::uintptr_t>(value));
   } else if (fseg.flags & is_integer) {
      /* print it as a signed integer value */
      print_value(out, fseg, reinterpret_cast<std::intptr_t>(value));
   } else {
      out << value;
   }
   return !!out;
}

/* formatted output of non-const char pointers
   which are delegated to the const char pointer variants */
template<typename CharT, typename Traits, typename Value>
inline typename std::enable_if<is_char<Value>::value, bool>::type
print_value(std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg, Value* value) {
   return print_value(out, fseg, static_cast<const Value*>(value));
}

template<typename CharT, typename Traits>
struct process_value_f {
   process_value_f(std::basic_ostream<CharT, Traits>& out,
         const format_segment<CharT>& fseg) :
         out(out), fseg(fseg) {
   }
   template<typename Value>
   bool operator()(Value&& value) {
      return print_value(out, fseg, std::forward<Value>(value));
   }
   std::basic_ostream<CharT, Traits>& out;
   const format_segment<CharT>& fseg;
};

template<typename Tuple, typename CharT, typename Traits>
inline bool process_value(const Tuple& tuple, integer index,
      std::basic_ostream<CharT, Traits>& out,
      const format_segment<CharT>& fseg) {
   if (index >= 0 &&
         index < static_cast<integer>(std::tuple_size<Tuple>::value)) {
      return apply(tuple, index, process_value_f<CharT, Traits>(out, fseg));
   } else {
      return false;
   }
}

template<typename Value>
inline std::enable_if<std::is_integral<Value>::value &&
   !std::is_const<Value>::value, bool>
set_value(Value* ptr, std::streamsize value) {
   *ptr = value;
   return true;
}

template<typename Value>
inline bool set_value(Value ptr, std::streamsize value) {
   return false;
}

} // namespace impl

template<typename CharT, typename Traits, typename... Values>
inline int printf(std::basic_ostream<CharT, Traits>& out,
      const CharT* format) {
   impl::counting_ostream<CharT, Traits> cout(out);

   while (format) {
      auto fseg = impl::parse_format_segment(format, 0);
      if (!fseg.valid) return -1;
      if (fseg.nof_args > 0) return -1;
      cout.write(fseg.beginp, fseg.endp - fseg.beginp);
      format = fseg.nextp;
   }
   return cout.get_count();
}

template<typename CharT, typename Traits, typename... Values>
inline int printf(std::basic_ostream<CharT, Traits>& out,
      const CharT* format, Values&&... values) {
   impl::counting_ostream<CharT, Traits> cout(out);
   if (cout.getloc() != std::locale::classic()) {
      cout.imbue(std::locale(cout.getloc(), new impl::suppress_grouping()));
   }
   std::tuple<Values&...> tuple(values...);
   impl::integer nof_args = 0;
   while (format) {
      auto fseg = impl::parse_format_segment(format, nof_args);
      if (!fseg.valid) return -1;
      nof_args += fseg.nof_args;
      if (fseg.endp > fseg.beginp) {
         cout.write(fseg.beginp, fseg.endp - fseg.beginp);
         if (!cout) return -1;
      }
      if (fseg.value_index >= 0) {
         if (fseg.conversion == 'n') {
            if (impl::set_value(tuple, fseg.value_index,
                  cout.get_count()) < 0) {
               return -1;
            }
         } else {
            if (fseg.width_index >= 0) {
               fseg.width = impl::get_value(tuple, fseg.width_index);
            }
            if (fseg.precision_index >= 0) {
               fseg.precision = impl::get_value(tuple, fseg.precision_index);
            }
            impl::format_saver<CharT, Traits> fsaver(cout);
            cout.setf(fseg.fmtflags);
            cout.setf(fseg.base == 8? std::ios_base::oct  :
                      fseg.base == 10? std::ios_base::dec :
                      fseg.base == 16? std::ios_base::hex :
                      std::ios_base::fmtflags(0), std::ios_base::basefield);
            if (fseg.width > 0) {
               cout.width(fseg.width);
            }
            if ((fseg.flags & impl::precision) && fseg.precision >= 0) {
               cout.precision(fseg.precision);
            }
            if (fseg.flags & impl::grouping_flag) {
               cout.imbue(std::locale(cout.getloc(),
                  new impl::thousands_grouping()));
            }
            if (!process_value(tuple, fseg.value_index, cout, fseg)) {
               return -1;
            }
         }
      }
      format = fseg.nextp;
   }
   return cout.get_count();
}

template<typename... Values>
inline int printf(const char* format, Values&&... values) {
   return printf(std::cout, format, std::forward<Values>(values)...);
}

template<typename... Values>
inline int printf(const wchar_t* format, Values&&... values) {
   return printf(std::wcout, format, std::forward<Values>(values)...);
}

template<typename... Values>
inline int snprintf(char* s, std::size_t n,
      const char* format, Values&&... values) {
   std::ostringstream os;
   int nbytes = printf(os, format, std::forward<Values>(values)...);
   if (nbytes < 0) return nbytes;
   if (n == 0) return nbytes;
   std::string result(os.str());
   if (nbytes + 1 <= n) {
      std::strcpy(s, result.c_str());
      return nbytes;
   } else {
      std::strcpy(s, result.substr(0, n-1).c_str());
      s[n] = 0;
      return n-1;
   }
}

template<typename... Values>
inline int snprintf(wchar_t* s, std::size_t n,
      const wchar_t* format, Values&&... values) {
   std::wostringstream os;
   int nbytes = printf(os, format, std::forward<Values>(values)...);
   if (nbytes < 0) return nbytes;
   if (n == 0) return nbytes;
   std::wstring result(os.str());
   if (nbytes + 1 <= n) {
      std::wcscpy(s, result.c_str());
      return nbytes;
   } else {
      std::wcscpy(s, result.substr(0, n-1).c_str());
      s[n] = 0;
      return n-1;
   }
}

} // namespace fmt

#endif // of #if __cplusplus < 201103L #else ...
#endif // of #ifndef FMT_PRINTF_HPP