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
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
//! # Slog -  Structured, extensible, composable logging for Rust
//!
//! `slog-rs` is an ecosystem of reusable components for structured, extensible,
//! composable logging for Rust.
//!
//! `slog` is `slog-rs`'s main crate providing core components shared between
//! all other parts of `slog-rs` ecosystem.
//!
//! This is auto-generated technical documentation of `slog`. For information
//! about project organization, development, help, etc. please see
//! [slog github page](https://github.com/slog-rs/slog)
//!
//! ## Core advantages over `log` crate
//!
//! * **extensible** - `slog` crate provides core functionality: very basic
//!   and portable standard feature-set based on open `trait`s. This allows
//!   implementing new features that can be independently published.
//! * **composable** - `trait`s that `slog` exposes to provide extensibility
//!   are designed to be easy to efficiently reuse and combine. By combining
//!   different functionalities every application can specify when, where and
//!   how exactly process logging data from the application and it's
//!   dependencies.
//! * **flexible** - `slog` does not constrain logging to just one globally
//!   registered backend. Parts of your application can handle logging
//!   in a customized way, or completely independently.
//! * **structured** and both **human and machine readable** - By keeping the
//!   key-value data format and retaining its type information, meaning of logging
//!   data is preserved.  Data can be serialized to machine readable formats like
//!   JSON and send it to data-mining system for further analysis etc. On the
//!   other hand, when presenting on screen, logging information can be presented
//!   in aesthetically pleasing and easy to understand way.
//! * **contextual** - `slog`'s `Logger` objects carry set of key-value data
//!   pairs that contains the context of logging - information that otherwise
//!   would have to be repeated in every logging statement.
//!
//! ## `slog` features
//!
//! * performance oriented; read [what makes slog
//!   fast](https://github.com/slog-rs/slog/wiki/What-makes-slog-fast) and see:
//!   [slog bench log](https://github.com/dpc/slog-rs/wiki/Bench-log)
//!   * lazily evaluation through closure values
//!   * async IO support included: see [`slog-async`
//!     crate](https://docs.rs/slog-async)
//! * `#![no_std]` support (with opt-out `std` cargo feature flag)
//! * support for named format arguments (eg. `info!(logger, "printed {line_count} lines", line_count = 2);`)
//!   for easy bridging the human readable and machine-readable output
//! * tree-structured loggers
//! * modular, lightweight and very extensible
//!   * tiny core crate that does not pull any dependencies
//!   * feature-crates for specific functionality
//!   * using `slog` in library does not force users of the library to use slog
//!     (but provides additional functionality); see [example how to use
//!     `slog` in library](https://github.com/slog-rs/example-lib)
//! * backward and forward compatibility with `log` crate:
//!   see [`slog-stdlog` crate](https://docs.rs/slog-stdlog)
//! * convenience crates:
//!   * logging-scopes for implicit `Logger` passing: see
//!     [slog-scope crate](https://docs.rs/slog-scope)
//! * many existing core&community provided features:
//!   * multiple outputs
//!   * filtering control
//!       * compile-time log level filter using cargo features (same as in `log`
//!         crate)
//!       * by level, msg, and any other meta-data
//!       * [`slog-envlogger`](https://github.com/slog-rs/envlogger) - port of
//!         `env_logger`
//!       * terminal output, with color support: see [`slog-term`
//!         crate](https://docs.rs/slog-term)
//!  * [json](https://docs.rs/slog-json)
//!      * [bunyan](https://docs.rs/slog-bunyan)
//!  * [syslog](https://docs.rs/slog-syslog)
//!    and [journald](https://docs.rs/slog-journald) support
//!  * run-time configuration:
//!      * run-time behavior change;
//!        see [slog-atomic](https://docs.rs/slog-atomic)
//!      * run-time configuration; see
//!        [slog-config crate](https://docs.rs/slog-config)
//!
//!
//! [env_logger]: https://crates.io/crates/env_logger
//!
//! ## Notable details
//!
//! **Note:** At compile time `slog` by default removes trace and debug level
//! statements in release builds, and trace level records in debug builds. This
//! makes `trace` and `debug` level logging records practically free, which
//! should encourage using them freely. If you want to enable trace/debug
//! messages or raise the compile time logging level limit, use the following in
//! your `Cargo.toml`:
//!
//! ```norust
//! slog = { version = ... ,
//!          features = ["max_level_trace", "release_max_level_warn"] }
//! ```
//!
//! Root drain (passed to `Logger::root`) must be one that does not ever return
//! errors. This forces user to pick error handing strategy.
//! `Drain::fuse()` or `Drain::ignore_res()`.
//!
//! [env_logger]: https://crates.io/crates/env_logger
//! [fn-overv]: https://github.com/dpc/slog-rs/wiki/Functional-overview
//! [atomic-switch]: https://docs.rs/slog-atomic/
//!
//! ## Where to start
//!
//! [`Drain`](trait.Drain.html), [`Logger`](struct.Logger.html) and
//! [`log` macro](macro.log.html) are the most important elements of
//! slog. Make sure to read their respective documentation
//!
//! Typically the biggest problem is creating a `Drain`
//!
//!
//! ### Logging to the terminal
//!
//! ```ignore
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! fn main() {
//!     let decorator = slog_term::TermDecorator::new().build();
//!     let drain = slog_term::FullFormat::new(decorator).build().fuse();
//!     let drain = slog_async::Async::new(drain).build().fuse();
//!
//!     let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//! ### Logging to a file
//!
//! ```ignore
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use std::fs::OpenOptions;
//! use slog::Drain;
//!
//! fn main() {
//!    let log_path = "target/your_log_file_path.log";
//!    let file = OpenOptions::new()
//!       .create(true)
//!       .write(true)
//!       .truncate(true)
//!       .open(log_path)
//!       .unwrap();
//!
//!     let decorator = slog_term::PlainDecorator::new(file);
//!     let drain = slog_term::FullFormat::new(decorator).build().fuse();
//!     let drain = slog_async::Async::new(drain).build().fuse();
//!
//!     let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//! You can consider using `slog-json` instead of `slog-term`.
//! `slog-term` only coincidently fits the role of a file output format. A
//! proper `slog-file` crate with suitable format, log file rotation and other
//! file-logging related features would be awesome. Contributions are welcome!
//!
//! ### Change logging level at runtime
//!
//! ```ignore
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! use std::sync::{Arc, atomic};
//! use std::sync::atomic::Ordering;
//! use std::result;
//!
//! /// Custom Drain logic
//! struct RuntimeLevelFilter<D>{
//!    drain: D,
//!    on: Arc<atomic::AtomicBool>,
//! }
//!
//! impl<D> Drain for RuntimeLevelFilter<D>
//!     where D : Drain {
//!     type Ok = Option<D::Ok>;
//!     type Err = Option<D::Err>;
//!
//!     fn log(&self,
//!           record: &slog::Record,
//!           values: &slog::OwnedKVList)
//!           -> result::Result<Self::Ok, Self::Err> {
//!           let current_level = if self.on.load(Ordering::Relaxed) {
//!               slog::Level::Trace
//!           } else {
//!               slog::Level::Info
//!           };
//!
//!           if record.level().is_at_least(current_level) {
//!               self.drain.log(
//!                   record,
//!                   values
//!               )
//!               .map(Some)
//!               .map_err(Some)
//!           } else {
//!               Ok(None)
//!           }
//!       }
//!   }
//!
//! fn main() {
//!     // atomic variable controlling logging level
//!     let on = Arc::new(atomic::AtomicBool::new(false));
//!
//!     let decorator = slog_term::TermDecorator::new().build();
//!     let drain = slog_term::FullFormat::new(decorator).build();
//!     let drain = RuntimeLevelFilter {
//!         drain: drain,
//!         on: on.clone(),
//!     }.fuse();
//!     let drain = slog_async::Async::new(drain).build().fuse();
//!
//!     let _log = slog::Logger::root(drain, o!());
//!
//!     // switch level in your code
//!     on.store(true, Ordering::Relaxed);
//! }
//! ```
//!
//! Why is this not an existing crate? Because there are multiple ways to
//! achieve the same result, and each application might come with it's own
//! variation. Supporting a more general solution is a maintenance effort.
//! There is also nothing stopping anyone from publishing their own crate
//! implementing it.
//!
//! Alternative to the above approach is `slog-atomic` crate. It implements
//! swapping whole parts of `Drain` logging hierarchy.
//!
//! ## Examples & help
//!
//! Basic examples that are kept up-to-date are typically stored in
//! respective git repository, under `examples/` subdirectory. Eg.
//! [slog-term examples](https://github.com/slog-rs/term/tree/master/examples).
//!
//! [slog-rs wiki pages](https://github.com/slog-rs/slog/wiki) contain
//! some pages about `slog-rs` technical details.
//!
//! Source code of other [software using
//! slog-rs](https://crates.io/crates/slog/reverse_dependencies) can
//! be an useful reference.
//!
//! Visit [slog-rs gitter channel](https://gitter.im/slog-rs/slog) for immediate
//! help.
//!
//! ## Migrating from slog v1 to slog v2
//!
//! ### Key-value pairs come now after format string
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//!
//! fn main() {
//!     let drain = slog::Discard;
//!     let root = slog::Logger::root(drain, o!());
//!     info!(root, "formatted: {}", 1; "log-key" => true);
//! }
//! ```
//!
//! See more information about format at [`log`](macro.log.html).
//!
//! ### `slog-streamer` is gone
//!
//! Create simple terminal logger like this:
//!
//! ```ignore
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! fn main() {
//!     let decorator = slog_term::TermDecorator::new().build();
//!     let drain = slog_term::FullFormat::new(decorator).build().fuse();
//!     let drain = slog_async::Async::new(drain).build().fuse();
//!
//!     let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//!
//! ### Logging macros now takes ownership of values.
//!
//! Pass them by reference: `&x`.
//!
// }}}

// {{{ Imports & meta
#![warn(missing_docs)]
#![no_std]

#[cfg(not(feature = "std"))]
extern crate alloc;
#[macro_use]
#[cfg(feature = "std")]
extern crate std;

mod key;
pub use self::key::Key;
#[cfg(not(feature = "std"))]
use alloc::sync::Arc;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::rc::Rc;
#[cfg(not(feature = "std"))]
use alloc::string::String;

#[cfg(feature = "nested-values")]
extern crate erased_serde;

use core::{convert, fmt, result};
use core::str::FromStr;
#[cfg(feature = "std")]
use std::boxed::Box;
#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};
#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(feature = "std")]
use std::string::String;
#[cfg(feature = "std")]
use std::sync::Arc;
// }}}

// {{{ Macros
/// Macro for building group of key-value pairs:
/// [`OwnedKV`](struct.OwnedKV.html)
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let _root = slog::Logger::root(
///         drain,
///         o!("key1" => "value1", "key2" => "value2")
///     );
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! o(
    ($($args:tt)*) => {
        $crate::OwnedKV(kv!($($args)*))
    };
);

/// Macro for building group of key-value pairs (alias)
///
/// Use in case of macro name collisions
#[macro_export(local_inner_macros)]
macro_rules! slog_o(
    ($($args:tt)*) => {
        $crate::OwnedKV(slog_kv!($($args)*))
    };
);

/// Macro for building group of key-value pairs in
/// [`BorrowedKV`](struct.BorrowedKV.html)
///
/// In most circumstances using this macro directly is unnecessary and `info!`
/// and other wrappers over `log!` should be used instead.
#[macro_export(local_inner_macros)]
macro_rules! b(
    ($($args:tt)*) => {
        $crate::BorrowedKV(&kv!($($args)*))
    };
);

/// Alias of `b`
#[macro_export(local_inner_macros)]
macro_rules! slog_b(
    ($($args:tt)*) => {
        $crate::BorrowedKV(&slog_kv!($($args)*))
    };
);

/// Macro for build `KV` implementing type
///
/// You probably want to use `o!` or `b!` instead.
#[macro_export(local_inner_macros)]
macro_rules! kv(
    (@ $args_ready:expr; $k:expr => %$v:expr) => {
        kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{}", $v))), $args_ready); )
    };
    (@ $args_ready:expr; $k:expr => %$v:expr, $($args:tt)* ) => {
        kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{}", $v))), $args_ready); $($args)* )
    };
    (@ $args_ready:expr; $k:expr => ?$v:expr) => {
        kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{:?}", $v))), $args_ready); )
    };
    (@ $args_ready:expr; $k:expr => ?$v:expr, $($args:tt)* ) => {
        kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{:?}", $v))), $args_ready); $($args)* )
    };
    (@ $args_ready:expr; $k:expr => $v:expr) => {
        kv!(@ ($crate::SingleKV::from(($k, $v)), $args_ready); )
    };
    (@ $args_ready:expr; $k:expr => $v:expr, $($args:tt)* ) => {
        kv!(@ ($crate::SingleKV::from(($k, $v)), $args_ready); $($args)* )
    };
    (@ $args_ready:expr; $kv:expr) => {
        kv!(@ ($kv, $args_ready); )
    };
    (@ $args_ready:expr; $kv:expr, $($args:tt)* ) => {
        kv!(@ ($kv, $args_ready); $($args)* )
    };
    (@ $args_ready:expr; ) => {
        $args_ready
    };
    (@ $args_ready:expr;, ) => {
        $args_ready
    };
    ($($args:tt)*) => {
        kv!(@ (); $($args)*)
    };
);

/// Alias of `kv`
#[macro_export(local_inner_macros)]
macro_rules! slog_kv(
    (@ $args_ready:expr; $k:expr => %$v:expr) => {
        slog_kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{}", $v))), $args_ready); )
    };
    (@ $args_ready:expr; $k:expr => %$v:expr, $($args:tt)* ) => {
        slog_kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{}", $v))), $args_ready); $($args)* )
    };
    (@ $args_ready:expr; $k:expr => ?$v:expr) => {
        kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{:?}", $v))), $args_ready); )
    };
    (@ $args_ready:expr; $k:expr => ?$v:expr, $($args:tt)* ) => {
        kv!(@ ($crate::SingleKV::from(($k, __slog_builtin!(@format_args "{:?}", $v))), $args_ready); $($args)* )
    };
    (@ $args_ready:expr; $k:expr => $v:expr) => {
        slog_kv!(@ ($crate::SingleKV::from(($k, $v)), $args_ready); )
    };
    (@ $args_ready:expr; $k:expr => $v:expr, $($args:tt)* ) => {
        slog_kv!(@ ($crate::SingleKV::from(($k, $v)), $args_ready); $($args)* )
    };
    (@ $args_ready:expr; $slog_kv:expr) => {
        slog_kv!(@ ($slog_kv, $args_ready); )
    };
    (@ $args_ready:expr; $slog_kv:expr, $($args:tt)* ) => {
        slog_kv!(@ ($slog_kv, $args_ready); $($args)* )
    };
    (@ $args_ready:expr; ) => {
        $args_ready
    };
    (@ $args_ready:expr;, ) => {
        $args_ready
    };
    ($($args:tt)*) => {
        slog_kv!(@ (); $($args)*)
    };
);

#[macro_export(local_inner_macros)]
/// Create `RecordStatic` at the given code location
macro_rules! record_static(
    ($lvl:expr, $tag:expr,) => { record_static!($lvl, $tag) };
    ($lvl:expr, $tag:expr) => {{
        static LOC : $crate::RecordLocation = $crate::RecordLocation {
            file: __slog_builtin!(@file),
            line: __slog_builtin!(@line),
            column: __slog_builtin!(@column),
            function: "",
            module: __slog_builtin!(@module_path),
        };
        $crate::RecordStatic {
            location : &LOC,
            level: $lvl,
            tag : $tag,
        }
    }};
);

#[macro_export(local_inner_macros)]
/// Create `RecordStatic` at the given code location (alias)
macro_rules! slog_record_static(
    ($lvl:expr, $tag:expr,) => { slog_record_static!($lvl, $tag) };
    ($lvl:expr, $tag:expr) => {{
        static LOC : $crate::RecordLocation = $crate::RecordLocation {
            file: __slog_builtin!(@file),
            line: __slog_builtin!(@line),
            column: __slog_builtin!(@column),
            function: "",
            module: __slog_builtin!(@module_path),
        };
        $crate::RecordStatic {
            location : &LOC,
            level: $lvl,
            tag: $tag,
        }
    }};
);

#[macro_export(local_inner_macros)]
/// Create `Record` at the given code location
///
/// Note that this requires that `lvl` and `tag` are compile-time constants. If
/// you need them to *not* be compile-time, such as when recreating a `Record`
/// from a serialized version, use `Record::new` instead.
macro_rules! record(
    ($lvl:expr, $tag:expr, $args:expr, $b:expr,) => {
        record!($lvl, $tag, $args, $b)
    };
    ($lvl:expr, $tag:expr, $args:expr, $b:expr) => {{
        #[allow(dead_code)]
        static RS : $crate::RecordStatic<'static> = record_static!($lvl, $tag);
        $crate::Record::new(&RS, $args, $b)
    }};
);

#[macro_export(local_inner_macros)]
/// Create `Record` at the given code location (alias)
macro_rules! slog_record(
    ($lvl:expr, $tag:expr, $args:expr, $b:expr,) => {
        slog_record!($lvl, $tag, $args, $b)
    };
    ($lvl:expr, $tag:expr, $args:expr, $b:expr) => {{
        static RS : $crate::RecordStatic<'static> = slog_record_static!($lvl,
                                                                        $tag);
        $crate::Record::new(&RS, $args, $b)
    }};
);

/// Log message a logging record
///
/// Use wrappers `error!`, `warn!` etc. instead
///
/// The `max_level_*` and `release_max_level*` cargo features can be used to
/// statically disable logging at various levels. See [slog notable
/// details](index.html#notable-details)
///
/// Use [version with longer name](macro.slog_log.html) if you want to prevent
/// clash with legacy `log` crate macro names.
///
/// ## Supported invocations
///
/// ### Simple
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let root = slog::Logger::root(
///         drain,
///         o!("key1" => "value1", "key2" => "value2")
///     );
///     info!(root, "test info log"; "log-key" => true);
/// }
/// ```
///
/// Note that `"key" => value` part is optional:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let root = slog::Logger::root(
///         drain, o!("key1" => "value1", "key2" => "value2")
///     );
///     info!(root, "test info log");
/// }
/// ```
///
/// ### Formatting support:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let root = slog::Logger::root(drain,
///         o!("key1" => "value1", "key2" => "value2")
///     );
///     info!(root, "formatted {num_entries} entries of {}", "something", num_entries = 2; "log-key" => true);
/// }
/// ```
///
/// Note:
///
/// * `;` is used to separate message arguments and key value pairs.
/// * message behaves like `format!`/`format_args!`
/// * Named arguments to messages will be added to key-value pairs as well!
///
/// `"key" => value` part is optional:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let root = slog::Logger::root(
///         drain, o!("key1" => "value1", "key2" => "value2")
///     );
///     info!(root, "formatted: {}", 1);
/// }
/// ```
///
/// Use formatting support wisely. Prefer named arguments, so the associated
/// data is not "lost" by becoming an untyped string in the message.
///
/// ### Tags
///
/// All above versions can be supplemented with a tag - string literal prefixed
/// with `#`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let root = slog::Logger::root(drain,
///         o!("key1" => "value1", "key2" => "value2")
///     );
///     let ops = 3;
///     info!(
///         root,
///         #"performance-metric", "thread speed"; "ops_per_sec" => ops
///     );
/// }
/// ```
///
/// See `Record::tag()` for more information about tags.
///
/// ### Own implementations of `KV` and `Value`
///
/// List of key value pairs is a comma separated list of key-values. Typically,
/// a designed syntax is used in form of `k => v` where `k` can be any type
/// that implements `Value` type.
///
/// It's possible to directly specify type that implements `KV` trait without
/// `=>` syntax.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// use slog::*;
///
/// fn main() {
///     struct MyKV;
///     struct MyV;
///
///     impl KV for MyKV {
///        fn serialize(&self,
///                     _record: &Record,
///                     serializer: &mut Serializer)
///                    -> Result {
///            serializer.emit_u32("MyK", 16)
///        }
///     }
///
///     impl Value for MyV {
///        fn serialize(&self,
///                     _record: &Record,
///                     key : Key,
///                     serializer: &mut Serializer)
///                    -> Result {
///            serializer.emit_u32("MyKV", 16)
///        }
///     }
///
///     let drain = slog::Discard;
///
///     let root = slog::Logger::root(drain, o!(MyKV));
///
///     info!(
///         root,
///         "testing MyV"; "MyV" => MyV
///     );
/// }
/// ```
///
/// ### `fmt::Display` and `fmt::Debug` values
///
/// Value of any type that implements `std::fmt::Display` can be prefixed with
/// `%` in `k => v` expression to use it's text representation returned by
/// `format_args!("{}", v)`. This is especially useful for errors. Not that
/// this does not allocate any `String` since it operates on `fmt::Arguments`.
///
/// Similarly to use `std::fmt::Debug` value can be prefixed with `?`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use std::fmt::Write;
///
/// fn main() {
///     let drain = slog::Discard;
///     let log  = slog::Logger::root(drain, o!());
///
///     let mut output = String::new();
///
///     if let Err(e) = write!(&mut output, "write to string") {
///         error!(log, "write failed"; "err" => %e);
///     }
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! log(
    // `2` means that `;` was already found
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* },  $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
      $l.log(&record!($lvl, $tag, &__slog_builtin!(@format_args $msg_fmt, $($fmt)*), b!($($kv)*)))
   };
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
       log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr;) => {
       log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $($args:tt)*) => {
       log!(2 @ { $($fmt)* }, { $($kv)* $($args)*}, $l, $lvl, $tag, $msg_fmt)
   };
    // `1` means that we are still looking for `;`
    // -- handle named arguments to format string
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr) => {
       log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr;) => {
       log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr,) => {
       log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr; $($args:tt)*) => {
       log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr, $($args:tt)*) => {
       log!(1 @ { $($fmt)* $k = $v, }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
    // -- look for `;` termination
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
       log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
       log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, ; $($args:tt)*) => {
       log!(1 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt; $($args)*)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr; $($args:tt)*) => {
       log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
    // -- must be normal argument to format string
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $f:tt $($args:tt)*) => {
       log!(1 @ { $($fmt)* $f }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
   ($l:expr, $lvl:expr, $tag:expr, $($args:tt)*) => {
       if $lvl.as_usize() <= $crate::__slog_static_max_level().as_usize() {
           log!(1 @ { }, { }, $l, $lvl, $tag, $($args)*)
       }
   };
);

/// Log message a logging record (alias)
///
/// Prefer [shorter version](macro.log.html), unless it clashes with
/// existing `log` crate macro.
///
/// See [`log`](macro.log.html) for documentation.
///
/// ```
/// #[macro_use(slog_o,slog_b,slog_record,slog_record_static,slog_log,slog_info,slog_kv,__slog_builtin)]
/// extern crate slog;
///
/// fn main() {
///     let log = slog::Logger::root(slog::Discard, slog_o!());
///
///     slog_info!(log, "some interesting info"; "where" => "right here");
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! slog_log(
    // `2` means that `;` was already found
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* },  $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
      $l.log(&slog_record!($lvl, $tag, &__slog_builtin!(@format_args $msg_fmt, $($fmt)*), slog_b!($($kv)*)))
   };
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
       slog_log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr;) => {
       slog_log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (2 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $($args:tt)*) => {
       slog_log!(2 @ { $($fmt)* }, { $($kv)* $($args)*}, $l, $lvl, $tag, $msg_fmt)
   };
    // `1` means that we are still looking for `;`
    // -- handle named arguments to format string
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr) => {
       slog_log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr;) => {
       slog_log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr,) => {
       slog_log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr; $($args:tt)*) => {
       slog_log!(2 @ { $($fmt)* $k = $v }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $k:ident = $v:expr, $($args:tt)*) => {
       slog_log!(1 @ { $($fmt)* $k = $v, }, { $($kv)* __slog_builtin!(@stringify $k) => $v, }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
    // -- look for `;` termination
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
       slog_log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
       slog_log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, ; $($args:tt)*) => {
       slog_log!(1 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt; $($args)*)
   };
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr; $($args:tt)*) => {
       slog_log!(2 @ { $($fmt)* }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
    // -- must be normal argument to format string
   (1 @ { $($fmt:tt)* }, { $($kv:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $f:tt $($args:tt)*) => {
       slog_log!(1 @ { $($fmt)* $f }, { $($kv)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
   };
   ($l:expr, $lvl:expr, $tag:expr, $($args:tt)*) => {
       if $lvl.as_usize() <= $crate::__slog_static_max_level().as_usize() {
           slog_log!(1 @ { }, { }, $l, $lvl, $tag, $($args)*)
       }
   };
);
/// Log critical level record
///
/// See `log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! crit(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Critical, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Critical, "", $($args)+)
    };
);

/// Log critical level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! slog_crit(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Critical, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Critical, "", $($args)+)
    };
);

/// Log error level record
///
/// See `log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! error(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Error, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Error, "", $($args)+)
    };
);

