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
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
/*!
 * # Overview
 * This library provides a flexible and powerful method to format data. At the
 * heart of the library lie two traits: `Fmt`, for things that are formattable,
 * and `FormatTable`, that maps placeholders in format strings to actual `Fmt`s
 * and supply those with information they need to produce output. Unlike with
 * `format!` from the standard library, there is no restriction that format
 * strings need to be static; in fact the whole point of the library is to
 * allow moving as much control over formatting process into the format strings
 * themselves (and ideally those - into user-editable config files).
 *
 * There are several `impl`s of `FormatTable`, most notable for `HashMap`s
 * (with either `str` or `String` keys, and `Borrow<dyn Fmt>` values, which
 * means a bit of type annotations required to use them) and `Vec`s (also with
 * `Borrow<dyn Fmt>` elements). The method on `FormatTable` to format a string
 * is `format(&self, format_string: &str) -> Result<String, FormattingError>`
 *
 * # Format string syntax
 * A format string consists of literals and placeholders. They can be separated
 * by colons, but this is not required. Just keep in mind that colons need to
 * be escaped in literals.
 *
 * A literal is any string not containing unescaped opening brackets "`{`" or
 * colons "`:`". Escaping is done in the usual fashion, with backslashes.
 *
 * A placeholder has a more complex structure. Each placeholder is contained
 * within a set of curly brackets, and starts with a name of the `Fmt` it
 * requests formatting from. Name is a dot-separated list of segments denoting
 * access to a (possibly nested) `Fmt`. There must be at least one segment, and
 * empty segments are not allowed (`FormattingError`s happen in both cases).
 * All of the following are valid name-only placeholders:
 * * `"{name}"`
 * * `"{a.path.to.some.nested.field}"`
 * * `r"{escapes.\{are\}.allowed}"`
 *
 * Note that trailing and leading whitespace is stripped from each segment
 * (which means that whitespace-only segments are not allowed as well as empty
 * segments).
 *
 * The name may be followed by an arguments block. An arguments block is just a
 * valid format string surrounded by a pair of curly brackets. Colons take on a
 * special meaning in argument blocks: they separate individual arguments.
 * While in a top-level format string the following two would behave
 * identically, they are very different if used as arguments:
 * * `"{foo{baz}}"`
 * * `"{foo:{baz}}"`
 *
 * If used as an argument block, the first string would form a single argument,
 * concatenating a literal `"foo"` and the expansion of placeholder `"baz"`.
 * The second would form two arguments instead.
 *
 * Here are some examples of valid placeholders with arguments:
 * * `"{name{simple!}}"`
 * * `"{name{two:arguments}}"`
 * * `"{name{{a}{b}:{c}foobar}}"`
 * * `"{nested{{also.can.have.arguments{arg}}}}"`
 *
 * There's one limitation to the above: there is a rather arbitrary limit of
 * 100 to the allowed nesting of placeholders inside placeholders in general
 * and inside argument lists in particular, to avoid blowing the stack up by
 * mistake of from malice.
 *
 * After the argument block (or after the name if there is no arguments) may be
 * a flags block. If the flags block follows the name, it has to be separated
 * from it by a colon. If the flags block follows an argument list, it may or
 * may not be separated from it by the colon. Flags block may be empty, or
 * contain one or more single-character flags. Flags can be repeated, the exact
 * meaning of the repetition depends on the `Fmt` the flags will be fed to. If 
 * the flags block is followed by options (see below) it has to be terminated
 * with a colon, otherwise the colon is optional.
 *
 * Here are some examples of placeholders with flags:
 * * `"{name:a=}"`
 * * `"{name{arg}asdf}"`
 * * `"{name{arg}:asdf:}"`
 *
 * Finally, a placeholder can contain zero or more options after the flags
 * block. Note that if the options are present, flags block must be present as
 * well (but may be empty). Options are key-value pairs, with keys being simple
 * strings with all leading and trailing whitespace stripped, while values can
 * be any valid format strings (the same caveat about nesting as with arguments
 * applies here as well). A key is separated from a value by an equals sign.
 * Key-value pairs are separated by colons. Empty values are allowed, empty
 * keys are not.
 *
 * Here are some examples of placeholders with options:
 * * `"{name::opt=value}"`
 * * `"{name::a=foo:b=baz}"`
 * * `"{name::opt=foo{can.be.a.placeholder.as.well}}"`
 *
 * Different implementations of `Fmt` support different flags and options, see
 * each entry to find out which. There is also a group of common options,
 * described in a separate section below.
 *
 * # Examples
 * Let's start with something boring:
 * ```
 * use std::collections::HashMap;
 * use pfmt::{Fmt, FormatTable};
 *
 * let i = 2;
 * let j = 5;
 * let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
 * table.insert("i", &i);
 * table.insert("j", &j);
 * let s = table.format("i = {i}, j = {j}").unwrap();
 * assert_eq!(s, "i = 2, j = 5");
 * ```
 * I can do that with `format!` too. This is a bit more fun, and shows both
 * options and flags:
 * ```
 * use std::collections::HashMap;
 * use pfmt::{Fmt, FormatTable};
 *
 * let s = "a_really_long_string";
 * let i = 10;
 * let j = 12;
 * let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
 * table.insert("s", &s);
 * table.insert("i", &i);
 * table.insert("j", &j);
 * // (note escaped colons)
 * let s = table.format("hex\\: {i:px}, octal\\: {j:o}, fixed width\\: {s::truncate=r5}").unwrap();
 * assert_eq!(s, "hex: 0xa, octal: 14, fixed width: a_rea");
 * ```
 * Can't decide if you want your booleans as "true" and "false", or "yes" and
 * "no"? Easy:
 * ```
 * use std::collections::HashMap;
 * use pfmt::{Fmt, FormatTable};
 *
 * let a = true;
 * let b = false;
 * let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
 * table.insert("a", &a);
 * table.insert("b", &b);
 * let s = table.format("{a}, {b:y}, {b:Y}").unwrap();
 * assert_eq!(s, "true, no, N");
 * ```
 * And here are `Vec`s as format tables:
 * ```
 * use pfmt::{Fmt, FormatTable};
 * let i = 1;
 * let j = 2;
 * let table: Vec<&dyn Fmt> = vec![&i, &j];
 * let s = table.format("{0}, {1}, {0}").unwrap();
 * assert_eq!(s, "1, 2, 1");
 * ```
 * All of the above examples used references as the element type of the format
 * tables, but `FormatTable` is implemented (for hashmaps and vectors) for
 * anything that is `Borrow<dyn Fmt>`, which means boxes, and reference
 * counters and more. Tables thus can fully own the data:
 * ```
 * use std::collections::HashMap;
 * use pfmt::{Fmt, FormatTable};
 *
 * let mut table: HashMap<String, Box<Fmt>> = HashMap::new();
 * table.insert("a".to_string(), Box::new(2) as Box<Fmt>);
 * table.insert("b".to_string(), Box::new("foobar".to_string()) as Box<Fmt>);
 * let s = table.format("{a}, {b}").unwrap();
 * assert_eq!(s, "2, foobar");
 * ```
 * This is a bit on the verbose side, though.
 *
 * The library also suppports accessing elements of `Fmt`s through the same
 * syntax Rust uses: dot-notation, provided the implementation of `Fmt` in
 * question allows it:
 * ```
 * use std::collections::HashMap;
 * use pfmt::{Fmt, FormatTable, SingleFmtError, util};
 * 
 * struct Point {
 *     x: i32,
 *     y: i32
 * }
 * 
 * impl Fmt for Point {
 *     fn format(
 *         &self,
 *         full_name: &[String],
 *         name: &[String],
 *         args: &[String],
 *         flags: &[char],
 *         options: &HashMap<String, String>,
 *     ) -> Result<String, SingleFmtError> {
 *         if name.is_empty() {
 *             Err(SingleFmtError::NamespaceOnlyFmt(util::join_name(full_name)))
 *         } else if name[0] == "x" {
 *             self.x.format(full_name, &name[1..], args, flags, options)
 *         } else if name[0] == "y" {
 *             self.y.format(full_name, &name[1..], args, flags, options)
 *         } else {
 *             Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)))
 *         }
 *     }
 * }
 * 
 * let p = Point { x: 1, y: 2 };
 * let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
 * table.insert("p", &p);
 * let s = table.format("{p.x}, {p.y}").unwrap();
 * assert_eq!(s, "1, 2");
 * ```
 * This can be nested to arbitrary depth.
 *
 * # Errors
 * `format` method on `FormatTables` returns a `Result<String,
 * FormattingError>`. There are three primary types of these: parsing errors
 * which occur when the format string is not well-formed, errors arising from
 * usage of unknown options and flags or options with invalid values, and
 * finally errors due to requesting `Fmt`s that are missing in the table.
 *
 * With hard-coded format strings and rigid format tables, most of these can be
 * safely ignored, so `unwrap()` away.
 *
 * # Common options
 * Most pre-made implementation of `Fmt` honor several common options. Here's
 * a list of them, with detailed info available further in this section:
 * * `truncate`
 * * `width`
 *
 * ## `truncate`: `{'l', 'r'} + non-negative integer`
 * Controls truncation of the field. If begins with `l`, left part of the
 * field that doesn't fit is truncated, if begins with `r` - the right part is
 * removed instead. Note that `"l0"` is not actually forbidden, just very
 * useless.
 *
 * It is an `InvalidOptionValue` to pass anything not fitting into the template
 * in the header as the value of this option.
 *
 * ## `width`: `{'l', 'c', 'r'} + non-negative integer`
 * Controls the width of the field. Has no effect if the field is already wider
 * than the value supplied. If starts with "`l`", the field will be
 * left-justified. If starts with "`c`", the field will be centered. If starts
 * with "`r`", the field will be right-justified.
 *
 * It is an `InvalidOptionValue` to pass anything not fitting into the template
 * in the header as the value for this option.
 *
 * # Common numeric options
 * Most numeric Fmts honor these. For the detailed description skip to the end
 * of this section.
 * * `prec`
 * * `round`
 *
 * ## `prec`: `integer`
 * Controls precision of the displayed number, with bigger values meaning more
 * significant digits will be displayed. If negative, the number will be
 * rounded, the rounding direction is controlled by the `round` option.
 * Positive values are accepted by integer Fmts, but have no effect.
 *
 * It is an `InvalidOptionValue` to pass a string that doesn't parse as a
 * signed integer as a value to this option.
 *
 * ## `round`: `{"up", "down", "nearest"}`
 * Controls the direction of rounding by the `round` option, and has no effect
 * without it. Defaults to `nearest`.
 *
 * It is an `InvalidOptionValue` to pass a string different from the mentioned
 * three to this option.
 *
 * # More fun
 * Format tables are pretty flexible in the type of format units they can
 * return from the `get_fmt` method. They don't even have to actually contain
 * the `Fmt`s, you can make your format tables produce format units on the fly.
 * The drawback is that you'll probably lose ability to combine format tables
 * via tuples (see below) if your `Item` is not `&'a dyn Fmt`. But variations
 * on the following are possible (and possibly useful):
 * ```
 * use pfmt::{Fmt, FormatTable};
 * 
 * struct Producer { }
 * 
 * impl<'a> FormatTable<'a> for Producer {
 *     type Item = i32;
 * 
 *     fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
 *         name.parse().ok()
 *     }
 * }
 *  
 * let table = Producer { };
 * let s = table.format("{1}, {12}").unwrap();
 * assert_eq!(s, "1, 12");
 * ```
 *
 * There's also an implementation of `FormatTable` for tuples (up to 6-tuples)
 * that contain format tables with the same `Item` type. It searches the format
 * tables in order and uses the first `Fmt` successfully returned by `get_fmt`.
 * This is particularly useful with `Mono` format table from the `extras`
 * module. It allows to easily combine format tables or provide defaults or
 * overrides without modifying the tables in question.
 * ```
 * use std::collections::HashMap;
 * 
 * use pfmt::{Fmt, FormatTable};
 * use pfmt::extras::Mono;
 * 
 * let a = Mono("a", 5);
 * let b = Mono("b", "foo");
 * let t = {
 *     let mut res: HashMap<&str, Box<dyn Fmt>> = HashMap::new();
 *     res.insert("a", Box::new("not five"));
 *     res.insert("b", Box::new("not foo"));
 *     res
 * };
 * let s1 = (&a, &b, &t).format("{a}, {b}").expect("Failed to format");
 * let s2 = (&a, &t, &b).format("{a}, {b}").expect("Failed to format");
 * assert_eq!(s1, "5, foo");
 * assert_eq!(s2, "5, not foo");
 * ```
 */

