summaryrefslogtreecommitdiffstatshomepage
path: root/src/lib/util/strformat.h
blob: 3bf95a5df290dacba3b5d367757ab62710b356d1 (plain) (blame)
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
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
// license:BSD-3-Clause
// copyright-holders:Vas Crabb
/***************************************************************************

    strformat.h

    type-safe printf substitutes

    This header provides type-safe printf substitutes that output to
    std::ostream- or std::string-like objects.  Most format strings
    supported by C99, SUS, glibc and MSVCRT are accepted.  Not all
    features are implemented, and semantics differ in some cases.  Any
    object with an appropriate stream output operator can be used as
    a format argument with the %s conversion.

    Since the funcitons are implemented using C++ iostream, some
    behaviour more closely resembles iostream output operator behaviour
    than printf behaviour.  You are also exposed to bugs in your C++
    iostream implementation (e.g. hexadecimal scientific format doesn't
    work properly on MinGW).

    These functions are designed to be forgiving - using an
    inappropriate conversion for an argument's type just results in the
    default conversion for the type being used.  Inappropriate types or
    out-of-range positions for parameterised field width and precision
    are treated as if no width/precision was specified.  Out-of-range
    argument positions result in the format specification being printed.

    Position specifiers for arguments (%123$), field width (*456$) and
    precision (.*789$) are supported.  Mixing explicit and implied
    positions for arugments/widths/precisions is discouraged, although
    it does produce deterministic behaviour.

    The following format flags are recognised:
    - "#": alternate format - sets showbase/showpoint, and also
           boolalpha for bool with s conversion
    - "0": pad with zeroes rather than spaces, ignored if '-' flag is
           specified or if precision is specified for d/i/u/o/x/X
           conversion
    - "-": left-align output, overrides '0'
    - " ": recognised but not implemented, ignored for u/o/x/X
           conversion
    - "+": show sign for positive numbers, overrides ' ', ignored for
           u/o/x/X conversions
    - "'": recognised for SUS compatibility but ignored (digit grouping
           is controlled by stream locale)
    - "I": recognised for glibc compatibility but ignored (digits are
           controlled by stream locale)

    Precision is supported for conversions by setting precision on the
    stream.  This works as expected for a/A/e/E/f/F/g/G conversions on
    floating-point types, and may work for objects with user-defined
    stream output operators.  Precision for d/i/u/o/x/X conversions
    (minimum digits to print) is not supported.  Precision for s
    conversions (maximum characters to print) is only honoured for
    string-like types (output character pointer/array and
    std::basic_string).

    Length specifiers are supported but not required for d/i/u/o/x/X
    conversions with integer/char/bool arguments.  They result in the
    value being cast to the desired type before being printed.  Length
    specifiers are ignored for other conversions.

    The following length specifiers are recognised:
    - hh:  cast to char/unsigned char for d/i/u/o/x/X
    - h:   cast to short/unsigned short for d/i/u/o/x/X
    - l:   cast to long/unsigned long for d/i/u/o/x/X
    - ll:  cast to long long/unsigned long long for d/i/u/o/x/X
    - L:   always ignored
    - j:   cast to intmax_t/uintmax_t for d/i/u/o/x/X
    - z:   cast to ssize_t/size_t for d/i/u/o/x/X
    - t:   cast to ptrdiff_t for d/i/u/o/x/X
    - I:   cast to ssize_t/size_t for d/i/u/o/x/X
    - I32: cast to int32_t/uint32_t for d/i/u/o/x/X
    - I64: cast to int64_t/uint64_t for d/i/u/o/x/X
    - w:   always ignored

    The following conversions are recognised:
    - d/i: signed decimal for integer/char/bool types
    - u:   unsigned decimal for integer/char/bool types
    - o:   unsigned octal for integer/char/bool types
    - x/X: lower/upppercase unsigned hexadecimal for integer/char/bool
           types or scientific hexadecimal for floating-point types
    - e/E: lower/uppercase scientific decimal for floating-point types
    - f/F: lower/uppercase fixed-point decimal for floating-point types
    - g/G: default stream output format for floating-point types (may
           differ from printf behaviour)
    - a/A: lower/upppercase scientific hexadecimal for floating-point
           types or hexadecimal for integer types
    - c/C: cast integer types to stream's character type, no automatic
           widening or narrowing
    - s/S: default stream output behaviour for argument
    - p/P: cast any integer/char/bool/pointer/array to void const *
    - m:   output of std::strerror(errno), no automatic widening or
           narrowing, does not consume an argument
    - %:   literal %, field width applied, does not consume an argument

    The output stream type for stream_format must be equivalent to a
    std::basic_ostream for duck-typing purposes.  The output string for
    string type for string_format must provide value_type, traits_type
    and allocator_type declarations, and must be constructible from a
    std::basic_string using the same value, traits and allocator types.

    The format string type can be a pointer to a NUL-terminated string,
    an array containing a NUL-terminated or non-terminated string, or a
    STL contiguous container holding a string (e.g. std::string,
    std::vector or std::array).  Note that NUL characters characters are
    only treated as terminators for pointers and arrays, they are
    treated as normal characters for other containers.  A non-contiguous
    container (e.g. std::list or std::deque) will result in undesirable
    behaviour likely culminating in a crash.

    The value type of the format string and the character type of the
    output stream/string need to match.  You can't use a wchar_t format
    to format char output and vice versa.

    The format string encoding must have contiguous decimal digits.  The
    character encoding must not use shift states or multi-byte sequences
    that could result in a format character codepoint appearing as part
    of a multi-byte sequence or being interpreted differently.  ASCII,
    ISO Latin, KOI-8, UTF-8, EUC, EBCDIC, and UTF-EBCDIC encodings meet
    these requirements, while ISO-2022, UTF-7, KOI-7 and Shift-JIS
    encodings do not.  For character types other than char and wchar_t,
    the encoding must be a strict superset of the char encoding.

    The following conditions cause assertion failures in debug builds:
    - Unsupported conversion specifier
    - Out-of-range argument/width/precision position
    - Inappropriate type for parameterised width/precision
    - Positional width/precision specifier not terminated with $

    Some limitations have been described in passing.  Major limitations
    and bugs include:
    - No automatic widening/narrowing support, so no simple way to
      output wide characters/strings to narrow streams/strings and vice
      versa.
    - No support for n conversion (store characters printed so far)
    - Precision ignored for d/i/u/o/x/X conversions (should set minimum
      digits to print).
    - Precisoin for s/S conversion is only honoured for string-like
      types (output character pointer/array and std::basic_string).
    - If the output character type is not char, signed char or unsgined
      char, printing the a value of this type with d/i/u/o/x/X
      conversion and no length specifier causes it to be printed as a
      character.  Can be worked around by casting to another integer
      type or using length specifier.
    - Printing with d/i/u/o/x/X conversions may not behave as expected
      if the output character type is an integer type other than char,
      signed char, unsigned char, or wchar_t.
    - Only output character pointer/array is treated as a C string, any
      other pointer/array will be printed as a pointer value.  The
      signed/unsigned/default char are not handled equivalently.
    - There is no length specifier to force cast to int/unsigned.  Can
      be worked around by casting the argument.
    - MSVCRT length specifiers I/I32/I64 will not be recognised if no
      width or precision is specified, as they will be mistaken for
      glibc alternate digits flag.
    - The " " flag to prefix positive numbers with a space is not
      implemented.
    - The "'" and "I" flags are not implemented, as digit grouping and
      characters are controlled by the output stream's locale.
    - The characters used for space- and zero-padding are not locale-
      aware.

***************************************************************************/