/// Log error level record
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! slog_error(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Error, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Error, "", $($args)+)
    };
);

/// Log warning level record
///
/// See `log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! warn(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Warning, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Warning, "", $($args)+)
    };
);

/// Log warning level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! slog_warn(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Warning, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Warning, "", $($args)+)
    };
);

/// Log info level record
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! info(
    ($l:expr, #$tag:expr, $($args:tt)*) => {
        log!($l, $crate::Level::Info, $tag, $($args)*)
    };
    ($l:expr, $($args:tt)*) => {
        log!($l, $crate::Level::Info, "", $($args)*)
    };
);

/// Log info level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! slog_info(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Info, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Info, "", $($args)+)
    };
);

/// Log debug level record
///
/// See `log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! debug(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Debug, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Debug, "", $($args)+)
    };
);

/// Log debug level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! slog_debug(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Debug, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Debug, "", $($args)+)
    };
);

/// Log trace level record
///
/// See `log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! trace(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Trace, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        log!($l, $crate::Level::Trace, "", $($args)+)
    };
);

/// Log trace level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export(local_inner_macros)]
macro_rules! slog_trace(
    ($l:expr, #$tag:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Trace, $tag, $($args)+)
    };
    ($l:expr, $($args:tt)+) => {
        slog_log!($l, $crate::Level::Trace, "", $($args)+)
    };
    ($($args:tt)+) => {
        slog_log!($crate::Level::Trace, $($args)+)
    };
);