#[cfg(test)] #[macro_use]
extern crate galvanic_assert;
#[cfg(test)] #[macro_use]
extern crate galvanic_test;

extern crate num;

use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::HashMap;

use parse::{parse, ParseError, Piece};

mod parse;

pub mod extras;
pub mod util;

/* ---------- base traits ---------- */

/// A unit of formatting.
pub trait Fmt {
    /// Perform the formatting of a single placeholder. Placeholder's full
    /// name, name segments of child format units, arguments, flags and options
    /// will be passed to this method.
    ///
    /// You should not use this method directly, use `format` on `FormatTable`
    /// instead.
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError>;
}

/// A collection or producer of format units.
pub trait FormatTable<'a> {
    type Item: Fmt;

    /// Produce or retrieve a format unit with the given name stem.
    fn get_fmt(&'a self, name: &str) -> Option<Self::Item>;

    /// Perform formatting of a format string.
    ///
    /// This method is not meant to be overridden. You can, but you would have
    /// to reimplement format strings parser yourself.
    fn format(&'a self, input: &str) -> Result<String, FormattingError> {
        format_one(self, &parse(input, 0, 0)?)
    }
}

fn format_one<'a, 'b, T: FormatTable<'a> + ?Sized>(
    table: &'a T,
    piece: &'b Piece,
) -> Result<String, FormattingError> {
    match piece {
        Piece::Literal(s) => Ok(s.clone()),
        Piece::Placeholder(name, args, flags, opts) => {
            if let Some(root) = table.get_fmt(&name[0]) {
                let mut processed_args = Vec::with_capacity(args.len());
                for arg in args.iter() {
                    processed_args.push(format_one(table, arg)?);
                }
                let mut processed_opts = HashMap::new();
                for (key, piece) in opts.iter() {
                    processed_opts.insert(key.clone(), format_one(table, piece)?);
                }
                Ok(root.format(name, &name[1..], &processed_args, flags, &processed_opts)?)
            } else {
                Err(FormattingError::UnknownFmt(util::join_name(&name)))
            }
        },
        Piece::Multi(pieces) => {
            let mut res = String::new();
            for piece in pieces.iter() {
                res.push_str(&format_one(table, piece)?);
            }
            Ok(res)
        }
    }
}