#pragma once

#ifndef __MAME_UTIL_STRFORMAT_H__
#define __MAME_UTIL_STRFORMAT_H__

#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <limits>
#include <locale>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>


namespace detail {
template <typename Character>
class format_chars
{
public:
	typedef Character char_type;
	enum : Character {
			nul         = Character('\0'),
			space       = Character(' '),
			point       = Character('.'),
			percent     = Character('%'),
			dollar      = Character('$'),
			hash        = Character('#'),
			minus       = Character('-'),
			plus        = Character('+'),
			asterisk    = Character('*'),
			quote       = Character('\''),
			zero        = Character('0'),
			nine        = Character('9'),
			a           = Character('a'),
			A           = Character('A'),
			c           = Character('c'),
			C           = Character('C'),
			d           = Character('d'),
			e           = Character('e'),
			E           = Character('E'),
			f           = Character('f'),
			F           = Character('F'),
			g           = Character('g'),
			G           = Character('G'),
			h           = Character('h'),
			i           = Character('i'),
			I           = Character('I'),
			j           = Character('j'),
			l           = Character('l'),
			L           = Character('L'),
			m           = Character('m'),
			o           = Character('o'),
			p           = Character('p'),
			s           = Character('s'),
			S           = Character('S'),
			t           = Character('t'),
			u           = Character('u'),
			w           = Character('w'),
			x           = Character('x'),
			X           = Character('X'),
			z           = Character('z')
		};
};

template <>
class format_chars<wchar_t>
{
public:
	typedef wchar_t char_type;
	enum : wchar_t {
			nul         = L'\0',
			space       = L' ',
			point       = L'.',
			percent     = L'%',
			dollar      = L'$',
			hash        = L'#',
			minus       = L'-',
			plus        = L'+',
			asterisk    = L'*',
			quote       = L'\'',
			zero        = L'0',
			nine        = L'9',
			a           = L'a',
			A           = L'A',
			c           = L'c',
			C           = L'C',
			d           = L'd',
			e           = L'e',
			E           = L'E',
			f           = L'f',
			F           = L'F',
			g           = L'g',
			G           = L'G',
			h           = L'h',
			i           = L'i',
			I           = L'I',
			j           = L'j',
			l           = L'l',
			L           = L'L',
			m           = L'm',
			o           = L'o',
			p           = L'p',
			s           = L's',
			S           = L'S',
			t           = L't',
			u           = L'u',
			w           = L'w',
			x           = L'x',
			X           = L'X',
			z           = L'z'
		};
};

class format_flags
{
public:
	enum class positive_sign {
			none,
			space,                      // ' '
			plus                        // +
		};

	enum class length {
			unspecified,
			character,                  // hh
			short_integer,              // h
			long_integer,               // l
			long_long_integer,          // ll
			long_double,                // L
			integer_maximum,            // j
			size_type,                  // z, I
			pointer_difference,         // t
			integer_32,                 // I32
			integer_64,                 // I64
			wide_character              // w
		};

	enum class conversion {
			unspecified,
			signed_decimal,             // i, d
			unsigned_decimal,           // u
			octal,                      // o
			hexadecimal,                // x, X
			scientific_decimal,         // e, E
			fixed_decimal,              // f, F
			floating_decimal,           // g, G
			scientific_hexadecimal,     // a, A
			character,                  // c, C
			string,                     // s, S
			pointer,                    // p
			strerror,                   // m
			percent                     // %
		};

	format_flags()
		: m_alternate_format(false)
		, m_zero_pad(false)
		, m_left_align(false)
		, m_positive_sign(positive_sign::none)
		, m_digit_grouping(false)
		, m_alternate_digits(false)
		, m_field_width(0)
		, m_precision(-1)
		, m_length(length::unspecified)
		, m_uppercase(false)
		, m_conversion(conversion::unspecified)
	{
	}