/// Helper macro for using the built-in macros inside of
/// exposed macros with `local_inner_macros` attribute.
#[doc(hidden)]
#[macro_export]
macro_rules! __slog_builtin {
    (@format_args $($t:tt)*) => ( format_args!($($t)*) );
    (@stringify $($t:tt)*) => ( stringify!($($t)*) );
    (@file) => ( file!() );
    (@line) => ( line!() );
    (@column) => ( column!() );
    (@module_path) => ( module_path!() );
}

// }}}

// {{{ Logger
/// Logging handle used to execute logging statements
///
/// In an essence `Logger` instance holds two pieces of information:
///
/// * drain - destination where to forward logging `Record`s for
/// processing.
/// * context - list of key-value pairs associated with it.
///
/// Root `Logger` is created with a `Drain` that will be cloned to every
/// member of it's hierarchy.
///
/// Child `Logger` are built from existing ones, and inherit their key-value
/// pairs, which can be supplemented with additional ones.
///
/// Cloning existing loggers and creating new ones is cheap. Loggers can be
/// freely passed around the code and between threads.
///
/// `Logger`s are `Sync+Send` - there's no need to synchronize accesses to them,
/// as they can accept logging records from multiple threads at once. They can
/// be sent to any thread. Because of that they require the `Drain` to be
/// `Sync+Sync` as well. Not all `Drain`s are `Sync` or `Send` but they can
/// often be made so by wrapping in a `Mutex` and/or `Arc`.
///
/// `Logger` implements `Drain` trait. Any logging `Record` delivered to
/// a `Logger` functioning as a `Drain`, will be delivered to it's `Drain`
/// with existing key-value pairs appended to the `Logger`s key-value pairs.
/// By itself it's effectively very similar to `Logger` being an ancestor
/// of `Logger` that originated the logging `Record`. Combined with other
/// `Drain`s, allows custom processing logic for a sub-tree of a whole logging
/// tree.
///
/// Logger is parametrized over type of a `Drain` associated with it (`D`). It
/// default to type-erased version so `Logger` without any type annotation
/// means `Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>`. See
/// `Logger::root_typed` and `Logger::to_erased` for more information.
#[derive(Clone)]
pub struct Logger<D = Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
    D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
    drain: D,
    list: OwnedKVList,
}

impl<D> Logger<D>
where
    D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
    /// Build a root `Logger`
    ///
    /// Root logger starts a new tree associated with a given `Drain`. Root
    /// logger drain must return no errors. See `Drain::ignore_res()` and
    /// `Drain::fuse()`.
    ///
    /// All children and their children (and so on), form one logging tree
    /// sharing a common drain. See `Logger::new`.
    ///
    /// This version (as opposed to `Logger:root_typed`) will take `drain` and
    /// made it into `Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>`.
    /// This is typically the most convenient way to work with `Logger`s.
    ///
    /// Use `o!` macro to build `OwnedKV` object.
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    ///
    /// fn main() {
    ///     let _root = slog::Logger::root(
    ///         slog::Discard,
    ///         o!("key1" => "value1", "key2" => "value2"),
    ///     );
    /// }
    /// ```
    pub fn root<T>(drain: D, values: OwnedKV<T>) -> Logger
    where
        D: 'static + SendSyncRefUnwindSafeDrain<Err = Never, Ok = ()>,
        T: SendSyncRefUnwindSafeKV + 'static,
    {
        Logger {
            drain: Arc::new(drain)
                as Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>,
            list: OwnedKVList::root(values),
        }
    }

    /// Build a root `Logger` that retains `drain` type
    ///
    /// Unlike `Logger::root`, this constructor retains the type of a `drain`,
    /// which allows highest performance possible by eliminating indirect call
    /// on `Drain::log`, and allowing monomorphization of `Logger` and `Drain`
    /// objects.
    ///
    /// If you don't understand the implications, you should probably just
    /// ignore it.
    ///
    /// See `Logger:into_erased` and `Logger::to_erased` for conversion from
    /// type returned by this function to version that would be returned by
    /// `Logger::root`.
    pub fn root_typed<T>(drain: D, values: OwnedKV<T>) -> Logger<D>
    where
        D: 'static + SendSyncUnwindSafeDrain<Err = Never, Ok = ()> + Sized,
        T: SendSyncRefUnwindSafeKV + 'static,
    {
        Logger {
            drain: drain,
            list: OwnedKVList::root(values),
        }
    }

    /// Build a child logger
    ///
    /// Child logger inherits all existing key-value pairs from its parent and
    /// supplements them with additional ones.
    ///
    /// Use `o!` macro to build `OwnedKV` object.
    ///
    /// ### Drain cloning (`D : Clone` requirement)
    ///
    /// All children, their children and so on, form one tree sharing a
    /// common drain. This drain, will be `Clone`d when this method is called.
    /// That is why `Clone` must be implemented for `D` in `Logger<D>::new`.
    ///
    /// For some `Drain` types `Clone` is cheap or even free (a no-op). This is
    /// the case for any `Logger` returned by `Logger::root` and it's children.
    ///
    /// When using `Logger::root_typed`, it's possible that cloning might be
    /// expensive, or even impossible.
    ///
    /// The reason why wrapping in an `Arc` is not done internally, and exposed
    /// to the user is performance. Calling `Drain::log` through an `Arc` is
    /// tiny bit slower than doing it directly.
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    ///
    /// fn main() {
    ///     let root = slog::Logger::root(slog::Discard,
    ///         o!("key1" => "value1", "key2" => "value2"));
    ///     let _log = root.new(o!("key" => "value"));
    /// }
    #[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
    pub fn new<T>(&self, values: OwnedKV<T>) -> Logger<D>
    where
        T: SendSyncRefUnwindSafeKV + 'static,
        D: Clone,
    {
        Logger {
            drain: self.drain.clone(),
            list: OwnedKVList::new(values, self.list.node.clone()),
        }
    }

    /// Log one logging `Record`
    ///
    /// Use specific logging functions instead. See `log!` macro
    /// documentation.
    #[inline]
    pub fn log(&self, record: &Record) {
        let _ = self.drain.log(record, &self.list);
    }

    /// Get list of key-value pairs assigned to this `Logger`
    pub fn list(&self) -> &OwnedKVList {
        &self.list
    }

    /// Convert to default, "erased" type:
    /// `Logger<Arc<SendSyncUnwindSafeDrain>>`
    ///
    /// Useful to adapt `Logger<D : Clone>` to an interface expecting
    /// `Logger<Arc<...>>`.
    ///
    /// Note that calling on a `Logger<Arc<...>>` will convert it to
    /// `Logger<Arc<Arc<...>>>` which is not optimal. This might be fixed when
    /// Rust gains trait implementation specialization.
    pub fn into_erased(
        self,
    ) -> Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
    where
        D: SendRefUnwindSafeDrain + 'static,
    {
        Logger {
            drain: Arc::new(self.drain)
                as Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>,
            list: self.list,
        }
    }

    /// Create a copy with "erased" type
    ///
    /// See `into_erased`
    pub fn to_erased(
        &self,
    ) -> Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
    where
        D: SendRefUnwindSafeDrain + 'static + Clone,
    {
        self.clone().into_erased()
    }
}

impl<D> fmt::Debug for Logger<D>
where
    D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "Logger{:?}", self.list));
        Ok(())
    }
}

impl<D> Drain for Logger<D>
where
    D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
    type Ok = ();
    type Err = Never;

    fn log(
        &self,
        record: &Record,
        values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        let chained = OwnedKVList {
            node: Arc::new(MultiListNode {
                next_node: values.node.clone(),
                node: self.list.node.clone(),
            }),
        };
        self.drain.log(record, &chained)
    }

    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        self.drain.is_enabled(level)
    }
}