/* ---------- errors ---------- */

/// Errors that happen in individual `Fmt`s. All of them contain the full path
/// to the `Fmt` in error as the first field.
#[derive(Debug, PartialEq)]
pub enum SingleFmtError {
    /// Returned if a `Fmt` receives a flag it doesn't know how to handle.
    /// It's not actually used by the `impl`s for the standard types, but you
    /// can use it if you wish to be strict. Contains the erroneous flag.
    UnknownFlag(String, char),
    /// Returned if a `Fmt` receives an option it doesn't know how to handle.
    /// Again, standard types do not do this, they are not strict. Contains the
    /// erroneous option.
    UnknownOption(String, String),
    /// Returned when a given option (stored in the first field) contains an
    /// invalid value (stored in the second field). Standard types *do* use
    /// this. Contains a pair of erroneous option's name and value.
    InvalidOptionValue(String, String, String),
    /// Returned when a `Fmt` that is only used as a container to hold/produce
    /// other `Fmt`s via the dot access syntax is used directly. Contains the
    /// full path to the format unit used in such fashion.
    NamespaceOnlyFmt(String),
    /// Returned when a `Fmt`does not contain a requested sub-`Fmt`. Contains
    /// the full path to the child format unit.
    UnknownSubfmt(String),
    /// Returned when a `Fmt` was passed wrong number of arguments. The
    /// `Ordering` member specifies whether more, less or precisely the
    /// expected number (given by the `usize` field) is required.
    WrongNumberOfArguments(String, Ordering, usize),
    /// Returned when a `Fmt` is passed an argument it can't process. Contains
    /// the index and contents of the argument in error.
    InvalidArgument(String, usize, String),
}