	template <typename Stream> void apply(Stream &stream) const
	{
		typedef format_chars<typename Stream::char_type> chars;

		stream.unsetf(
				Stream::basefield |
				Stream::adjustfield |
				Stream::floatfield |
				Stream::boolalpha |
				Stream::showbase |
				Stream::showpoint |
				Stream::showpos |
				Stream::uppercase);

		if (get_alternate_format()) stream.setf(Stream::showbase | Stream::showpoint);
		stream.fill(get_zero_pad() ? chars::zero : chars::space);
		stream.setf(get_left_align() ? Stream::left : get_zero_pad() ? Stream::internal : Stream::right);
		if (positive_sign::plus == get_positive_sign()) stream.setf(Stream::showpos);
		stream.precision((get_precision() < 0) ? 6 : get_precision());
		stream.width(get_field_width());
		if (get_uppercase()) stream.setf(Stream::uppercase);
		switch (get_conversion())
		{
		case conversion::unspecified:
			break;
		case conversion::signed_decimal:
		case conversion::unsigned_decimal:
			stream.setf(Stream::dec);
			break;
		case conversion::octal:
			stream.setf(Stream::oct);
			break;
		case conversion::hexadecimal:
			stream.setf(Stream::hex | Stream::scientific | Stream::fixed);
			break;
		case conversion::scientific_decimal:
			stream.setf(Stream::dec | Stream::scientific);
			break;
		case conversion::fixed_decimal:
			stream.setf(Stream::dec | Stream::fixed);
			break;
		case conversion::floating_decimal:
			stream.setf(Stream::dec);
			break;
		case conversion::scientific_hexadecimal:
			stream.setf(Stream::hex | Stream::scientific | Stream::fixed);
			break;
		case conversion::character:
		case conversion::string:
		case conversion::pointer:
		case conversion::strerror:
		case conversion::percent:
			break;
		}
	}

	bool            get_alternate_format() const    { return m_alternate_format; }
	bool            get_zero_pad() const            { return m_zero_pad; }
	bool            get_left_align() const          { return m_left_align; }
	positive_sign   get_positive_sign() const       { return m_positive_sign; }
	bool            get_digit_grouping() const      { return m_digit_grouping; }
	bool            get_alternate_digits() const    { return m_alternate_digits; }
	unsigned        get_field_width() const         { return m_field_width; }
	int             get_precision() const           { return m_precision; }
	length          get_length() const              { return m_length; }
	bool            get_uppercase() const           { return m_uppercase; }
	conversion      get_conversion() const          { return m_conversion; }

	void set_alternate_format()
	{
		m_alternate_format = true;
	}

	void set_zero_pad()
	{
		if (!m_left_align)
		{
			switch (m_conversion)
			{
			case conversion::signed_decimal:
			case conversion::unsigned_decimal:
			case conversion::octal:
			case conversion::hexadecimal:
				m_zero_pad = (0 > m_precision);
				break;
			default:
				m_zero_pad = true;
			}
		}
	}

	void set_left_align()
	{
		m_zero_pad = false;
		m_left_align = true;
	}

	void set_positive_sign_space()
	{
		switch (m_conversion)
		{
		case conversion::unsigned_decimal:
		case conversion::octal:
		case conversion::hexadecimal:
			break;
		default:
			if (positive_sign::plus != m_positive_sign)
				m_positive_sign = positive_sign::space;
		}
	}

	void set_positive_sign_plus()
	{
		switch (m_conversion)
		{
		case conversion::unsigned_decimal:
		case conversion::octal:
		case conversion::hexadecimal:
			break;
		default:
			m_positive_sign = positive_sign::plus;
		}
	}

	void set_digit_grouping()
	{
		m_digit_grouping = true;
	}

	void set_alternate_digits()
	{
		m_alternate_digits = true;
	}

	void set_field_width(int value)
	{
		if (0 > value)
		{
			set_left_align();
			m_field_width = unsigned(-value);
		}
		else
		{
			m_field_width = unsigned(value);
		}
	}

	void set_precision(int value)
	{
		m_precision = value;
		if (0 <= value)
		{
			switch (m_conversion)
			{
			case conversion::signed_decimal:
			case conversion::unsigned_decimal:
			case conversion::octal:
			case conversion::hexadecimal:
				m_zero_pad = false;
				break;
			default:
				break;
			}
		}
	}

	void set_length(length value)
	{
		m_length = value;
	}

	void set_uppercase()
	{
		m_uppercase = true;
	}