// {{{ Drain
/// Logging drain
///
/// `Drain`s typically mean destination for logs, but `slog` generalizes the
/// term.
///
/// `Drain`s are responsible for handling logging statements (`Record`s) from
/// `Logger`s associated with them: filtering, modifying, formatting
/// and writing the log records into given destination(s).
///
/// It's a typical pattern to parametrize `Drain`s over `Drain` traits to allow
/// composing `Drain`s.
///
/// Implementing this trait allows writing custom `Drain`s. Slog users should
/// not be afraid of implementing their own `Drain`s. Any custom log handling
/// logic should be implemented as a `Drain`.
pub trait Drain {
    /// Type returned by this drain
    ///
    /// It can be useful in some circumstances, but rarely. It will probably
    /// default to `()` once https://github.com/rust-lang/rust/issues/29661 is
    /// stable.
    type Ok;
    /// Type of potential errors that can be returned by this `Drain`
    type Err;
    /// Handle one logging statement (`Record`)
    ///
    /// Every logging `Record` built from a logging statement (eg.
    /// `info!(...)`), and key-value lists of a `Logger` it was executed on
    /// will be passed to the root drain registered during `Logger::root`.
    ///
    /// Typically `Drain`s:
    ///
    /// * pass this information (or not) to the sub-logger(s) (filters)
    /// * format and write the information to a destination (writers)
    /// * deal with the errors returned from the sub-logger(s)
    fn log(
        &self,
        record: &Record,
        values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err>;

    /// **Avoid**: Check if messages at the specified log level are **maybe**
    /// enabled for this logger.
    ///
    /// The purpose of it so to allow **imprecise** detection if a given logging
    /// level has any chance of actually being logged. This might be used
    /// to explicitly skip needless computation.
    ///
    /// **It is best effort, can return false positives, but not false negatives.**
    ///
    /// The logger is still free to ignore records even if the level is enabled,
    /// so an enabled level doesn't necessarily guarantee that the record will
    /// actually be logged.
    ///
    /// This function is somewhat needless, and is better expressed by using
    /// lazy values (see `FnValue`).  A `FnValue` is more precise and does not
    /// require additional (potentially recursive) calls to do something that
    /// `log` will already do anyways (making decision if something should be
    /// logged or not).
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate slog;
    /// # use slog::*;
    /// # fn main() {
    /// let logger = Logger::root(Discard, o!());
    /// if logger.is_enabled(Level::Debug) {
    ///     let num = 5.0f64;
    ///     let sqrt = num.sqrt();
    ///     debug!(logger, "Sqrt"; "num" => num, "sqrt" => sqrt);
    /// }
    /// # }
    /// ```
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        level.as_usize() <= ::__slog_static_max_level().as_usize()
    }

    /// **Avoid**: See `is_enabled`
    #[inline]
    fn is_critical_enabled(&self) -> bool {
        self.is_enabled(Level::Critical)
    }

    /// **Avoid**: See `is_enabled`
    #[inline]
    fn is_error_enabled(&self) -> bool {
        self.is_enabled(Level::Error)
    }

    /// **Avoid**: See `is_enabled`
    #[inline]
    fn is_warning_enabled(&self) -> bool {
        self.is_enabled(Level::Warning)
    }

    /// **Avoid**: See `is_enabled`
    #[inline]
    fn is_info_enabled(&self) -> bool {
        self.is_enabled(Level::Info)
    }

    /// **Avoid**: See `is_enabled`
    #[inline]
    fn is_debug_enabled(&self) -> bool {
        self.is_enabled(Level::Debug)
    }

    /// **Avoid**: See `is_enabled`
    #[inline]
    fn is_trace_enabled(&self) -> bool {
        self.is_enabled(Level::Trace)
    }

    /// Pass `Drain` through a closure, eg. to wrap
    /// into another `Drain`.
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    /// use slog::*;
    ///
    /// fn main() {
    ///     let _drain = Discard.map(Fuse);
    /// }
    /// ```
    fn map<F, R>(self, f: F) -> R
    where
        Self: Sized,
        F: FnOnce(Self) -> R,
    {
        f(self)
    }

    /// Filter logging records passed to `Drain`
    ///
    /// Wrap `Self` in `Filter`
    ///
    /// This will convert `self` to a `Drain that ignores `Record`s
    /// for which `f` returns false.
    fn filter<F>(self, f: F) -> Filter<Self, F>
    where
        Self: Sized,
        F: FilterFn,
    {
        Filter::new(self, f)
    }

    /// Filter logging records passed to `Drain` (by level)
    ///
    /// Wrap `Self` in `LevelFilter`
    ///
    /// This will convert `self` to a `Drain that ignores `Record`s of
    /// logging lever smaller than `level`.
    fn filter_level(self, level: Level) -> LevelFilter<Self>
    where
        Self: Sized,
    {
        LevelFilter(self, level)
    }

    /// Map logging errors returned by this drain
    ///
    /// `f` is a closure that takes `Drain::Err` returned by a given
    /// drain, and returns new error of potentially different type
    fn map_err<F, E>(self, f: F) -> MapError<Self, E>
    where
        Self: Sized,
        F: MapErrFn<Self::Err, E>,
    {
        MapError::new(self, f)
    }

    /// Ignore results returned by this drain
    ///
    /// Wrap `Self` in `IgnoreResult`
    fn ignore_res(self) -> IgnoreResult<Self>
    where
        Self: Sized,
    {
        IgnoreResult::new(self)
    }

    /// Make `Self` panic when returning any errors
    ///
    /// Wrap `Self` in `Map`
    fn fuse(self) -> Fuse<Self>
    where
        Self::Err: fmt::Debug,
        Self: Sized,
    {
        self.map(Fuse)
    }
}

impl<'a, D: Drain + 'a> Drain for &'a D {
    type Ok = D::Ok;
    type Err = D::Err;
    #[inline]
    fn log(
        &self,
        record: &Record,
        values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        (**self).log(record, values)
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        (**self).is_enabled(level)
    }
}

impl<'a, D: Drain + 'a> Drain for &'a mut D {
    type Ok = D::Ok;
    type Err = D::Err;
    #[inline]
    fn log(
        &self,
        record: &Record,
        values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        (**self).log(record, values)
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        (**self).is_enabled(level)
    }
}

#[cfg(feature = "std")]
/// `Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafe: Send + Sync + UnwindSafe {}

#[cfg(feature = "std")]
impl<T> SendSyncUnwindSafe for T
where
    T: Send + Sync + UnwindSafe + ?Sized,
{
}

#[cfg(feature = "std")]
/// `Drain + Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafeDrain: Drain + Send + Sync + UnwindSafe {}

#[cfg(feature = "std")]
impl<T> SendSyncUnwindSafeDrain for T
where
    T: Drain + Send + Sync + UnwindSafe + ?Sized,
{
}

#[cfg(feature = "std")]
/// `Drain + Send + Sync + RefUnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncRefUnwindSafeDrain: Drain + Send + Sync + RefUnwindSafe {}

#[cfg(feature = "std")]
impl<T> SendSyncRefUnwindSafeDrain for T
where
    T: Drain + Send + Sync + RefUnwindSafe + ?Sized,
{
}

#[cfg(feature = "std")]
/// Function that can be used in `MapErr` drain
pub trait MapErrFn<EI, EO>
    : 'static + Sync + Send + UnwindSafe + RefUnwindSafe + Fn(EI) -> EO {
}

#[cfg(feature = "std")]
impl<T, EI, EO> MapErrFn<EI, EO> for T
where
    T: 'static
        + Sync
        + Send
        + ?Sized
        + UnwindSafe
        + RefUnwindSafe
        + Fn(EI) -> EO,
{
}

#[cfg(feature = "std")]
/// Function that can be used in `Filter` drain
pub trait FilterFn
    : 'static + Sync + Send + UnwindSafe + RefUnwindSafe + Fn(&Record) -> bool {
}

#[cfg(feature = "std")]
impl<T> FilterFn for T
where
    T: 'static
        + Sync
        + Send
        + ?Sized
        + UnwindSafe
        + RefUnwindSafe
        + Fn(&Record) -> bool,
{
}

#[cfg(not(feature = "std"))]
/// `Drain + Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafeDrain: Drain + Send + Sync {}

#[cfg(not(feature = "std"))]
impl<T> SendSyncUnwindSafeDrain for T
where
    T: Drain + Send + Sync + ?Sized,
{
}

#[cfg(not(feature = "std"))]
/// `Drain + Send + Sync + RefUnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncRefUnwindSafeDrain: Drain + Send + Sync {}

#[cfg(not(feature = "std"))]
impl<T> SendSyncRefUnwindSafeDrain for T
where
    T: Drain + Send + Sync + ?Sized,
{
}

#[cfg(feature = "std")]
/// `Drain + Send + RefUnwindSafe` bound
pub trait SendRefUnwindSafeDrain: Drain + Send + RefUnwindSafe {}

#[cfg(feature = "std")]
impl<T> SendRefUnwindSafeDrain for T
where
    T: Drain + Send + RefUnwindSafe + ?Sized,
{
}

#[cfg(not(feature = "std"))]
/// `Drain + Send + RefUnwindSafe` bound
pub trait SendRefUnwindSafeDrain: Drain + Send {}

#[cfg(not(feature = "std"))]
impl<T> SendRefUnwindSafeDrain for T
where
    T: Drain + Send + ?Sized,
{
}

#[cfg(not(feature = "std"))]
/// Function that can be used in `MapErr` drain
pub trait MapErrFn<EI, EO>: 'static + Sync + Send + Fn(EI) -> EO {}

#[cfg(not(feature = "std"))]
impl<T, EI, EO> MapErrFn<EI, EO> for T
where
    T: 'static + Sync + Send + ?Sized + Fn(EI) -> EO,
{
}

#[cfg(not(feature = "std"))]
/// Function that can be used in `Filter` drain
pub trait FilterFn: 'static + Sync + Send + Fn(&Record) -> bool {}

#[cfg(not(feature = "std"))]
impl<T> FilterFn for T
where
    T: 'static + Sync + Send + ?Sized + Fn(&Record) -> bool,
{
}

impl<D: Drain + ?Sized> Drain for Box<D> {
    type Ok = D::Ok;
    type Err = D::Err;
    fn log(
        &self,
        record: &Record,
        o: &OwnedKVList,
    ) -> result::Result<Self::Ok, D::Err> {
        (**self).log(record, o)
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        (**self).is_enabled(level)
    }
}

impl<D: Drain + ?Sized> Drain for Arc<D> {
    type Ok = D::Ok;
    type Err = D::Err;
    fn log(
        &self,
        record: &Record,
        o: &OwnedKVList,
    ) -> result::Result<Self::Ok, D::Err> {
        (**self).log(record, o)
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        (**self).is_enabled(level)
    }
}

/// `Drain` discarding everything
///
/// `/dev/null` of `Drain`s
#[derive(Debug, Copy, Clone)]
pub struct Discard;

impl Drain for Discard {
    type Ok = ();
    type Err = Never;
    fn log(&self, _: &Record, _: &OwnedKVList) -> result::Result<(), Never> {
        Ok(())
    }
    #[inline]
    fn is_enabled(&self, _1: Level) -> bool {
        false
    }
}

/// `Drain` filtering records
///
/// Wraps another `Drain` and passes `Record`s to it, only if they satisfy a
/// given condition.
#[derive(Debug, Clone)]
pub struct Filter<D: Drain, F>(pub D, pub F)
where
    F: Fn(&Record) -> bool + 'static + Send + Sync;

impl<D: Drain, F> Filter<D, F>
where
    F: FilterFn,
{
    /// Create `Filter` wrapping given `drain`
    pub fn new(drain: D, cond: F) -> Self {
        Filter(drain, cond)
    }
}

impl<D: Drain, F> Drain for Filter<D, F>
where
    F: FilterFn,
{
    type Ok = Option<D::Ok>;
    type Err = D::Err;
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        if (self.1)(record) {
            Ok(Some(self.0.log(record, logger_values)?))
        } else {
            Ok(None)
        }
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        /*
         * This is one of the reasons we can't guarantee the value is actually logged.
         * The filter function is given dynamic control over whether or not the record is logged
         * and could filter stuff out even if the log level is supposed to be enabled
         */
        self.0.is_enabled(level)
    }
}

/// `Drain` filtering records by `Record` logging level
///
/// Wraps a drain and passes records to it, only
/// if their level is at least given level.
///
/// TODO: Remove this type. This drain is a special case of `Filter`, but
/// because `Filter` can not use static dispatch ATM due to Rust limitations
/// that will be lifted in the future, it is a standalone type.
/// Reference: https://github.com/rust-lang/rust/issues/34511
#[derive(Debug, Clone)]
pub struct LevelFilter<D: Drain>(pub D, pub Level);

impl<D: Drain> LevelFilter<D> {
    /// Create `LevelFilter`
    pub fn new(drain: D, level: Level) -> Self {
        LevelFilter(drain, level)
    }
}

impl<D: Drain> Drain for LevelFilter<D> {
    type Ok = Option<D::Ok>;
    type Err = D::Err;
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        if record.level().is_at_least(self.1) {
            Ok(Some(self.0.log(record, logger_values)?))
        } else {
            Ok(None)
        }
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        level.is_at_least(self.1) && self.0.is_enabled(level)
    }
}