/// Any error that can happen during formatting.
#[derive(Debug, PartialEq)]
pub enum FormattingError {
    // Parsing errors.
    /// Returned when the brackets in the format string are not balanced.
    /// Contains the byte address of the offending bracket.
    UnbalancedBrackets(usize),
    /// Returned when a placeholder in the format string has an empty name
    /// segment. Contains the byte offset of the empty segment.
    EmptyNameSegment(usize),
    /// Returned when a placeholder's option has an empty name. Contains the
    /// byte offset of the place where the name should have been.
    EmptyOptionName(usize),
    // Errors from single Fmts.
    /// A `SingleFmtError::UnknownFlag` is propagated as this.
    UnknownFlag(String, char),
    /// A `SingleFmtError::UnknownOption` is propagated as this.
    UnknownOption(String, String),
    /// A `SingleFmtError::InvalidOptionValue` is propagated as this.
    InvalidOptionValue(String, String, String),
    /// A `SingleFmtError::NamespaceOnlyFmt` is propagated as this.
    NamespaceOnlyFmt(String),
    /// A `SingleFmtError::WrongNumberOfArguments` is propagated as this.
    WrongNumberOfArguments(String, Ordering, usize),
    /// A `SingleFmtError::InvalidArgument` is propagated as this.
    InvalidArgument(String, usize, String),
    // General errors.
    /// Returned when a requested `Fmt` does not exist (or cannot be created)
    /// in the format table. A `SingleFmtError::UnknownSubfmt` is also
    /// propagated as this. Contains the full path to the failed format unit.
    UnknownFmt(String),
}

impl From<SingleFmtError> for FormattingError {
    fn from(err: SingleFmtError) -> Self {
        match err {
            SingleFmtError::UnknownFlag(s, c) => FormattingError::UnknownFlag(s, c),
            SingleFmtError::UnknownOption(p, o) => FormattingError::UnknownOption(p, o),
            SingleFmtError::InvalidOptionValue(p, opt, val) =>
                FormattingError::InvalidOptionValue(p, opt, val),
            SingleFmtError::NamespaceOnlyFmt(s) => FormattingError::NamespaceOnlyFmt(s),
            SingleFmtError::UnknownSubfmt(s) => FormattingError::UnknownFmt(s),
            SingleFmtError::WrongNumberOfArguments(s, o, n) =>
                FormattingError::WrongNumberOfArguments(s, o, n),
            SingleFmtError::InvalidArgument(s, i, a) =>
                FormattingError::InvalidArgument(s, i, a),
        }
    }
}

impl From<ParseError> for FormattingError {
    fn from(err: ParseError) -> Self {
        use parse::ParseError::*;
        match err {
            UnbalancedBrackets(i) => FormattingError::UnbalancedBrackets(i),
            EmptyNameSegment(i) => FormattingError::EmptyNameSegment(i),
            EmptyOptionName(i) => FormattingError::EmptyOptionName(i),
        }
    }
}

/* ---------- key implementations ---------- */

impl<'a, T: Fmt + ?Sized> Fmt for &'a T { 
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        (*self).format(full_name, name, args, flags, options)
    }
}

impl<'a, 'b, I: Fmt, T: FormatTable<'a, Item = I>> FormatTable<'a> for &'b T {
    type Item = I;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        (*self).get_fmt(name)
    }
}