	void set_conversion(conversion value)
	{
		m_conversion = value;
		switch (value)
		{
		case conversion::unsigned_decimal:
		case conversion::octal:
		case conversion::hexadecimal:
			m_positive_sign = positive_sign::none;
		case conversion::signed_decimal:
			if (0 <= m_precision)
				m_zero_pad = false;
			break;
		default:
			break;
		}
	}

private:
	bool            m_alternate_format; // #
	bool            m_zero_pad;         // 0
	bool            m_left_align;       // -
	positive_sign   m_positive_sign;    // ' ', +
	bool            m_digit_grouping;   // '
	bool            m_alternate_digits; // I
	unsigned        m_field_width;
	int             m_precision;        // .
	length          m_length;           // hh, h, l, ll, L, j, z, I, t, w
	bool            m_uppercase;        // X, E, F, G, A
	conversion      m_conversion;       // i, d, u, o, x, X, e, E, f, F, g, G, a, A, c, C, s, S, p, m, %
};

template <typename Format>
class format_helper_base : public format_chars<std::remove_cv_t<std::remove_reference_t<decltype(*std::cbegin(std::declval<Format>()))> > >
{
public:
	typedef std::remove_reference_t<decltype(std::cbegin(std::declval<Format>()))> iterator;
	static iterator begin(Format const &fmt) { return std::cbegin(fmt); }
	static bool at_end(Format const &fmt, iterator const &it) { return std::cend(fmt) == it; }
};

template <typename Character>
class format_helper_base<Character *> : public format_chars<std::remove_cv_t<Character> >
{
public:
	typedef Character const *iterator;
	static iterator begin(Character const *fmt) { return fmt; }
	static bool at_end(Character const *fmt, iterator const &it) { return format_helper_base::nul == *it; }
};

template <typename Character, std::size_t Length>
class format_helper_base<Character [Length]> : public format_chars<std::remove_cv_t<Character> >
{
public:
	typedef Character const *iterator;
	static iterator begin(Character (&fmt)[Length]) { return std::cbegin(fmt); }
	static iterator begin(Character const (&fmt)[Length]) { return std::cbegin(fmt); }
	static bool at_end(Character (&fmt)[Length], iterator const &it) { return (std::cend(fmt) == it) || (format_chars<Character>::nul == *it); }
	static bool at_end(Character const (&fmt)[Length], iterator const &it) { return (std::cend(fmt) == it) || (format_helper_base::nul == *it); }
};

template <typename Format>
class format_helper : public format_helper_base<Format>
{
public:
	static bool parse_format(
			Format const &fmt,
			typename format_helper::iterator &it,
			format_flags &flags,
			int &next_position,
			int &argument_position,
			int &width_position,
			int &precision_position)
	{
		static_assert((format_helper::nine - format_helper::zero) == 9, "Digits must be contiguous");
		assert(!format_helper::at_end(fmt, it));
		assert(format_helper::percent == *it);

		int num;
		int nxt(next_position);
		++it;
		flags = format_flags();
		argument_position = -1;
		width_position = -1;
		precision_position = -1;

		// Leading zeroes are tricky - they could be a zero-pad flag or part of a position specifier
		bool const leading_zero(!format_helper::at_end(fmt, it) && (format_helper::zero == *it));
		while (!format_helper::at_end(fmt, it) && (format_helper::zero == *it)) ++it;

		// Digits encountered at this point could be a field width or a position specifier
		num = 0;
		bool leading_num(have_digit(fmt, it));
		while (have_digit(fmt, it)) add_digit(num, *it++);
		if (leading_num && !have_dollar(fmt, it))
		{
			// No dollar sign, leading number is field width
			if (leading_zero) flags.set_zero_pad();
			flags.set_field_width(num);
		}
		else
		{
			// If we hit a dollar sign after a number, that's a position specifier
			if ((leading_zero || leading_num) && have_dollar(fmt, it))
			{
				argument_position = num;
				++it;
			}
			else if (leading_zero)
			{
				flags.set_zero_pad();
			}

			// Parse flag characters
			while (!format_helper::at_end(fmt, it))
			{
				switch (*it)
				{
				case format_helper::hash:   ++it;   flags.set_alternate_format();       continue;
				case format_helper::zero:   ++it;   flags.set_zero_pad();               continue;
				case format_helper::minus:  ++it;   flags.set_left_align();             continue;
				case format_helper::space:  ++it;   flags.set_positive_sign_space();    continue;
				case format_helper::plus:   ++it;   flags.set_positive_sign_plus();     continue;
				case format_helper::quote:  ++it;   flags.set_digit_grouping();         continue;
				case format_helper::I:      ++it;   flags.set_alternate_digits();       continue;
				default: break;
				}
				break;
			}

			// Check for literal or parameterised field width
			if (!format_helper::at_end(fmt, it))
			{
				if (is_digit(*it))
				{
					flags.set_field_width(read_number(fmt, it));
				}
				else if (format_helper::asterisk == *it)
				{
					++it;
					if (have_digit(fmt, it))
					{
						num = read_number(fmt, it);
						assert(have_dollar(fmt, it)); // invalid positional width
						if (!have_dollar(fmt, it)) return false;
						width_position = num;
						nxt = width_position + 1;
						++it;
					}
					else
					{
						width_position = nxt++;
					}
				}
			}
		}

		// Check for literal or parameterised precision
		if (!format_helper::at_end(fmt, it) && (*it == format_helper::point))
		{
			++it;
			if (have_digit(fmt, it))
			{
				flags.set_precision(read_number(fmt, it));
			}
			else if (!format_helper::at_end(fmt, it) && (format_helper::asterisk == *it))
			{
				++it;
				if (have_digit(fmt, it))
				{
					num = read_number(fmt, it);
					assert(have_dollar(fmt, it)); // invalid positional precision
					if (!have_dollar(fmt, it)) return false;
					precision_position = num;
					nxt = precision_position + 1;
					++it;
				}
				else
				{
					precision_position = nxt++;
				}
			}
			else
			{
				flags.set_precision(0);
			}
		}

		// Check for length modifiers
		if (!format_helper::at_end(fmt, it)) switch (*it)
		{
		case format_helper::h:
			++it;
			if (!format_helper::at_end(fmt, it) && (format_helper::h == *it))
			{
				++it;
				flags.set_length(format_flags::length::character);
			}
			else
			{
				flags.set_length(format_flags::length::short_integer);
			}
			break;
		case format_helper::l:
			++it;
			if (!format_helper::at_end(fmt, it) && (format_helper::l == *it))
			{
				++it;
				flags.set_length(format_flags::length::long_long_integer);
			}
			else
			{
				flags.set_length(format_flags::length::long_integer);
			}
			break;
		case format_helper::L:
			++it;
			flags.set_length(format_flags::length::long_double);
			break;
		case format_helper::j:
			++it;
			flags.set_length(format_flags::length::integer_maximum);
			break;
		case format_helper::z:
			++it;
			flags.set_length(format_flags::length::size_type);
			break;
		case format_helper::t:
			++it;
			flags.set_length(format_flags::length::pointer_difference);
			break;
		case format_helper::I:
			{
				++it;
				format_flags::length length = format_flags::length::size_type;
				if (!format_helper::at_end(fmt, it))
				{
					if ((typename format_helper::char_type(format_helper::zero) + 3) == *it)
					{
						typename format_helper::iterator tmp(it);
						++tmp;
						if (!format_helper::at_end(fmt, tmp) && ((typename format_helper::char_type(format_helper::zero) + 2) == *tmp))
						{
							length = format_flags::length::integer_32;
							it = ++tmp;
						}
					}
					else if ((typename format_helper::char_type(format_helper::zero) + 6) == *it)
					{
						typename format_helper::iterator tmp(it);
						++tmp;
						if (!format_helper::at_end(fmt, tmp) && ((typename format_helper::char_type(format_helper::zero) + 4) == *tmp))
						{
							length = format_flags::length::integer_64;
							it = ++tmp;
						}
					}
				}
				flags.set_length(length);
			}
			break;
		case format_helper::w:
			++it;
			flags.set_length(format_flags::length::wide_character);
			break;
		default:
			break;
		}

		// Now we should find a conversion specifier
		assert(!format_helper::at_end(fmt, it)); // missing conversion
		if (format_helper::at_end(fmt, it)) return false;
		switch (*it)
		{
		case format_helper::d:
		case format_helper::i:
			flags.set_conversion(format_flags::conversion::signed_decimal);
			break;
		case format_helper::o:
			flags.set_conversion(format_flags::conversion::octal);
			break;
		case format_helper::u:
			flags.set_conversion(format_flags::conversion::unsigned_decimal);
			break;
		case format_helper::X:
			flags.set_uppercase();
		case format_helper::x:
			flags.set_conversion(format_flags::conversion::hexadecimal);
			break;
		case format_helper::E:
			flags.set_uppercase();
		case format_helper::e:
			flags.set_conversion(format_flags::conversion::scientific_decimal);
			break;
		case format_helper::F:
			flags.set_uppercase();
		case format_helper::f:
			flags.set_conversion(format_flags::conversion::fixed_decimal);
			break;
		case format_helper::G:
			flags.set_uppercase();
		case format_helper::g:
			flags.set_conversion(format_flags::conversion::floating_decimal);
			break;
		case format_helper::A:
			flags.set_uppercase();
		case format_helper::a:
			flags.set_conversion(format_flags::conversion::scientific_hexadecimal);
			break;
		case format_helper::C:
			if (format_flags::length::unspecified == flags.get_length())
				flags.set_length(format_flags::length::long_integer);
		case format_helper::c:
			flags.set_conversion(format_flags::conversion::character);
			break;
		case format_helper::S:
			if (format_flags::length::unspecified == flags.get_length())
				flags.set_length(format_flags::length::long_integer);
		case format_helper::s:
			flags.set_conversion(format_flags::conversion::string);
			break;
		case format_helper::p:
			flags.set_conversion(format_flags::conversion::pointer);
			break;
		case format_helper::m:
			flags.set_conversion(format_flags::conversion::strerror);
			break;
		case format_helper::percent:
			flags.set_conversion(format_flags::conversion::percent);
			break;
		default:
			assert(false); // unsupported conversion
			return false;
		}
		++it;

		// Finalise argument position
		if (argument_position < 0) argument_position = nxt;
		next_position = argument_position;
		switch (flags.get_conversion())
		{
		case format_flags::conversion::strerror:
		case format_flags::conversion::percent:
			break;
		default:
			++next_position;
		}
		return true;
	}

private:
	static bool have_dollar(Format const &fmt, typename format_helper::iterator const &it)
	{
		return !format_helper::at_end(fmt, it) && (*it == format_helper::dollar);
	}