/// `Drain` mapping error returned by another `Drain`
///
/// See `Drain::map_err` for convenience function.
pub struct MapError<D: Drain, E> {
    drain: D,
    // eliminated dynamic dispatch, after rust learns `-> impl Trait`
    map_fn: Box<MapErrFn<D::Err, E, Output = E>>,
}

impl<D: Drain, E> MapError<D, E> {
    /// Create `Filter` wrapping given `drain`
    pub fn new<F>(drain: D, map_fn: F) -> Self
    where
        F: MapErrFn<<D as Drain>::Err, E>,
    {
        MapError {
            drain: drain,
            map_fn: Box::new(map_fn),
        }
    }
}

impl<D: Drain, E> Drain for MapError<D, E> {
    type Ok = D::Ok;
    type Err = E;
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        self.drain
            .log(record, logger_values)
            .map_err(|e| (self.map_fn)(e))
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        self.drain.is_enabled(level)
    }
}

/// `Drain` duplicating records into two other `Drain`s
///
/// Can be nested for more than two outputs.
#[derive(Debug, Clone)]
pub struct Duplicate<D1: Drain, D2: Drain>(pub D1, pub D2);

impl<D1: Drain, D2: Drain> Duplicate<D1, D2> {
    /// Create `Duplicate`
    pub fn new(drain1: D1, drain2: D2) -> Self {
        Duplicate(drain1, drain2)
    }
}

impl<D1: Drain, D2: Drain> Drain for Duplicate<D1, D2> {
    type Ok = (D1::Ok, D2::Ok);
    type Err = (
        result::Result<D1::Ok, D1::Err>,
        result::Result<D2::Ok, D2::Err>,
    );
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        let res1 = self.0.log(record, logger_values);
        let res2 = self.1.log(record, logger_values);

        match (res1, res2) {
            (Ok(o1), Ok(o2)) => Ok((o1, o2)),
            (r1, r2) => Err((r1, r2)),
        }
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        self.0.is_enabled(level) || self.1.is_enabled(level)
    }
}

/// `Drain` panicking on error
///
/// `Logger` requires a root drain to handle all errors (`Drain::Error == ()`),
/// `Fuse` will wrap a `Drain` and panic if it returns any errors.
///
/// Note: `Drain::Err` must implement `Display` (for displaying on panic). It's
/// easy to create your own `Fuse` drain if this requirement can't be fulfilled.
#[derive(Debug, Clone)]
pub struct Fuse<D: Drain>(pub D)
where
    D::Err: fmt::Debug;

impl<D: Drain> Fuse<D>
where
    D::Err: fmt::Debug,
{
    /// Create `Fuse` wrapping given `drain`
    pub fn new(drain: D) -> Self {
        Fuse(drain)
    }
}

impl<D: Drain> Drain for Fuse<D>
where
    D::Err: fmt::Debug,
{
    type Ok = ();
    type Err = Never;
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Never> {
        let _ = self.0
            .log(record, logger_values)
            .unwrap_or_else(|e| panic!("slog::Fuse Drain: {:?}", e));
        Ok(())
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        self.0.is_enabled(level)
    }
}

/// `Drain` ignoring result
///
/// `Logger` requires a root drain to handle all errors (`Drain::Err=()`), and
/// returns nothing (`Drain::Ok=()`) `IgnoreResult` will ignore any result
/// returned by the `Drain` it wraps.
#[derive(Clone)]
pub struct IgnoreResult<D: Drain> {
    drain: D,
}

impl<D: Drain> IgnoreResult<D> {
    /// Create `IgnoreResult` wrapping `drain`
    pub fn new(drain: D) -> Self {
        IgnoreResult { drain: drain }
    }
}

impl<D: Drain> Drain for IgnoreResult<D> {
    type Ok = ();
    type Err = Never;
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<(), Never> {
        let _ = self.drain.log(record, logger_values);
        Ok(())
    }

    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        self.drain.is_enabled(level)
    }
}

/// Error returned by `Mutex<D : Drain>`
#[cfg(feature = "std")]
#[derive(Clone)]
pub enum MutexDrainError<D: Drain> {
    /// Error acquiring mutex
    Mutex,
    /// Error returned by drain
    Drain(D::Err),
}

#[cfg(feature = "std")]
impl<D> fmt::Debug for MutexDrainError<D>
where
    D: Drain,
    D::Err: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
        match *self {
            MutexDrainError::Mutex => write!(f, "MutexDrainError::Mutex"),
            MutexDrainError::Drain(ref e) => e.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl<D> std::error::Error for MutexDrainError<D>
where
    D: Drain,
    D::Err: fmt::Debug + fmt::Display + std::error::Error,
{
    fn description(&self) -> &str {
        match *self {
            MutexDrainError::Mutex => "Mutex acquire failed",
            MutexDrainError::Drain(ref e) => e.description(),
        }
    }

    fn cause(&self) -> Option<&std::error::Error> {
        match *self {
            MutexDrainError::Mutex => None,
            MutexDrainError::Drain(ref e) => Some(e),
        }
    }
}

#[cfg(feature = "std")]
impl<'a, D: Drain> From<std::sync::PoisonError<std::sync::MutexGuard<'a, D>>>
    for MutexDrainError<D> {
    fn from(
        _: std::sync::PoisonError<std::sync::MutexGuard<'a, D>>,
    ) -> MutexDrainError<D> {
        MutexDrainError::Mutex
    }
}

#[cfg(feature = "std")]
impl<D: Drain> fmt::Display for MutexDrainError<D>
where
    D::Err: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
        match *self {
            MutexDrainError::Mutex => write!(f, "MutexError"),
            MutexDrainError::Drain(ref e) => write!(f, "{}", e),
        }
    }
}

#[cfg(feature = "std")]
impl<D: Drain> Drain for std::sync::Mutex<D> {
    type Ok = D::Ok;
    type Err = MutexDrainError<D>;
    fn log(
        &self,
        record: &Record,
        logger_values: &OwnedKVList,
    ) -> result::Result<Self::Ok, Self::Err> {
        let d = self.lock()?;
        d.log(record, logger_values).map_err(MutexDrainError::Drain)
    }
    #[inline]
    fn is_enabled(&self, level: Level) -> bool {
        self.lock().ok().map_or(true, |lock| lock.is_enabled(level))
    }
}
// }}}

// {{{ Level & FilterLevel
/// Official capitalized logging (and logging filtering) level names
///
/// In order of `as_usize()`.
pub static LOG_LEVEL_NAMES: [&'static str; 7] =
    ["OFF", "CRITICAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];

/// Official capitalized logging (and logging filtering) short level names
///
/// In order of `as_usize()`.
pub static LOG_LEVEL_SHORT_NAMES: [&'static str; 7] =
    ["OFF", "CRIT", "ERRO", "WARN", "INFO", "DEBG", "TRCE"];

/// Logging level associated with a logging `Record`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Level {
    /// Critical
    Critical,
    /// Error
    Error,
    /// Warning
    Warning,
    /// Info
    Info,
    /// Debug
    Debug,
    /// Trace
    Trace,
}

/// Logging filtering level
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum FilterLevel {
    /// Log nothing
    Off,
    /// Log critical level only
    Critical,
    /// Log only error level and above
    Error,
    /// Log only warning level and above
    Warning,
    /// Log only info level and above
    Info,
    /// Log only debug level and above
    Debug,
    /// Log everything
    Trace,
}

impl Level {
    /// Convert to `str` from `LOG_LEVEL_SHORT_NAMES`
    pub fn as_short_str(&self) -> &'static str {
        LOG_LEVEL_SHORT_NAMES[self.as_usize()]
    }

    /// Convert to `str` from `LOG_LEVEL_NAMES`
    pub fn as_str(&self) -> &'static str {
        LOG_LEVEL_NAMES[self.as_usize()]
    }

    /// Cast `Level` to ordering integer
    ///
    /// `Critical` is the smallest and `Trace` the biggest value
    #[inline]
    pub fn as_usize(&self) -> usize {
        match *self {
            Level::Critical => 1,
            Level::Error => 2,
            Level::Warning => 3,
            Level::Info => 4,
            Level::Debug => 5,
            Level::Trace => 6,
        }
    }

    /// Get a `Level` from an `usize`
    ///
    /// This complements `as_usize`
    #[inline]
    pub fn from_usize(u: usize) -> Option<Level> {
        match u {
            1 => Some(Level::Critical),
            2 => Some(Level::Error),
            3 => Some(Level::Warning),
            4 => Some(Level::Info),
            5 => Some(Level::Debug),
            6 => Some(Level::Trace),
            _ => None,
        }
    }
}

impl FilterLevel {
    /// Convert to `str` from `LOG_LEVEL_SHORT_NAMES`
    pub fn as_short_str(&self) -> &'static str {
        LOG_LEVEL_SHORT_NAMES[self.as_usize()]
    }

    /// Convert to `str` from `LOG_LEVEL_NAMES`
    pub fn as_str(&self) -> &'static str {
        LOG_LEVEL_NAMES[self.as_usize()]
    }

    /// Convert to `usize` value
    ///
    /// `Off` is 0, and `Trace` 6
    #[inline]
    pub fn as_usize(&self) -> usize {
        match *self {
            FilterLevel::Off => 0,
            FilterLevel::Critical => 1,
            FilterLevel::Error => 2,
            FilterLevel::Warning => 3,
            FilterLevel::Info => 4,
            FilterLevel::Debug => 5,
            FilterLevel::Trace => 6,
        }
    }

    /// Get a `FilterLevel` from an `usize`
    ///
    /// This complements `as_usize`
    #[inline]
    pub fn from_usize(u: usize) -> Option<FilterLevel> {
        match u {
            0 => Some(FilterLevel::Off),
            1 => Some(FilterLevel::Critical),
            2 => Some(FilterLevel::Error),
            3 => Some(FilterLevel::Warning),
            4 => Some(FilterLevel::Info),
            5 => Some(FilterLevel::Debug),
            6 => Some(FilterLevel::Trace),
            _ => None,
        }
    }

    /// Maximum logging level (log everything)
    #[inline]
    pub fn max() -> Self {
        FilterLevel::Trace
    }

    /// Minimum logging level (log nothing)
    #[inline]
    pub fn min() -> Self {
        FilterLevel::Off
    }

    /// Check if message with given level should be logged
    pub fn accepts(self, level: Level) -> bool {
        self.as_usize() >= level.as_usize()
    }
}

impl FromStr for Level {
    type Err = ();
    fn from_str(name: &str) -> core::result::Result<Level, ()> {
        index_of_log_level_name(name)
            .and_then(|idx| Level::from_usize(idx))
            .ok_or(())
    }
}

impl FromStr for FilterLevel {
    type Err = ();
    fn from_str(name: &str) -> core::result::Result<FilterLevel, ()> {
        index_of_log_level_name(name)
            .and_then(|idx| FilterLevel::from_usize(idx))
            .ok_or(())
    }
}

fn index_of_log_level_name(name: &str) -> Option<usize> {
    index_of_str_ignore_case(&LOG_LEVEL_NAMES, name)
        .or_else(|| index_of_str_ignore_case(&LOG_LEVEL_SHORT_NAMES, name))
}

fn index_of_str_ignore_case(haystack: &[&str], needle: &str) -> Option<usize> {
    if needle.is_empty() {
        return None;
    }
    haystack.iter()
        // This will never panic because haystack has only ASCII characters
        .map(|hay| &hay[..needle.len().min(hay.len())])
        .position(|hay| hay.eq_ignore_ascii_case(needle))
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_short_str())
    }
}

impl fmt::Display for FilterLevel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_short_str())
    }
}

impl Level {
    /// Returns true if `self` is at least `level` logging level
    #[inline]
    pub fn is_at_least(&self, level: Self) -> bool {
        self.as_usize() <= level.as_usize()
    }
}