/* ---------- implementations of FormatTable for standard types ---------- */

/// This implementation recognizes placeholders with string names stored in the
/// hash map.
impl<'a, B, H> FormatTable<'a> for HashMap<String, B, H> 
where
    B: Borrow<dyn Fmt>,
    H: std::hash::BuildHasher,
{
    type Item = &'a dyn Fmt;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.get(name).map(|b| b.borrow())
    }
}

/// This implementation recognizes placeholders with string names (represented by
/// string slices) stored in the hash map.
impl<'a, 'b, B, H> FormatTable<'a> for HashMap<&'b str, B, H> 
where
    B: Borrow<dyn Fmt>,
    H: std::hash::BuildHasher,
{
    type Item = &'a dyn Fmt;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.get(name).map(|b| b.borrow())
    }
}

/// This implementation recognizes placeholders which names are valid integer
/// indices into the vector.
impl<'a, B: Borrow<dyn Fmt>> FormatTable<'a> for Vec<B> {
    type Item = &'a dyn Fmt;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        if let Ok(index) = name.parse::<usize>() {
            if index < self.len() {
                Some(self[index].borrow())
            } else {
                None
            }
        } else {
            None
        }
    }
}

/// This implementation first uses the first table to look up placeholders'
/// names, and then the second.
impl<'a, F, A, B> FormatTable<'a> for (A, B)
where
    F: Fmt,
    A: FormatTable<'a, Item = F>,
    B: FormatTable<'a, Item = F>,
{
    type Item = F;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.0.get_fmt(name)
            .or_else(|| self.1.get_fmt(name))
    }
}

/// This implementation looks up placeholders' names consecutively in three
/// tables.
impl<'a, F, A, B, C> FormatTable<'a> for (A, B, C)
where
    F: Fmt,
    A: FormatTable<'a, Item = F>,
    B: FormatTable<'a, Item = F>,
    C: FormatTable<'a, Item = F>,
{
    type Item = F;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.0
            .get_fmt(name)
            .or_else(|| self.1.get_fmt(name))
            .or_else(|| self.2.get_fmt(name))
    }
}

/// This implementation looks up placeholders' names consecutively in four
/// tables.
impl<'a, F, A, B, C, D> FormatTable<'a> for (A, B, C, D)
where
    F: Fmt,
    A: FormatTable<'a, Item = F>,
    B: FormatTable<'a, Item = F>,
    C: FormatTable<'a, Item = F>,
    D: FormatTable<'a, Item = F>,
{
    type Item = F;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.0
            .get_fmt(name)
            .or_else(|| self.1.get_fmt(name))
            .or_else(|| self.2.get_fmt(name))
            .or_else(|| self.3.get_fmt(name))
    }
}

/// This implementation looks up placeholders' names consecutively in five
/// tables.
impl<'a, T, A, B, C, D, E> FormatTable<'a> for (A, B, C, D, E)
where
    T: Fmt,
    A: FormatTable<'a, Item = T>,
    B: FormatTable<'a, Item = T>,
    C: FormatTable<'a, Item = T>,
    D: FormatTable<'a, Item = T>,
    E: FormatTable<'a, Item = T>,
{
    type Item = T;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.0
            .get_fmt(name)
            .or_else(|| self.1.get_fmt(name))
            .or_else(|| self.2.get_fmt(name))
            .or_else(|| self.3.get_fmt(name))
            .or_else(|| self.4.get_fmt(name))
    }
}

/// This implementation looks up placeholders' names consecutively in six
/// tables.
impl<'a, T, A, B, C, D, E, F> FormatTable<'a> for (A, B, C, D, E, F)
where
    T: Fmt,
    A: FormatTable<'a, Item = T>,
    B: FormatTable<'a, Item = T>,
    C: FormatTable<'a, Item = T>,
    D: FormatTable<'a, Item = T>,
    E: FormatTable<'a, Item = T>,
    F: FormatTable<'a, Item = T>,
{
    type Item = T;

    fn get_fmt(&'a self, name: &str) -> Option<Self::Item> {
        self.0
            .get_fmt(name)
            .or_else(|| self.1.get_fmt(name))
            .or_else(|| self.2.get_fmt(name))
            .or_else(|| self.3.get_fmt(name))
            .or_else(|| self.4.get_fmt(name))
            .or_else(|| self.5.get_fmt(name))
    }
}

/* ---------- implementations of Fmt for standard types ---------- */

/// This instance is aware of the following flags:
/// * `y`, which changes the output from true/false to yes/no;
/// * `Y`, which changes the output to Y/N.
///
/// Common options are recognized.
impl Fmt for bool {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut res = if *self {
            if flags.contains(&'y') {
                "yes".to_string()
            } else if flags.contains(&'Y') {
                "Y".to_string()
            } else {
                "true".to_string()
            }
        } else if flags.contains(&'y') {
            "no".to_string()
        } else if flags.contains(&'Y') {
            "N".to_string()
        } else {
            "false".to_string()
        };
        util::apply_common_options(full_name, &mut res, options)?;
        Ok(res)
    }
}