	static bool have_digit(Format const &fmt, typename format_helper::iterator const &it)
	{
		return !format_helper::at_end(fmt, it) && is_digit(*it);
	}

	static bool is_digit(typename format_helper::char_type value)
	{
		return (format_helper::zero <= value) && (format_helper::nine >= value);
	}

	static int digit_value(typename format_helper::char_type value)
	{
		assert(is_digit(value));
		return int(std::make_signed_t<decltype(value)>(value - format_helper::zero));
	}

	static void add_digit(int &num, typename format_helper::char_type digit)
	{
		num = (num * 10) + digit_value(digit);
	}

	static int read_number(Format const &fmt, typename format_helper::iterator &it)
	{
		assert(have_digit(fmt, it));
		int value = 0;
		do add_digit(value, *it++); while (have_digit(fmt, it));
		return value;
	}
};

template <typename Stream, typename T>
class format_output
{
private:
	template <typename U> struct signed_integer_semantics
	{ static constexpr bool value = std::is_integral<U>::value && std::is_signed<U>::value; };
	template <typename U> struct unsigned_integer_semantics
	{ static constexpr bool value = std::is_integral<U>::value && !std::is_signed<U>::value; };
	template <typename U> struct default_semantics
	{ static constexpr bool value = !signed_integer_semantics<U>::value && !unsigned_integer_semantics<U>::value; };

public:
	template <typename U>
	static void apply(std::enable_if_t<signed_integer_semantics<U>::value, Stream> &str, format_flags const &flags, U const &value)
	{
		switch (flags.get_conversion())
		{
		case format_flags::conversion::signed_decimal:
			switch (flags.get_length())
			{
			case format_flags::length::character:
				str << int(static_cast<signed char>(value));
				break;
			case format_flags::length::short_integer:
				str << short(value);
				break;
			case format_flags::length::long_integer:
				str << long(value);
				break;
			case format_flags::length::long_long_integer:
				str << static_cast<long long>(value);
				break;
			case format_flags::length::integer_maximum:
				str << std::intmax_t(value);
				break;
			case format_flags::length::size_type:
				str << std::make_signed_t<std::size_t>(value);
				break;
			case format_flags::length::pointer_difference:
				str << std::make_signed_t<std::ptrdiff_t>(value);
				break;
			case format_flags::length::integer_32:
				str << std::uint32_t(std::int32_t(value));
				break;
			case format_flags::length::integer_64:
				str << std::int64_t(value);
				break;
			default:
				if (std::is_same<std::make_signed_t<U>, std::make_signed_t<char> >::value)
					str << int(value);
				else
					str << value;
			}
			break;
		case format_flags::conversion::unsigned_decimal:
		case format_flags::conversion::octal:
		case format_flags::conversion::hexadecimal:
			switch (flags.get_length())
			{
			case format_flags::length::character:
				str << unsigned(static_cast<unsigned char>(static_cast<signed char>(value)));
				break;
			case format_flags::length::short_integer:
				str << static_cast<unsigned short>(short(value));
				break;
			case format_flags::length::long_integer:
				str << static_cast<unsigned long>(long(value));
				break;
			case format_flags::length::long_long_integer:
				str << static_cast<unsigned long long>(static_cast<long long>(value));
				break;
			case format_flags::length::integer_maximum:
				str << std::uintmax_t(std::intmax_t(value));
				break;
			case format_flags::length::size_type:
				str << std::make_unsigned_t<std::size_t>(std::make_signed_t<std::size_t>(value));
				break;
			case format_flags::length::pointer_difference:
				str << std::make_unsigned_t<std::ptrdiff_t>(std::make_signed_t<std::ptrdiff_t>(value));
				break;
			case format_flags::length::integer_32:
				str << std::uint32_t(std::int32_t(value));
				break;
			case format_flags::length::integer_64:
				str << std::uint64_t(std::int64_t(value));
				break;
			default:
				if (std::is_same<std::make_unsigned_t<U>, std::make_unsigned_t<char> >::value)
					str << unsigned(std::make_unsigned_t<U>(value));
				else
					str << std::make_unsigned_t<U>(value);
			}
			break;
		case format_flags::conversion::character:
			if (std::is_signed<typename Stream::char_type>::value)
				str << typename Stream::char_type(value);
			else
				str << typename Stream::char_type(std::make_signed_t<typename Stream::char_type>(value));
			break;
		case format_flags::conversion::pointer:
			str << reinterpret_cast<void const *>(std::uintptr_t(std::intptr_t(value)));
			break;
		default:
			str << value;
		}
	}
	template <typename U>
	static void apply(std::enable_if_t<unsigned_integer_semantics<U>::value, Stream> &str, format_flags const &flags, U const &value)
	{
		switch (flags.get_conversion())
		{
		case format_flags::conversion::signed_decimal:
			switch (flags.get_length())
			{
			case format_flags::length::character:
				str << int(static_cast<signed char>(static_cast<unsigned char>(value)));
				break;
			case format_flags::length::short_integer:
				str << short(static_cast<unsigned short>(value));
				break;
			case format_flags::length::long_integer:
				str << long(static_cast<unsigned long>(value));
				break;
			case format_flags::length::long_long_integer:
				str << static_cast<long long>(static_cast<unsigned long long>(value));
				break;
			case format_flags::length::integer_maximum:
				str << std::intmax_t(std::uintmax_t(value));
				break;
			case format_flags::length::size_type:
				str << std::make_signed_t<std::size_t>(std::make_unsigned_t<std::size_t>(value));
				break;
			case format_flags::length::pointer_difference:
				str << std::make_signed_t<std::ptrdiff_t>(std::make_unsigned_t<std::ptrdiff_t>(value));
				break;
			case format_flags::length::integer_32:
				str << std::int32_t(std::uint32_t(value));
				break;
			case format_flags::length::integer_64:
				str << std::int64_t(std::uint64_t(value));
				break;
			default:
				if (std::is_same<std::make_signed_t<U>, std::make_signed_t<char> >::value)
					str << int(std::make_signed_t<U>(value));
				else
					str << std::make_signed_t<U>(value);
			}
			break;
		case format_flags::conversion::unsigned_decimal:
		case format_flags::conversion::octal:
		case format_flags::conversion::hexadecimal:
			switch (flags.get_length())
			{
			case format_flags::length::character:
				str << unsigned(static_cast<unsigned char>(value));
				break;
			case format_flags::length::short_integer:
				str << static_cast<unsigned short>(value);
				break;
			case format_flags::length::long_integer:
				str << static_cast<unsigned long>(value);
				break;
			case format_flags::length::long_long_integer:
				str << static_cast<unsigned long long>(value);
				break;
			case format_flags::length::integer_maximum:
				str << std::uintmax_t(value);
				break;
			case format_flags::length::size_type:
				str << std::make_unsigned_t<std::size_t>(value);
				break;
			case format_flags::length::pointer_difference:
				str << std::make_unsigned_t<std::ptrdiff_t>(value);
				break;
			case format_flags::length::integer_32:
				str << std::uint32_t(std::int32_t(value));
				break;
			case format_flags::length::integer_64:
				str << std::int64_t(value);
				break;
			default:
				if (std::is_same<std::make_unsigned_t<U>, std::make_unsigned_t<char> >::value)
					str << unsigned(value);
				else
					str << value;
			}
			break;
		case format_flags::conversion::character:
			if (std::is_signed<typename Stream::char_type>::value)
				str << typename Stream::char_type(value);
			else
				str << typename Stream::char_type(std::make_signed_t<typename Stream::char_type>(value));
			break;
		case format_flags::conversion::pointer:
			str << reinterpret_cast<void const *>(std::uintptr_t(value));
			break;
		default:
			str << value;
		}
	}
	template <typename U>
	static void apply(std::enable_if_t<default_semantics<U>::value, Stream> &str, format_flags const &flags, U const &value)
	{
		str << value;
	}
	static void apply(Stream &str, format_flags const &flags, bool value)
	{
		switch (flags.get_conversion())
		{
		case format_flags::conversion::signed_decimal:
		case format_flags::conversion::unsigned_decimal:
		case format_flags::conversion::octal:
		case format_flags::conversion::hexadecimal:
		case format_flags::conversion::scientific_decimal:
		case format_flags::conversion::fixed_decimal:
		case format_flags::conversion::floating_decimal:
		case format_flags::conversion::scientific_hexadecimal:
		case format_flags::conversion::character:
		case format_flags::conversion::pointer:
			apply(str, flags, unsigned(value));
			break;
		default:
			if (flags.get_alternate_format()) str.setf(Stream::boolalpha);
			str << value;
		}
	}
	template <typename CharT, typename Traits, typename Allocator>
	static void apply(std::enable_if_t<std::is_same<CharT, typename Stream::char_type>::value, Stream> &str, format_flags const &flags, std::basic_string<CharT, Traits, Allocator> const &value)
	{
		int const precision(flags.get_precision());
		if ((0 <= precision) && (value.size() > unsigned(precision)))
		{
			unsigned width(flags.get_field_width());
			bool const pad(unsigned(precision) < width);
			typename Stream::fmtflags const adjust(str.flags() & Stream::adjustfield);
			if (!pad || (Stream::left == adjust)) str.write(&*value.begin(), unsigned(precision));
			if (pad)
			{
				for (width -= precision; 0U < width; --width) str.put(str.fill());
				if (Stream::left != adjust) str.write(&*value.begin(), unsigned(precision));
			}
			str.width(0);
		}
		else
		{
			str << value;
		}
	}
	template <typename CharT, typename Traits, typename Allocator>
	static void apply(std::enable_if_t<!std::is_same<CharT, typename Stream::char_type>::value, Stream> &str, format_flags const &flags, std::basic_string<CharT, Traits, Allocator> const &value)
	{
		int const precision(flags.get_precision());
		if ((0 <= precision) && (value.size() > unsigned(precision)))
			str << value.substr(0, unsigned(precision));
		else
			str << value;
	}
};

template <typename Stream, typename T>
class format_output<Stream, T *>
{
protected:
	template <typename U> struct string_semantics
	{ static constexpr bool value = std::is_same<std::remove_const_t<U>, typename Stream::char_type>::value; };

public:
	template <typename U>
	static void apply(std::enable_if_t<string_semantics<U>::value, Stream> &str, format_flags const &flags, U const *value)
	{
		switch (flags.get_conversion())
		{
		case format_flags::conversion::string:
			{
				int precision(flags.get_precision());
				if (0 <= flags.get_precision())
				{
					std::streamsize cnt(0);
					for ( ; (0 < precision) && (U(format_chars<U>::nul) != value[cnt]); --precision, ++cnt) { }
					unsigned width(flags.get_field_width());
					bool const pad(std::make_unsigned_t<std::streamsize>(cnt) < width);
					typename Stream::fmtflags const adjust(str.flags() & Stream::adjustfield);
					if (!pad || (Stream::left == adjust)) str.write(value, cnt);
					if (pad)
					{
						for (width -= cnt; 0U < width; --width) str.put(str.fill());
						if (Stream::left != adjust) str.write(value, cnt);
					}
					str.width(0);
				}
				else
				{
					str << value;
				}
			}
			break;
		case format_flags::conversion::pointer:
			str << reinterpret_cast<void const *>(const_cast<std::remove_volatile_t<U> *>(value));
			break;
		default:
			str << value;
		}
	}
	template <typename U>
	static void apply(std::enable_if_t<!string_semantics<U>::value, Stream> &str, format_flags const &flags, U const *value)
	{
		str << reinterpret_cast<void const *>(const_cast<std::remove_volatile_t<U> *>(value));
	}
};

template <typename Stream, typename T, std::size_t N>
class format_output<Stream, T[N]> : protected format_output<Stream, T *>
{
public:
	template <typename U>
	static void apply(Stream &str, format_flags const &flags, U const *value)
	{
		static_assert(
				!format_output::template string_semantics<U>::value || (N <= size_t(unsigned((std::numeric_limits<int>::max)()))),
				"C string array length must not exceed maximum integer value");
		format_flags f(flags);
		if (format_output::template string_semantics<U>::value && ((0 > f.get_precision()) || (N < unsigned(f.get_precision()))))
			f.set_precision(int(unsigned(N)));
		format_output<Stream, T *>::apply(str, f, value);
	}
};

template <typename T>
class format_make_integer
{
private:
	template <typename U> struct use_unsigned_cast
	{ static constexpr bool value = std::is_convertible<U const, unsigned>::value && std::is_unsigned<U>::value; };
	template <typename U> struct use_signed_cast
	{ static constexpr bool value = !use_unsigned_cast<U>::value && std::is_convertible<U const, int>::value; };
	template <typename U> struct disable
	{ static constexpr bool value = !use_unsigned_cast<U>::value && !use_signed_cast<U>::value; };

public:
	template <typename U> static std::enable_if_t<use_unsigned_cast<U>::value, bool> apply(U const &value, int &result)
	{
		result = int(unsigned(value));
		return true;
	}
	template <typename U> static std::enable_if_t<use_signed_cast<U>::value, bool> apply(U const &value, int &result)
	{
		result = int(value);
		return true;
	}
	template <typename U> static std::enable_if_t<disable<U>::value, bool> apply(U const &value, int &result)
	{
		return false;
	}
};

template <typename Stream>
class format_argument
{
public:
	format_argument()
		: m_value(nullptr)
		, m_output_function(nullptr)
		, m_make_integer_function(nullptr)
	{
	}