#[test]
fn level_at_least() {
    assert!(Level::Debug.is_at_least(Level::Debug));
    assert!(Level::Debug.is_at_least(Level::Trace));
    assert!(!Level::Debug.is_at_least(Level::Info));
}

#[test]
fn filter_level_sanity() {
    assert!(Level::Critical.as_usize() > FilterLevel::Off.as_usize());
    assert!(Level::Critical.as_usize() == FilterLevel::Critical.as_usize());
    assert!(Level::Trace.as_usize() == FilterLevel::Trace.as_usize());
}

#[test]
fn level_from_str() {
    refute_from_str::<Level>("off");
    assert_from_str(Level::Critical, "critical");
    assert_from_str(Level::Critical, "crit");
    assert_from_str(Level::Error, "error");
    assert_from_str(Level::Error, "erro");
    assert_from_str(Level::Warning, "warn");
    assert_from_str(Level::Info, "info");
    assert_from_str(Level::Debug, "debug");
    assert_from_str(Level::Debug, "debg");
    assert_from_str(Level::Trace, "trace");
    assert_from_str(Level::Trace, "trce");

    assert_from_str(Level::Info, "Info");
    assert_from_str(Level::Info, "INFO");
    assert_from_str(Level::Info, "iNfO");

    refute_from_str::<Level>("");
    assert_from_str(Level::Info, "i");
    assert_from_str(Level::Info, "in");
    assert_from_str(Level::Info, "inf");
    refute_from_str::<Level>("infor");

    refute_from_str::<Level>("?");
    refute_from_str::<Level>("info ");
    refute_from_str::<Level>(" info");
    refute_from_str::<Level>("desinfo");
}

#[test]
fn filter_level_from_str() {
    assert_from_str(FilterLevel::Off, "off");
    assert_from_str(FilterLevel::Critical, "critical");
    assert_from_str(FilterLevel::Critical, "crit");
    assert_from_str(FilterLevel::Error, "error");
    assert_from_str(FilterLevel::Error, "erro");
    assert_from_str(FilterLevel::Warning, "warn");
    assert_from_str(FilterLevel::Info, "info");
    assert_from_str(FilterLevel::Debug, "debug");
    assert_from_str(FilterLevel::Debug, "debg");
    assert_from_str(FilterLevel::Trace, "trace");
    assert_from_str(FilterLevel::Trace, "trce");

    assert_from_str(FilterLevel::Info, "Info");
    assert_from_str(FilterLevel::Info, "INFO");
    assert_from_str(FilterLevel::Info, "iNfO");

    refute_from_str::<FilterLevel>("");
    assert_from_str(FilterLevel::Info, "i");
    assert_from_str(FilterLevel::Info, "in");
    assert_from_str(FilterLevel::Info, "inf");
    refute_from_str::<FilterLevel>("infor");

    refute_from_str::<FilterLevel>("?");
    refute_from_str::<FilterLevel>("info ");
    refute_from_str::<FilterLevel>(" info");
    refute_from_str::<FilterLevel>("desinfo");
}

#[cfg(test)]
fn assert_from_str<T>(expected: T, level_str: &str)
    where
        T: FromStr + fmt::Debug + PartialEq,
        T::Err: fmt::Debug {
    let result = T::from_str(level_str);

    let actual = result.unwrap_or_else(|e| {
        panic!("Failed to parse filter level '{}': {:?}", level_str, e)
    });
    assert_eq!(expected, actual, "Invalid filter level parsed from '{}'", level_str);
}

#[cfg(test)]
fn refute_from_str<T>(level_str: &str)
    where
        T: FromStr + fmt::Debug {
    let result = T::from_str(level_str);

    if let Ok(level) = result {
        panic!("Parsing filter level '{}' succeeded: {:?}", level_str, level)
    }
}

#[cfg(feature = "std")]
#[test]
fn level_to_string_and_from_str_are_compatible() {
    assert_to_string_from_str(Level::Critical);
    assert_to_string_from_str(Level::Error);
    assert_to_string_from_str(Level::Warning);
    assert_to_string_from_str(Level::Info);
    assert_to_string_from_str(Level::Debug);
    assert_to_string_from_str(Level::Trace);
}

#[cfg(feature = "std")]
#[test]
fn filter_level_to_string_and_from_str_are_compatible() {
    assert_to_string_from_str(FilterLevel::Off);
    assert_to_string_from_str(FilterLevel::Critical);
    assert_to_string_from_str(FilterLevel::Error);
    assert_to_string_from_str(FilterLevel::Warning);
    assert_to_string_from_str(FilterLevel::Info);
    assert_to_string_from_str(FilterLevel::Debug);
    assert_to_string_from_str(FilterLevel::Trace);
}

#[cfg(all(test, feature = "std"))]
fn assert_to_string_from_str<T>(expected: T)
    where
        T: std::string::ToString + FromStr + PartialEq + fmt::Debug,
        <T as FromStr>::Err: fmt::Debug {
    let string = expected.to_string();

    let actual = T::from_str(&string)
        .expect(&format!("Failed to parse string representation of {:?}", expected));

    assert_eq!(expected, actual, "Invalid value parsed from string representation of {:?}", actual);
}

#[test]
fn filter_level_accepts_tests() {
    assert_eq!(true, FilterLevel::Warning.accepts(Level::Error));
    assert_eq!(true, FilterLevel::Warning.accepts(Level::Warning));
    assert_eq!(false, FilterLevel::Warning.accepts(Level::Info));
    assert_eq!(false, FilterLevel::Off.accepts(Level::Critical));
}
// }}}

// {{{ Record
#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct RecordLocation {
    /// File
    pub file: &'static str,
    /// Line
    pub line: u32,
    /// Column (currently not implemented)
    pub column: u32,
    /// Function (currently not implemented)
    pub function: &'static str,
    /// Module
    pub module: &'static str,
}
/// Information that can be static in the given record thus allowing to optimize
/// record creation to be done mostly at compile-time.
///
/// This should be constructed via the `record_static!` macro.
pub struct RecordStatic<'a> {
    /// Code location
    #[doc(hidden)]
    pub location: &'a RecordLocation,
    /// Tag
    #[doc(hidden)]
    pub tag: &'a str,
    /// Logging level
    #[doc(hidden)]
    pub level: Level,
}

/// One logging record
///
/// Corresponds to one logging statement like `info!(...)` and carries all it's
/// data: eg. message, immediate key-value pairs and key-value pairs of `Logger`
/// used to execute it.
///
/// Record is passed to a `Logger`, which delivers it to it's own `Drain`,
/// where actual logging processing is implemented.
pub struct Record<'a> {
    rstatic: &'a RecordStatic<'a>,
    msg: &'a fmt::Arguments<'a>,
    kv: BorrowedKV<'a>,
}

impl<'a> Record<'a> {
    /// Create a new `Record`
    ///
    /// Most of the time, it is slightly more performant to construct a `Record`
    /// via the `record!` macro because it enforces that the *entire*
    /// `RecordStatic` is built at compile-time.
    ///
    /// Use this if runtime record creation is a requirement, as is the case with
    /// [slog-async](https://docs.rs/slog-async/latest/slog_async/struct.Async.html),
    /// for example.
    #[inline]
    pub fn new(
        s: &'a RecordStatic<'a>,
        msg: &'a fmt::Arguments<'a>,
        kv: BorrowedKV<'a>,
    ) -> Self {
        Record {
            rstatic: s,
            msg: msg,
            kv: kv,
        }
    }

    /// Get a log record message
    pub fn msg(&self) -> &fmt::Arguments {
        self.msg
    }

    /// Get record logging level
    pub fn level(&self) -> Level {
        self.rstatic.level
    }

    /// Get line number
    pub fn line(&self) -> u32 {
        self.rstatic.location.line
    }

    /// Get line number
    pub fn location(&self) -> &RecordLocation {
        self.rstatic.location
    }

    /// Get error column
    pub fn column(&self) -> u32 {
        self.rstatic.location.column
    }

    /// Get file path
    pub fn file(&self) -> &'static str {
        self.rstatic.location.file
    }

    /// Get tag
    ///
    /// Tag is information that can be attached to `Record` that is not meant
    /// to be part of the normal key-value pairs, but only as an ad-hoc control
    /// flag for quick lookup in the `Drain`s. As such should be used carefully
    /// and mostly in application code (as opposed to libraries) - where tag
    /// meaning across the system can be coordinated. When used in libraries,
    /// make sure to prefix it with something reasonably distinct, like create
    /// name.
    pub fn tag(&self) -> &str {
        self.rstatic.tag
    }

    /// Get module
    pub fn module(&self) -> &'static str {
        self.rstatic.location.module
    }

    /// Get function (placeholder)
    ///
    /// There's currently no way to obtain that information
    /// in Rust at compile time, so it is not implemented.
    ///
    /// It will be implemented at first opportunity, and
    /// it will not be considered a breaking change.
    pub fn function(&self) -> &'static str {
        self.rstatic.location.function
    }

    /// Get key-value pairs
    pub fn kv(&self) -> BorrowedKV {
        BorrowedKV(self.kv.0)
    }
}
// }}}

// {{{ Serializer

#[cfg(macro_workaround)]
macro_rules! impl_default_as_fmt{
    (#[$m:meta] $($t:tt)+) => {
        #[$m]
        impl_default_as_fmt!($($t)*);
    };
    ($t:ty => $f:ident) => {
        #[allow(missing_docs)]
        fn $f(&mut self, key : Key, val : $t)
            -> Result {
                self.emit_arguments(key, &format_args!("{}", val))
            }
    };
}

#[cfg(not(macro_workaround))]
macro_rules! impl_default_as_fmt{
    ($(#[$m:meta])* $t:ty => $f:ident) => {
        $(#[$m])*
        fn $f(&mut self, key : Key, val : $t)
            -> Result {
                self.emit_arguments(key, &format_args!("{}", val))
            }
    };
}

/// This is a workaround to be able to pass &mut Serializer, from
/// `Serializer::emit_serde` default implementation. `&Self` can't be casted to
/// `&Serializer` (without : Sized, which break object safety), but it can be
/// used as <T: Serializer>.
#[cfg(feature = "nested-values")]
struct SerializerForward<'a, T: 'a + ?Sized>(&'a mut T);

#[cfg(feature = "nested-values")]
impl<'a, T: Serializer + 'a + ?Sized> Serializer for SerializerForward<'a, T> {
    fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result {
        self.0.emit_arguments(key, val)
    }

    #[cfg(feature = "nested-values")]
    fn emit_serde(&mut self, _key: Key, _value: &SerdeValue) -> Result {
        panic!();
    }
}

/// Serializer
///
/// Drains using `Format` will internally use
/// types implementing this trait.
pub trait Serializer {
    impl_default_as_fmt! {
        /// Emit `usize`
        usize => emit_usize
    }
    impl_default_as_fmt! {
        /// Emit `isize`
        isize => emit_isize
    }
    impl_default_as_fmt! {
        /// Emit `bool`
        bool => emit_bool
    }
    impl_default_as_fmt! {
        /// Emit `char`
        char => emit_char
    }
    impl_default_as_fmt! {
        /// Emit `u8`
        u8 => emit_u8
    }
    impl_default_as_fmt! {
        /// Emit `i8`
        i8 => emit_i8
    }
    impl_default_as_fmt! {
        /// Emit `u16`
        u16 => emit_u16
    }
    impl_default_as_fmt! {
        /// Emit `i16`
        i16 => emit_i16
    }
    impl_default_as_fmt! {
        /// Emit `u32`
        u32 => emit_u32
    }
    impl_default_as_fmt! {
        /// Emit `i32`
        i32 => emit_i32
    }
    impl_default_as_fmt! {
        /// Emit `f32`
        f32 => emit_f32
    }
    impl_default_as_fmt! {
        /// Emit `u64`
        u64 => emit_u64
    }
    impl_default_as_fmt! {
        /// Emit `i64`
        i64 => emit_i64
    }
    impl_default_as_fmt! {
        /// Emit `f64`
        f64 => emit_f64
    }
    impl_default_as_fmt! {
        /// Emit `u128`
        #[cfg(integer128)]
        u128 => emit_u128
    }
    impl_default_as_fmt! {
        /// Emit `i128`
        #[cfg(integer128)]
        i128 => emit_i128
    }
    impl_default_as_fmt! {
        /// Emit `&str`
        &str => emit_str
    }

    /// Emit `()`
    fn emit_unit(&mut self, key: Key) -> Result {
        self.emit_arguments(key, &format_args!("()"))
    }

    /// Emit `None`
    fn emit_none(&mut self, key: Key) -> Result {
        self.emit_arguments(key, &format_args!(""))
    }

    /// Emit `fmt::Arguments`
    ///
    /// This is the only method that has to implemented, but for performance and
    /// to retain type information most serious `Serializer`s will want to
    /// implement all other methods as well.
    fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result;

    /// Emit a value implementing
    /// [`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html)
    ///
    /// This is especially useful for composite values, eg. structs as Json values, or sequences.
    ///
    /// To prevent pulling-in `serde` dependency, this is an extension behind a
    /// `serde` feature flag.
    ///
    /// The value needs to implement `SerdeValue`.
    #[cfg(feature = "nested-values")]
    fn emit_serde(&mut self, key: Key, value: &SerdeValue) -> Result {
        value.serialize_fallback(key, &mut SerializerForward(self))
    }
}

/// Serializer to closure adapter.
///
/// Formats all arguments as `fmt::Arguments` and passes them to a given closure.
struct AsFmtSerializer<F>(pub F)
where
    F: for<'a> FnMut(Key, fmt::Arguments<'a>) -> Result;

impl<F> Serializer for AsFmtSerializer<F>
where
    F: for<'a> FnMut(Key, fmt::Arguments<'a>) -> Result,
{
    fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result {
        (self.0)(key, *val)
    }
}
// }}}