/// This instance has no special flags.
///
/// Common options are recognized.
impl Fmt for char {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        _flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = self.to_string();
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `e`, which changes the output to the scientific, or exponential,
/// notation.
///
/// Common options are recognized.
/// Common numeric options are also recognized.
impl Fmt for f32 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut res = if flags.contains(&'e') {
            util::float_to_exp(full_name, *self, options)?
        } else {
            util::float_to_normal(full_name, *self, options)?
        };
        util::add_sign(&mut res, *self, flags)?;
        util::apply_common_options(full_name, &mut res, options)?;
        Ok(res)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `e`, which changes the output to scientific format.
///
/// Common options are recognized.
/// Common numeric options are also recognized.
impl Fmt for f64 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut res = if flags.contains(&'e') {
            util::float_to_exp(full_name, *self, options)?
        } else {
            util::float_to_normal(full_name, *self, options)?
        };
        util::add_sign(&mut res, *self, flags)?;
        util::apply_common_options(full_name, &mut res, options)?;
        Ok(res)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes output hexadecimal;
///
/// Common and common numeric options are recognized.
impl Fmt for i8 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        util::add_sign(&mut s, *self, flags)?;
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes output hexadecimal;
///
/// Common and common numeric options are recognized.
impl Fmt for i16 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        util::add_sign(&mut s, *self, flags)?;
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes output hexadecimal;
///
/// Common and common numeric options are recognized.
impl Fmt for i32 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        util::add_sign(&mut s, *self, flags)?;
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes output hexadecimal;
///
/// Common and common numeric options are recognized.
impl Fmt for i64 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        util::add_sign(&mut s, *self, flags)?;
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes output hexadecimal;
///
/// Common and common numeric options are recognized.
impl Fmt for i128 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        util::add_sign(&mut s, *self, flags)?;
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which forces display of the sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes output hexadecimal;
///
/// Common and common numeric options are recognized.
impl Fmt for isize {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        util::add_sign(&mut s, *self, flags)?;
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance has no special flags.
///
/// Common options are recognized.
impl<'a> Fmt for &'a str {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        _flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = self.to_string();
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance has no special flags.
///
/// Common options are recognized.
impl Fmt for String {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        _flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = self.clone();
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which add a leading plus sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes the output hexadecimal.
///
/// Common and common numeric options are recognized.
impl Fmt for u8 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        if flags.contains(&'+') {
            s.insert(0, '+');
        }
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which add a leading plus sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes the output hexadecimal.
///
/// Common and common numeric options are recognized.
impl Fmt for u16 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        if flags.contains(&'+') {
            s.insert(0, '+');
        }
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which add a leading plus sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes the output hexadecimal.
///
/// Common and common numeric options are recognized.
impl Fmt for u32 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        if flags.contains(&'+') {
            s.insert(0, '+');
        }
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which add a leading plus sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes the output hexadecimal.
///
/// Common and common numeric options are recognized.
impl Fmt for u64 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        if flags.contains(&'+') {
            s.insert(0, '+');
        }
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which add a leading plus sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes the output hexadecimal.
///
/// Common and common numeric options are recognized.
impl Fmt for u128 {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        if flags.contains(&'+') {
            s.insert(0, '+');
        }
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/// This instance is aware of the following flags:
/// * `+`, which add a leading plus sign;
/// * `b`, which makes the output binary;
/// * `o`, which makes the output octal;
/// * `p`, which in combination with '`b`', '`o`' or '`x`' adds a base prefix
/// to the output.
/// * `x`, which makes the output hexadecimal.
///
/// Common and common numeric options are recognized.
impl Fmt for usize {
    fn format(
        &self,
        full_name: &[String],
        name: &[String],
        _args: &[String],
        flags: &[char],
        options: &HashMap<String, String>,
    ) -> Result<String, SingleFmtError> {
        if !name.is_empty() {
            return Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)));
        }
        let mut s = util::int_to_str(full_name, *self, flags, options)?;
        if flags.contains(&'+') {
            s.insert(0, '+');
        }
        util::apply_common_options(full_name, &mut s, options)?;
        Ok(s)
    }
}

/* ---------- tests for Fmts ---------- */

#[cfg(test)]
mod fmt_tests {
    test_suite! {
        name general;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt, FormattingError};

        test unknown_fmt() {
            let table: HashMap<&str, &dyn Fmt> = HashMap::new();
            let s = table.format("i = {i}");
            assert_that!(&s, eq(Err(FormattingError::UnknownFmt("i".to_string()))));
        }

        test unknown_fmt_nested() {
            let i = 1;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i.a}");
            assert_that!(&s, eq(Err(FormattingError::UnknownFmt("i.a".to_string()))));
        }

        test integers_simple_1() {
            let i = 1;
            let j = 23;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            table.insert("j", &j);
            let s = table.format("i = {i}, j = {j}").unwrap();
            assert_that!(&s.as_str(), eq("i = 1, j = 23"));
        }