	template <typename T>
	format_argument(T const &value)
		: m_value(reinterpret_cast<void const *>(&value))
		, m_output_function(&static_output<T>)
		, m_make_integer_function(&static_make_integer<T>)
	{
	}

	void output(Stream &str, format_flags const &flags) const { m_output_function(str, flags, m_value); }
	bool make_integer(int &result) const { return m_make_integer_function(m_value, result); }

private:
	typedef void (*output_function)(Stream &str, format_flags const &flags, void const *value);
	typedef bool (*make_integer_function)(void const *value, int &result);

	template <typename T> static void static_output(Stream &str, format_flags const &flags, void const *value)
	{
		format_output<Stream, T>::apply(str, flags, *reinterpret_cast<T const *>(value));
	}

	template <typename T> static bool static_make_integer(void const *value, int &result)
	{
		return format_make_integer<T>::apply(*reinterpret_cast<T const *>(value), result);
	}

	void const              *m_value;
	output_function         m_output_function;
	make_integer_function   m_make_integer_function;
};

template <typename Stream, typename... Params>
inline std::array<format_argument<Stream>, sizeof...(Params)> make_format_arguments(Params &&... args)
{
	return std::array<format_argument<Stream>, sizeof...(Params)>({ { format_argument<Stream>(std::forward<Params>(args))... } });
}

template <typename Stream, typename Format, std::size_t Count>
void stream_format(Stream &str, Format const &fmt, std::array<format_argument<Stream>, Count> const &args)
{
	typedef format_helper<std::remove_reference_t<Format> > format_helper;
	typedef typename format_helper::iterator iterator;
	class stream_preserver
	{
	public:
		stream_preserver(Stream &stream)
			: m_stream(stream)
			, m_fill(stream.fill())
			, m_flags(stream.flags())
			, m_precision(stream.precision())
			, m_width(stream.width())
		{
		}
		~stream_preserver()
		{
			m_stream.width(m_width);
			m_stream.precision(m_precision);
			m_stream.flags(m_flags);
			m_stream.fill(m_fill);
		}
	private:
		Stream                      &m_stream;
		typename Stream::char_type  m_fill;
		typename Stream::fmtflags   m_flags;
		std::streamsize             m_precision;
		std::streamsize             m_width;
	};

	stream_preserver preserver(str);
	int next_pos(1);
	iterator start = format_helper::begin(fmt);
	for (iterator it = start; !format_helper::at_end(fmt, start); )
	{
		while (!format_helper::at_end(fmt, it) && (format_helper::percent != *it)) ++it;
		if (start != it)
		{
			str.write(&*start, it - start);
			start = it;
		}
		if (!format_helper::at_end(fmt, it))
		{
			// Try to parse a percent format specification
			format_flags flags;
			int arg_pos, width_pos, prec_pos;
			if (!format_helper::parse_format(fmt, it, flags, next_pos, arg_pos, width_pos, prec_pos))
				continue;

			// Handle parameterised width
			if (0 <= width_pos)
			{
				assert(flags.get_field_width() == 0U);
				assert(0 < width_pos);
				assert(args.size() >= unsigned(width_pos));
				if ((0 < width_pos) && (args.size() >= unsigned(width_pos)))
				{
					int width;
					if (args[width_pos - 1].make_integer(width))
					{
						if (0 > width)
						{
							flags.set_left_align();
							flags.set_field_width(unsigned(-width));
						}
						else
						{
							flags.set_field_width(unsigned(width));
						}
					}
					else
					{
						assert(false); // inappropriate type passed as width argument
					}
				}
			}

			// Handle parameterised precision
			if (0 <= prec_pos)
			{
				assert(flags.get_precision() < 0);
				assert(0 < prec_pos);
				assert(args.size() >= unsigned(prec_pos));
				if ((0 < prec_pos) && (args.size() >= unsigned(prec_pos)))
				{
					int precision;
					if (args[prec_pos - 1].make_integer(precision))
						flags.set_precision(precision);
					else
						assert(false); // inappropriate type passed as precision argument
				}
			}

			// Some conversions don't actually take an argument - get them out of the way
			flags.apply(str);
			if (format_flags::conversion::strerror == flags.get_conversion())
			{
				str << std::strerror(errno);
				start = it;
			}
			else if (format_flags::conversion::percent == flags.get_conversion())
			{
				str << typename Stream::char_type(format_chars<typename Stream::char_type>::percent);
				start = it;
			}
			else
			{
				assert(0 < arg_pos);
				assert(args.size() >= unsigned(arg_pos));
				if ((0 >= arg_pos) || (args.size() < unsigned(arg_pos)))
					continue;
				args[arg_pos - 1].output(str, flags);
				start = it;
			}
		}
	}
}

} // namespace detail

template <typename Stream, typename Format, typename... Params>
inline void stream_format(Stream &str, Format const &fmt, Params &&... args)
{
	auto const arg_pack(detail::make_format_arguments<Stream>(std::forward<Params>(args)...));
	detail::stream_format(str, fmt, arg_pack);
}

template <typename String = std::string, typename Format, typename... Params>
inline String string_format(Format const &fmt, Params &&... args)
{
	typedef std::basic_ostringstream<typename String::value_type, typename String::traits_type, typename String::allocator_type> ostream;
	ostream str;
	stream_format(str, fmt, std::forward<Params>(args)...);
	return str.str();
};

template <typename String = std::string, typename Format, typename... Params>
inline String string_format(std::locale const &locale, Format const &fmt, Params &&... args)
{
	typedef std::basic_ostringstream<typename String::value_type, typename String::traits_type, typename String::allocator_type> ostream;
	ostream str;
	str.imbue(locale);
	stream_format(str, fmt, std::forward<Params>(args)...);
	return str.str();
};

#endif // __MAME_UTIL_STRFORMAT_H__