// {{{ serde
/// A value that can be serialized via serde
///
/// This is useful for implementing nested values, like sequences or structures.
#[cfg(feature = "nested-values")]
pub trait SerdeValue: erased_serde::Serialize + Value {
    /// Serialize the value in a way that is compatible with `slog::Serializer`s
    /// that do not support serde.
    ///
    /// The implementation should *not* call `slog::Serialize::serialize`
    /// on itself, as it will lead to infinite recursion.
    ///
    /// Default implementation is provided, but it returns error, so use it
    /// only for internal types in systems and libraries where `serde` is always
    /// enabled.
    fn serialize_fallback(
        &self,
        _key: Key,
        _serializer: &mut Serializer,
    ) -> Result<()> {
        Err(Error::Other)
    }

    /// Convert to `erased_serialize::Serialize` of the underlying value,
    /// so `slog::Serializer`s can use it to serialize via `serde`.
    fn as_serde(&self) -> &erased_serde::Serialize;

    /// Convert to a boxed value that can be sent across threads
    ///
    /// This enables functionality like `slog-async` and similar.
    fn to_sendable(&self) -> Box<SerdeValue + Send + 'static>;
}

// }}}

// {{{ Value
/// Value that can be serialized
///
/// Types that implement this type implement custom serialization in the
/// structured part of the log macros. Without an implementation of `Value` for
/// your type you must emit using either the `?` "debug", `%` "display" or
/// [`SerdeValue`](trait.SerdeValue.html) (if you have the `nested-values`
/// feature enabled) formatters.
///
/// # Example
///
/// ```
/// use slog::{Key, Value, Record, Result, Serializer};
/// struct MyNewType(i64);
///
/// impl Value for MyNewType {
///     fn serialize(&self, _rec: &Record, key: Key, serializer: &mut Serializer) -> Result {
///         serializer.emit_i64(key, self.0)
///     }
/// }
/// ```
///
/// See also [`KV`](trait.KV.html) for formatting both the key and value.
pub trait Value {
    /// Serialize self into `Serializer`
    ///
    /// Structs implementing this trait should generally
    /// only call respective methods of `serializer`.
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result;
}

impl<'a, V> Value for &'a V
where
    V: Value + ?Sized,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        (*self).serialize(record, key, serializer)
    }
}

macro_rules! impl_value_for{
    ($t:ty, $f:ident) => {
        impl Value for $t {
            fn serialize(&self,
                         _record : &Record,
                         key : Key,
                         serializer : &mut Serializer
                         ) -> Result {
                serializer.$f(key, *self)
            }
        }
    };
}

impl_value_for!(usize, emit_usize);
impl_value_for!(isize, emit_isize);
impl_value_for!(bool, emit_bool);
impl_value_for!(char, emit_char);
impl_value_for!(u8, emit_u8);
impl_value_for!(i8, emit_i8);
impl_value_for!(u16, emit_u16);
impl_value_for!(i16, emit_i16);
impl_value_for!(u32, emit_u32);
impl_value_for!(i32, emit_i32);
impl_value_for!(f32, emit_f32);
impl_value_for!(u64, emit_u64);
impl_value_for!(i64, emit_i64);
impl_value_for!(f64, emit_f64);
#[cfg(integer128)]
impl_value_for!(u128, emit_u128);
#[cfg(integer128)]
impl_value_for!(i128, emit_i128);

impl Value for () {
    fn serialize(
        &self,
        _record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        serializer.emit_unit(key)
    }
}

impl Value for str {
    fn serialize(
        &self,
        _record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        serializer.emit_str(key, self)
    }
}

impl<'a> Value for fmt::Arguments<'a> {
    fn serialize(
        &self,
        _record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        serializer.emit_arguments(key, self)
    }
}

impl Value for String {
    fn serialize(
        &self,
        _record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        serializer.emit_str(key, self.as_str())
    }
}

impl<T: Value> Value for Option<T> {
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        match *self {
            Some(ref s) => s.serialize(record, key, serializer),
            None => serializer.emit_none(key),
        }
    }
}

impl<T> Value for Box<T>
where
    T: Value + ?Sized,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        (**self).serialize(record, key, serializer)
    }
}
impl<T> Value for Arc<T>
where
    T: Value + ?Sized,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        (**self).serialize(record, key, serializer)
    }
}

impl<T> Value for Rc<T>
where
    T: Value,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        (**self).serialize(record, key, serializer)
    }
}

impl<T> Value for core::num::Wrapping<T>
where
    T: Value,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        self.0.serialize(record, key, serializer)
    }
}

#[cfg(feature = "std")]
impl<'a> Value for std::path::Display<'a> {
    fn serialize(
        &self,
        _record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        serializer.emit_arguments(key, &format_args!("{}", *self))
    }
}

#[cfg(feature = "std")]
impl Value for std::net::SocketAddr {
    fn serialize(
        &self,
        _record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        serializer.emit_arguments(key, &format_args!("{}", self))
    }
}

/// Explicit lazy-closure `Value`
pub struct FnValue<V: Value, F>(pub F)
where
    F: for<'c, 'd> Fn(&'c Record<'d>) -> V;

impl<'a, V: 'a + Value, F> Value for FnValue<V, F>
where
    F: 'a + for<'c, 'd> Fn(&'c Record<'d>) -> V,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        (self.0)(record).serialize(record, key, serializer)
    }
}

#[deprecated(note = "Renamed to `PushFnValueSerializer`")]
/// Old name of `PushFnValueSerializer`
pub type PushFnSerializer<'a> = PushFnValueSerializer<'a>;

/// Handle passed to `PushFnValue` closure
///
/// It makes sure only one value is serialized, and will automatically emit
/// `()` if nothing else was serialized.
pub struct PushFnValueSerializer<'a> {
    record: &'a Record<'a>,
    key: Key,
    serializer: &'a mut Serializer,
    done: bool,
}

impl<'a> PushFnValueSerializer<'a> {
    #[deprecated(note = "Renamed to `emit`")]
    /// Emit a value
    pub fn serialize<'b, S: 'b + Value>(self, s: S) -> Result {
        self.emit(s)
    }

    /// Emit a value
    ///
    /// This consumes `self` to prevent serializing one value multiple times
    pub fn emit<'b, S: 'b + Value>(mut self, s: S) -> Result {
        self.done = true;
        s.serialize(self.record, self.key.clone(), self.serializer)
    }
}

impl<'a> Drop for PushFnValueSerializer<'a> {
    fn drop(&mut self) {
        if !self.done {
            // unfortunately this gives no change to return serialization errors
            let _ = self.serializer.emit_unit(self.key.clone());
        }
    }
}

/// Lazy `Value` that writes to Serializer
///
/// It's more ergonomic for closures used as lazy values to return type
/// implementing `Serialize`, but sometimes that forces an allocation (eg.
/// `String`s)
///
/// In some cases it might make sense for another closure form to be used - one
/// taking a serializer as an argument, which avoids lifetimes / allocation
/// issues.
///
/// Generally this method should be used if it avoids a big allocation of
/// `Serialize`-implementing type in performance-critical logging statement.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::{PushFnValue, Logger, Discard};
///
/// fn main() {
///     // Create a logger with a key-value printing
///     // `file:line` string value for every logging statement.
///     // `Discard` `Drain` used for brevity.
///     let root = Logger::root(Discard, o!(
///         "source_location" => PushFnValue(|record , s| {
///              s.serialize(
///                   format_args!(
///                        "{}:{}",
///                        record.file(),
///                        record.line(),
///                   )
///              )
///         })
///     ));
/// }
/// ```
pub struct PushFnValue<F>(pub F)
where
    F: 'static
        + for<'c, 'd> Fn(&'c Record<'d>, PushFnValueSerializer<'c>) -> Result;

impl<F> Value for PushFnValue<F>
where
    F: 'static
        + for<'c, 'd> Fn(&'c Record<'d>, PushFnValueSerializer<'c>) -> Result,
{
    fn serialize(
        &self,
        record: &Record,
        key: Key,
        serializer: &mut Serializer,
    ) -> Result {
        let ser = PushFnValueSerializer {
            record: record,
            key: key,
            serializer: serializer,
            done: false,
        };
        (self.0)(record, ser)
    }
}
// }}}

// {{{ KV
/// Key-value pair(s) for log events
///
/// Zero, one or more key value pairs chained together
///
/// Any logging data must implement this trait for slog to be able to use it,
/// although slog comes with default implementations within its macros (the
/// `=>` and `kv!` portions of the log macros).
///
/// If you don't use this trait, you must emit your structured data by
/// specifying both key and value in each log event:
///
/// ```ignore
/// info!(logger, "my event"; "type_key" => %my_val);
/// ```
///
/// If you implement this trait, that can become:
///
/// ```ignore
/// info!(logger, "my event"; my_val);
/// ```
///
/// Types implementing this trait can emit multiple key-value pairs, and can
/// customize their structured representation. The order of emitting them
/// should be consistent with the way key-value pair hierarchy is traversed:
/// from data most specific to the logging context to the most general one. Or
/// in other words: from newest to oldest.
///
/// Implementers are are responsible for calling the `emit_*` methods on the
/// `Serializer` passed in, the `Record` can be used to make display decisions
/// based on context, but for most plain-value structs you will just call
/// `emit_*`.
///
/// # Example
///
/// ```
/// use slog::{KV, Record, Result, Serializer};
///
/// struct MyNewType(i64);
///
/// impl KV for MyNewType {
///    fn serialize(&self, _rec: &Record, serializer: &mut Serializer) -> Result {
///        serializer.emit_i64("my_new_type", self.0)
///    }
/// }
/// ```
///
/// See also [`Value`](trait.Value.html), which allows you to customize just
/// the right hand side of the `=>` structure macro, and (if you have the
/// `nested-values` feature enabled) [`SerdeValue`](trait.SerdeValue.html)
/// which allows emitting anything serde can emit.
pub trait KV {
    /// Serialize self into `Serializer`
    ///
    /// `KV` should call respective `Serializer` methods
    /// for each key-value pair it contains.
    fn serialize(&self, record: &Record, serializer: &mut Serializer)
        -> Result;
}

impl<'a, T> KV for &'a T
where
    T: KV,
{
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        (**self).serialize(record, serializer)
    }
}

#[cfg(feature = "nothreads")]
/// Thread-local safety bound for `KV`
///
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV {}

#[cfg(feature = "nothreads")]
impl<T> SendSyncRefUnwindSafeKV for T where T: KV + ?Sized {}

#[cfg(all(not(feature = "nothreads"), feature = "std"))]
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV + Send + Sync + RefUnwindSafe {}

#[cfg(all(not(feature = "nothreads"), feature = "std"))]
impl<T> SendSyncRefUnwindSafeKV for T where T: KV + Send + Sync + RefUnwindSafe + ?Sized {}

#[cfg(all(not(feature = "nothreads"), not(feature = "std")))]
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV + Send + Sync {}

#[cfg(all(not(feature = "nothreads"), not(feature = "std")))]
impl<T> SendSyncRefUnwindSafeKV for T where T: KV + Send + Sync + ?Sized {}

/// Single pair `Key` and `Value`
pub struct SingleKV<V>(pub Key, pub V)
where
    V: Value;

#[cfg(feature = "dynamic-keys")]
impl<V: Value> From<(String, V)> for SingleKV<V> {
    fn from(x: (String, V)) -> SingleKV<V> {
        SingleKV(Key::from(x.0), x.1)
    }
}
#[cfg(feature = "dynamic-keys")]
impl<V: Value> From<(&'static str, V)> for SingleKV<V> {
    fn from(x: (&'static str, V)) -> SingleKV<V> {
        SingleKV(Key::from(x.0), x.1)
    }
}
#[cfg(not(feature = "dynamic-keys"))]
impl<V: Value> From<(&'static str, V)> for SingleKV<V> {
    fn from(x: (&'static str, V)) -> SingleKV<V> {
        SingleKV(x.0, x.1)
    }
}

impl<V> KV for SingleKV<V>
where
    V: Value,
{
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        self.1.serialize(record, self.0.clone(), serializer)
    }
}

impl KV for () {
    fn serialize(
        &self,
        _record: &Record,
        _serializer: &mut Serializer,
    ) -> Result {
        Ok(())
    }
}

impl<T: KV, R: KV> KV for (T, R) {
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        try!(self.0.serialize(record, serializer));
        self.1.serialize(record, serializer)
    }
}

impl<T> KV for Box<T>
where
    T: KV + ?Sized,
{
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        (**self).serialize(record, serializer)
    }
}