        test separated_by_colons() {
            let table: HashMap<&str, &dyn Fmt> = HashMap::new();
            let s = table.format("a:b").unwrap();
            assert_that!(&s.as_str(), eq("ab"));
        }

    }

    test_suite! {
        name boolean;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test flags() {
            let a = true;
            let b = false;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("a", &a);
            table.insert("b", &b);
            let s = table.format("{a}, {b:y}, {b:Y}").unwrap();
            assert_that!(&s.as_str(), eq("true, no, N"));
        }

    }

    test_suite! {
        name char;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test boring() {
            let c = 'z';
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("c", &c);
            let s = table.format("{c}, {c::width=l5}!").unwrap();
            assert_that!(&s.as_str(), eq("z, z    !"));
        }

    }

    test_suite! {
        name floats;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test exp_precision_neg() {
            let f: f64 = 1_234_567.891;
            let mut table: HashMap<String, &dyn Fmt> = HashMap::new();
            table.insert("f".to_string(), &f);
            let s = table.format("{f:e+:prec=-1}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("+1.23457e6"));
        }

        test exp_precision_pos() {
            let f: f32 = 1000.123;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("f", &f);
            let s = table.format("{f:e:prec=2}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("1.00012e3"));
        }

        test exp_negative_power() {
            let f: f32 = 0.0625;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("f", &f);
            let s = table.format("{f:e}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("6.25e-2"));
        }

        test norm_rounding_up() {
            let f = 0.2;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("f", &f);
            let s = table.format("{f::round=up:prec=0}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("1"));
        }

        test norm_rounding_down() {
            let f = 0.8;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("f", &f);
            let s = table.format("{f::round=down:prec=0}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("0"));
        }

        test norm_rounding_usual() {
            let f = 0.5;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("f", &f);
            let s = table.format("{f::round=nearest:prec=0}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("1"));
        }

        test negative() {
            let f = -1.0;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("f", &f);
            let s = table.format("{f}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("-1"));
        }

    }

    test_suite! {
        name integers;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test basic() {
            let i = 10;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("10"));
        }

        test different_bases() {
            let i = 11;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i:b}, {i:o}, {i:x}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("1011, 13, b"));
        }

        test base_prefixes() {
            let i = 1;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i:bp}, {i:op}, {i:xp}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("0b1, 0o1, 0x1"));
        }

        test bases_for_negative_numbers() {
            let i = -11;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i:b}, {i:o}, {i:x}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("-1011, -13, -b"));
        }

        test rounding() {
            let i = 1235;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i::prec=-1}, {i::prec=-2}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("1240, 1200"));
        }

        test rounding_for_negatives() {
            let i = -1235;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("i", &i);
            let s = table.format("{i::prec=-1}, {i::prec=-2}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("-1240, -1200"));
        }

        test rounding_in_different_bases() {
            let o = 0o124;
            let b = 0b1101;
            let x = 0x1a2;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("o", &o);
            table.insert("b", &b);
            table.insert("x", &x);
            let s1 = table.format("{o:op:prec=-1}, {o:op:prec=-2}").expect("Failed to parse 1");
            let s2 = table.format("{b:bp:prec=-1}, {b:bp:prec=-2}").expect("Failed to parse 2");
            let s3 = table.format("{x:xp:prec=-1}, {x:xp:prec=-2}").expect("Failed to parse 3");
            assert_that!(&s1.as_str(), eq("0o130, 0o100"));
            assert_that!(&s2.as_str(), eq("0b1110, 0b1100"));
            assert_that!(&s3.as_str(), eq("0x1a0, 0x200"));
        }

    }

    test_suite! {
        name common_options;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test width_left() {
            let string = "foobar";
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("s", &string);
            let s = table.format("{s::width=l10}").unwrap();
            assert_that!(&s.as_str(), eq("foobar    "));
        }

        test width_right() {
            let string = "foobar";
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("s", &string);
            let s = table.format("{s::width=r10}").unwrap();
            assert_that!(&s.as_str(), eq("    foobar"));
        }

        test width_center() {
            let string = "foobar";
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("s", &string);
            let s = table.format("{s::width=c10}").unwrap();
            assert_that!(&s.as_str(), eq("  foobar  "));
        }

        test truncate_left() {
            let string = "1234567890";
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("s", &string);
            let s = table.format("{s::truncate=l5}").unwrap();
            assert_that!(&s.as_str(), eq("67890"));
        }

        test truncate_right() {
            let string = "1234567890";
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("s", &string);
            let s = table.format("{s::truncate=r5}").unwrap();
            assert_that!(&s.as_str(), eq("12345"));
        }

    }

    test_suite! {
        name nested_fmts;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt, FormattingError, SingleFmtError, util};

        struct Point {
            x: i32,
            y: i32
        }

        struct Line {
            start: Point,
            end: Point
        }

        impl Fmt for Point {
            fn format(&self,
                      full_name: &[String],
                      name: &[String],
                      args: &[String],
                      flags: &[char],
                      options: &HashMap<String, String>)
                -> Result<String, SingleFmtError>
                {
                    if name.is_empty() {
                        Err(SingleFmtError::NamespaceOnlyFmt(util::join_name(full_name)))
                    } else if name[0] == "x" {
                        self.x.format(full_name, &name[1..], args, flags, options)
                    } else if name[0] == "y" {
                        self.y.format(full_name, &name[1..], args, flags, options)
                    } else {
                        Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)))
                    }
                }
        }

        impl Fmt for Line {
            fn format(&self,
                      full_name: &[String],
                      name: &[String],
                      args: &[String],
                      flags: &[char],
                      options: &HashMap<String, String>)
                -> Result<String, SingleFmtError>
                {
                    if name.is_empty() {
                        Err(SingleFmtError::NamespaceOnlyFmt(util::join_name(full_name)))
                    } else if name[0] == "start" || name[0] == "a" {
                        self.start.format(full_name, &name[1..], args, flags, options)
                    } else if name[0] == "end" || name[0] == "b" {
                        self.end.format(full_name, &name[1..], args, flags, options)
                    } else {
                        Err(SingleFmtError::UnknownSubfmt(util::join_name(full_name)))
                    }
                }
        }

        test single_nested() {
            let a = Point { x: 0, y: 0 };
            let b = Point { x: 2, y: 10 };
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("a", &a);
            table.insert("b", &b);
            let s = table.format("{a.x}, {b.y}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("0, 10"));
        }

        test double_nested() {
            let line = Line {
                start: Point { x: 0, y: 2 },
                end: Point { x: 6, y: 10},
            };
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("line", &line);
            let s = table.format("{line.start.x}, {line.end.y}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("0, 10"));
        }

        test namespace_only() {
            let p = Point { x: 1, y: 2 };
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("p", &p);
            let s = table.format("{p}");
            assert_that!(&s, eq(Err(FormattingError::NamespaceOnlyFmt("p".to_string()))));
        }

    }

    test_suite! {
        name placeholder_substitution;
        use std::collections::HashMap;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test placeholder_in_options() {
            let p1 = 3;
            let p2 = 5;
            let f = 0.765_432_1;
            let mut table: HashMap<&str, &dyn Fmt> = HashMap::new();
            table.insert("p1", &p1);
            table.insert("p2", &p2);
            table.insert("f", &f);
            let s = table.format("{f::prec={p1}}, {f::prec={p2}}").expect("Failed to format");
            assert_that!(&s.as_str(), eq("0.765, 0.76543"));
        }

    }

}

/* ---------- tests for FormatTables ---------- */

#[cfg(test)]
mod table_tests {
    test_suite! {
        name vec;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt, FormattingError};

        test unknown_fmt_1() {
            let i = 1;
            let j = 2;
            let table: Vec<&dyn Fmt> = vec![&i, &j];
            let err = table.format("{10}").expect_err("Unexpectedly found a fmt");
            assert_that!(&err, eq(FormattingError::UnknownFmt("10".to_string())));
        }

        test unknown_fmt_2() {
            let i = 1;
            let j = 2;
            let table: Vec<&dyn Fmt> = vec![&i, &j];
            let err = table.format("{-3}").expect_err("Unexpectedly found a fmt");
            assert_that!(&err, eq(FormattingError::UnknownFmt("-3".to_string())));
        }

        test boring() {
            let i = 1;
            let j = 2;
            let table: Vec<&dyn Fmt> = vec![&i, &j];
            let s = table.format("{0}, {1}").expect("Failed to format");
            assert_that!(&s, eq("1, 2".to_string()));
        }

    }

    test_suite! {
        name tuples;
        use galvanic_assert::matchers::*;
        use {FormatTable, Fmt};

        test defaulting() {
            let a: Vec<Box<Fmt>> = vec![Box::new(-1), Box::new(-2)];
            let b: Vec<Box<Fmt>> = (0..10_i32).map(|i| Box::new(i) as Box<Fmt>).collect();
            let s = (a, b).format("{5}").expect("Failed");
            assert_that!(&s, eq("5".to_string()));
        }

        test precedence() {
            let a: Vec<Box<Fmt>> = vec![Box::new(1)];
            let b: Vec<Box<Fmt>> = vec![Box::new(10)];
            let s = (a, b).format("{0}").expect("Failed");
            assert_that!(&s, eq("1".to_string()));
        }

        test lifetimes() {
            let i = 10;
            let j = 12;
            let v1: Vec<&dyn Fmt> = vec![&i, &j];
            {
                let k = 13;
                let v2: Vec<&dyn Fmt> = vec![&k];
                let s1 = (&v1, &v2).format("{0}").expect("Failed to format");
                let s2 = (&v2, &v1).format("{0}").expect("Failed to format");
                assert_that!(&s1.as_str(), eq("10"));
                assert_that!(&s2.as_str(), eq("13"));
            }
        }

    }

}