impl<T> KV for Arc<T>
where
    T: KV + ?Sized,
{
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        (**self).serialize(record, serializer)
    }
}

impl<T> KV for OwnedKV<T>
where
    T: SendSyncRefUnwindSafeKV + ?Sized,
{
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        self.0.serialize(record, serializer)
    }
}

impl<'a> KV for BorrowedKV<'a> {
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        self.0.serialize(record, serializer)
    }
}
// }}}

// {{{ OwnedKV
/// Owned KV
///
/// "Owned" means that the contained data (key-value pairs) can belong
/// to a `Logger` and thus must be thread-safe (`'static`, `Send`, `Sync`)
///
/// Zero, one or more owned key-value pairs.
///
/// Can be constructed with [`o!` macro](macro.o.html).
pub struct OwnedKV<T>(
    #[doc(hidden)]
    /// The exact details of that it are not considered public
    /// and stable API. `slog_o` or `o` macro should be used
    /// instead to create `OwnedKV` instances.
    pub T,
)
where
    T: SendSyncRefUnwindSafeKV + ?Sized;
// }}}

// {{{ BorrowedKV
/// Borrowed `KV`
///
/// "Borrowed" means that the data is only a temporary
/// referenced (`&T`) and can't be stored directly.
///
/// Zero, one or more borrowed key-value pairs.
///
/// Can be constructed with [`b!` macro](macro.b.html).
pub struct BorrowedKV<'a>(
    /// The exact details of it function are not
    /// considered public and stable API. `log` and other
    /// macros should be used instead to create
    /// `BorrowedKV` instances.
    #[doc(hidden)]
    pub &'a KV,
);

// }}}

// {{{ OwnedKVList
struct OwnedKVListNode<T>
where
    T: SendSyncRefUnwindSafeKV + 'static,
{
    next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
    kv: T,
}

struct MultiListNode {
    next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
    node: Arc<SendSyncRefUnwindSafeKV + 'static>,
}

/// Chain of `SyncMultiSerialize`-s of a `Logger` and its ancestors
#[derive(Clone)]
pub struct OwnedKVList {
    node: Arc<SendSyncRefUnwindSafeKV + 'static>,
}

impl<T> KV for OwnedKVListNode<T>
where
    T: SendSyncRefUnwindSafeKV + 'static,
{
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        try!(self.kv.serialize(record, serializer));
        try!(self.next_node.serialize(record, serializer));

        Ok(())
    }
}

impl KV for MultiListNode {
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        try!(self.next_node.serialize(record, serializer));
        try!(self.node.serialize(record, serializer));

        Ok(())
    }
}

impl KV for OwnedKVList {
    fn serialize(
        &self,
        record: &Record,
        serializer: &mut Serializer,
    ) -> Result {
        try!(self.node.serialize(record, serializer));

        Ok(())
    }
}

impl fmt::Debug for OwnedKVList {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "("));
        let mut i = 0;

        {
            let mut as_str_ser = AsFmtSerializer(|key, _val| {
                if i != 0 {
                    try!(write!(f, ", "));
                }

                try!(write!(f, "{}", key));
                i += 1;
                Ok(())
            });
            let record_static = record_static!(Level::Trace, "");

            try!(
                self.node
                    .serialize(
                        &Record::new(
                            &record_static,
                            &format_args!(""),
                            BorrowedKV(&STATIC_TERMINATOR_UNIT)
                        ),
                        &mut as_str_ser
                    )
                    .map_err(|_| fmt::Error)
            );
        }

        try!(write!(f, ")"));
        Ok(())
    }
}

impl OwnedKVList {
    /// New `OwnedKVList` node without a parent (root)
    fn root<T>(values: OwnedKV<T>) -> Self
    where
        T: SendSyncRefUnwindSafeKV + 'static,
    {
        OwnedKVList {
            node: Arc::new(OwnedKVListNode {
                next_node: Arc::new(()),
                kv: values.0,
            }),
        }
    }

    /// New `OwnedKVList` node with an existing parent
    fn new<T>(
        values: OwnedKV<T>,
        next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
    ) -> Self
    where
        T: SendSyncRefUnwindSafeKV + 'static,
    {
        OwnedKVList {
            node: Arc::new(OwnedKVListNode {
                next_node: next_node,
                kv: values.0,
            }),
        }
    }
}

impl<T> convert::From<OwnedKV<T>> for OwnedKVList
where
    T: SendSyncRefUnwindSafeKV + 'static,
{
    fn from(from: OwnedKV<T>) -> Self {
        OwnedKVList::root(from)
    }
}
// }}}

// {{{ Error
#[derive(Debug)]
#[cfg(feature = "std")]
/// Serialization Error
pub enum Error {
    /// `io::Error` (not available in ![no_std] mode)
    Io(std::io::Error),
    /// `fmt::Error`
    Fmt(std::fmt::Error),
    /// Other error
    Other,
}

#[derive(Debug)]
#[cfg(not(feature = "std"))]
/// Serialization Error
pub enum Error {
    /// `fmt::Error`
    Fmt(core::fmt::Error),
    /// Other error
    Other,
}

/// Serialization `Result`
pub type Result<T = ()> = result::Result<T, Error>;

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<core::fmt::Error> for Error {
    fn from(_: core::fmt::Error) -> Error {
        Error::Other
    }
}

#[cfg(feature = "std")]
impl From<Error> for std::io::Error {
    fn from(e: Error) -> std::io::Error {
        match e {
            Error::Io(e) => e,
            Error::Fmt(_) => std::io::Error::new(
                std::io::ErrorKind::Other,
                "formatting error",
            ),
            Error::Other => {
                std::io::Error::new(std::io::ErrorKind::Other, "other error")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Io(ref e) => e.description(),
            Error::Fmt(_) => "formatting error",
            Error::Other => "serialization error",
        }
    }

    fn cause(&self) -> Option<&std::error::Error> {
        match *self {
            Error::Io(ref e) => Some(e),
            Error::Fmt(ref e) => Some(e),
            Error::Other => None,
        }
    }
}

#[cfg(feature = "std")]
impl core::fmt::Display for Error {
    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> std::fmt::Result {
        match *self {
            Error::Io(ref e) => e.fmt(fmt),
            Error::Fmt(ref e) => e.fmt(fmt),
            Error::Other => fmt.write_str("Other serialization error"),
        }
    }
}
// }}}

// {{{ Misc
/// This type is here just to abstract away lack of `!` type support in stable
/// rust during time of the release. It will be switched to `!` at some point
/// and `Never` should not be considered "stable" API.
#[doc(hidden)]
pub type Never = private::NeverStruct;

mod private {
    #[doc(hidden)]
    #[derive(Debug)]
    pub struct NeverStruct(());
}

/// This is not part of "stable" API
#[doc(hidden)]
pub static STATIC_TERMINATOR_UNIT: () = ();

#[allow(unknown_lints)]
#[allow(inline_always)]
#[inline(always)]
#[doc(hidden)]
/// Not an API
///
/// Generally it's a bad idea to depend on static logging level
/// in your code. Use closures to perform operations lazily
/// only when logging actually takes place.
pub fn __slog_static_max_level() -> FilterLevel {
    if !cfg!(debug_assertions) {
        if cfg!(feature = "release_max_level_off") {
            return FilterLevel::Off;
        } else if cfg!(feature = "release_max_level_error") {
            return FilterLevel::Error;
        } else if cfg!(feature = "release_max_level_warn") {
            return FilterLevel::Warning;
        } else if cfg!(feature = "release_max_level_info") {
            return FilterLevel::Info;
        } else if cfg!(feature = "release_max_level_debug") {
            return FilterLevel::Debug;
        } else if cfg!(feature = "release_max_level_trace") {
            return FilterLevel::Trace;
        }
    }
    if cfg!(feature = "max_level_off") {
        FilterLevel::Off
    } else if cfg!(feature = "max_level_error") {
        FilterLevel::Error
    } else if cfg!(feature = "max_level_warn") {
        FilterLevel::Warning
    } else if cfg!(feature = "max_level_info") {
        FilterLevel::Info
    } else if cfg!(feature = "max_level_debug") {
        FilterLevel::Debug
    } else if cfg!(feature = "max_level_trace") {
        FilterLevel::Trace
    } else {
        if !cfg!(debug_assertions) {
            FilterLevel::Info
        } else {
            FilterLevel::Debug
        }
    }
}

// }}}

// {{{ Slog v1 Compat
#[deprecated(note = "Renamed to `Value`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type Serialize = Value;

#[deprecated(note = "Renamed to `PushFnValue`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type PushLazy<T> = PushFnValue<T>;

#[deprecated(note = "Renamed to `PushFnValueSerializer`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type ValueSerializer<'a> = PushFnValueSerializer<'a>;

#[deprecated(note = "Renamed to `OwnedKVList`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type OwnedKeyValueList = OwnedKVList;

#[deprecated(note = "Content of ser module moved to main namespace")]
/// Compatibility name to ease upgrading from `slog v1`
pub mod ser {
    #[allow(deprecated)]
    pub use super::{OwnedKeyValueList, PushLazy, Serialize, Serializer,
                    ValueSerializer};
}
// }}}

// {{{ Test
#[cfg(test)]
mod tests;

// }}}

// vim: foldmethod=marker foldmarker={{{,}}}