emit 1.17.2

Developer-first diagnostics for Rust applications.
Documentation
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
/*!
The [`Span`] type.
*/

/*
Parts of this file are adapted from other libraries:

uuid:
https://github.com/uuid-rs/uuid/blob/main/src/parser.rs
Licensed under Apache 2.0
*/

use emit_core::{
    and::And,
    clock::Clock,
    ctxt::Ctxt,
    empty::Empty,
    event::{Event, ToEvent},
    extent::{Extent, ToExtent},
    filter::Filter,
    path::Path,
    props::{ErasedProps, Props},
    rng::Rng,
    str::{Str, ToStr},
    template::{self, Template},
    timestamp::Timestamp,
    value::{FromValue, ToValue, Value},
    well_known::{
        KEY_EVT_KIND, KEY_SPAN_ID, KEY_SPAN_NAME, KEY_SPAN_PARENT, KEY_TRACE_ID, SPAN_KIND_CLIENT,
        SPAN_KIND_CONSUMER, SPAN_KIND_INTERNAL, SPAN_KIND_PRODUCER, SPAN_KIND_SERVER,
    },
};

use crate::{kind::Kind, Frame, Timer};
use core::{
    fmt, mem,
    num::{NonZeroU128, NonZeroU64},
    ops::ControlFlow,
    str::{self, FromStr},
};

pub use self::completion::Completion;

/**
A [W3C Trace Id](https://www.w3.org/TR/trace-context/#trace-id).
*/
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TraceId(NonZeroU128);

impl fmt::Debug for TraceId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(str::from_utf8(&self.to_hex()).unwrap(), f)
    }
}

impl fmt::Display for TraceId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(str::from_utf8(&self.to_hex()).unwrap())
    }
}

impl FromStr for TraceId {
    type Err = ParseIdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_hex_slice(s.as_bytes())
    }
}

impl ToValue for TraceId {
    fn to_value(&self) -> Value<'_> {
        Value::capture_display(self)
    }
}

impl<'v> FromValue<'v> for TraceId {
    fn from_value(value: Value<'v>) -> Option<Self> {
        value
            .downcast_ref::<TraceId>()
            .copied()
            .or_else(|| u128::from_value(value.by_ref()).and_then(TraceId::from_u128))
            .or_else(|| TraceId::try_from_hex(value).ok())
    }
}

#[cfg(feature = "sval")]
impl sval::Value for TraceId {
    fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> sval::Result {
        sval::stream_display(stream, self)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for TraceId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl TraceId {
    /**
    Create a random trace id.

    This method will return `None` if the given [`Rng`] fails to produce a random value, or if it produces the value `0`.
    */
    pub fn random<R: Rng>(rng: R) -> Option<Self> {
        Some(TraceId::new(NonZeroU128::new(rng.gen_u128()?)?))
    }

    /**
    Create a trace id from a non-zero integer.
    */
    pub const fn new(v: NonZeroU128) -> Self {
        TraceId(v)
    }

    /**
    Try create a trace id from an integer.

    This method will return `None` if `v` is `0`.
    */
    pub fn from_u128(v: u128) -> Option<Self> {
        Some(TraceId(NonZeroU128::new(v)?))
    }

    /**
    Get the value of the trace id as an integer.
    */
    pub const fn to_u128(&self) -> u128 {
        self.0.get()
    }

    /**
    Get a trace id from a 16 byte big-endian array.
    */
    pub fn from_bytes(v: [u8; 16]) -> Option<Self> {
        Self::from_u128(u128::from_be_bytes(v))
    }

    /**
    Convert the trace id into a 16 byte big-endian array.
    */
    pub fn to_bytes(&self) -> [u8; 16] {
        self.0.get().to_be_bytes()
    }

    /**
    Convert the trace id into a 32 byte ASCII-compatible hex string, like `4bf92f3577b34da6a3ce929d0e0e4736`.
    */
    pub fn to_hex(&self) -> [u8; 32] {
        let mut dst = [0; 32];
        let src: [u8; 16] = self.0.get().to_be_bytes();

        for i in 0..src.len() {
            let b = src[i];

            dst[i * 2] = HEX_ENCODE_TABLE[(b >> 4) as usize];
            dst[i * 2 + 1] = HEX_ENCODE_TABLE[(b & 0x0f) as usize];
        }

        dst
    }

    /**
    Try parse a slice of ASCII hex bytes into a trace id.

    If `hex` is not a 32 byte array of valid hex characters (`[a-fA-F0-9]`) then this method will fail.
    */
    pub fn try_from_hex_slice(hex: &[u8]) -> Result<Self, ParseIdError> {
        let hex: &[u8; 32] = hex.try_into().map_err(|_| ParseIdError {})?;

        let mut dst = [0; 16];

        let mut i = 0;
        while i < 16 {
            // Convert a two-char hex value (like `A8`)
            // into a byte (like `10101000`)
            let h1 = HEX_DECODE_TABLE[hex[i * 2] as usize];
            let h2 = HEX_DECODE_TABLE[hex[i * 2 + 1] as usize];

            // We use `0xff` as a sentinel value to indicate
            // an invalid hex character sequence (like the letter `G`)
            if h1 | h2 == 0xff {
                return Err(ParseIdError {});
            }

            // The upper nibble needs to be shifted into position
            // to produce the final byte value
            dst[i] = SHL4_TABLE[h1 as usize] | h2;
            i += 1;
        }

        Ok(TraceId::new(
            NonZeroU128::new(u128::from_be_bytes(dst)).ok_or_else(|| ParseIdError {})?,
        ))
    }

    /**
    Try parse ASCII hex characters into a trace id.

    If `hex` is not exactly 32 valid hex characters (`[a-fA-F0-9]`) then this method will fail.
    */
    pub fn try_from_hex(hex: impl fmt::Display) -> Result<Self, ParseIdError> {
        let mut buf = Buffer::<32>::new();

        Self::try_from_hex_slice(buf.buffer(hex)?)
    }
}

/**
A [W3C Span Id](https://www.w3.org/TR/trace-context/#parent-id).
*/
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct SpanId(NonZeroU64);

impl fmt::Debug for SpanId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(str::from_utf8(&self.to_hex()).unwrap(), f)
    }
}

impl fmt::Display for SpanId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(str::from_utf8(&self.to_hex()).unwrap())
    }
}

impl FromStr for SpanId {
    type Err = ParseIdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_hex_slice(s.as_bytes())
    }
}

impl ToValue for SpanId {
    fn to_value(&self) -> Value<'_> {
        Value::capture_display(self)
    }
}

impl<'v> FromValue<'v> for SpanId {
    fn from_value(value: Value<'v>) -> Option<Self> {
        value
            .downcast_ref::<SpanId>()
            .copied()
            .or_else(|| u64::from_value(value.by_ref()).and_then(SpanId::from_u64))
            .or_else(|| SpanId::try_from_hex(value).ok())
    }
}

#[cfg(feature = "sval")]
impl sval::Value for SpanId {
    fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> sval::Result {
        sval::stream_display(stream, self)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SpanId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl SpanId {
    /**
    Create a new random span id.

    This method will return `None` if the given [`Rng`] fails to produce a random value, or if it produces the value `0`.
    */
    pub fn random<R: Rng>(rng: R) -> Option<Self> {
        Some(SpanId::new(NonZeroU64::new(rng.gen_u64()?)?))
    }

    /**
    Create a span id from a non-zero integer.
    */
    pub const fn new(v: NonZeroU64) -> Self {
        SpanId(v)
    }

    /**
    Create a span id from an integer.

    This method will return `None` if `v` is `0`.
    */
    pub fn from_u64(v: u64) -> Option<Self> {
        Some(SpanId(NonZeroU64::new(v)?))
    }

    /**
    Get the value of the span id as an integer.
    */
    pub const fn to_u64(&self) -> u64 {
        self.0.get()
    }

    /**
    Get a span id from an 8 byte big-endian array.
    */
    pub fn from_bytes(v: [u8; 8]) -> Option<Self> {
        Self::from_u64(u64::from_be_bytes(v))
    }

    /**
    Convert the span id into an 8 byte big-endian array.
    */
    pub fn to_bytes(&self) -> [u8; 8] {
        self.0.get().to_be_bytes()
    }

    /**
    Convert the span id into a 16 byte ASCII-compatible hex string, like `00f067aa0ba902b7`.
    */
    pub fn to_hex(&self) -> [u8; 16] {
        let mut dst = [0; 16];
        let src: [u8; 8] = self.0.get().to_be_bytes();

        for i in 0..src.len() {
            let b = src[i];

            dst[i * 2] = HEX_ENCODE_TABLE[(b >> 4) as usize];
            dst[i * 2 + 1] = HEX_ENCODE_TABLE[(b & 0x0f) as usize];
        }

        dst
    }

    /**
    Try parse a slice of ASCII hex bytes into a span id.

    If `hex` is not a 16 byte array of valid hex characters (`[a-fA-F0-9]`) then this method will fail.
    */
    pub fn try_from_hex_slice(hex: &[u8]) -> Result<Self, ParseIdError> {
        let hex: &[u8; 16] = hex.try_into().map_err(|_| ParseIdError {})?;

        let mut dst = [0; 8];

        let mut i = 0;
        while i < 8 {
            // Convert a two-char hex value (like `A8`)
            // into a byte (like `10101000`)
            let h1 = HEX_DECODE_TABLE[hex[i * 2] as usize];
            let h2 = HEX_DECODE_TABLE[hex[i * 2 + 1] as usize];

            // We use `0xff` as a sentinel value to indicate
            // an invalid hex character sequence (like the letter `G`)
            if h1 | h2 == 0xff {
                return Err(ParseIdError {});
            }

            // The upper nibble needs to be shifted into position
            // to produce the final byte value
            dst[i] = SHL4_TABLE[h1 as usize] | h2;
            i += 1;
        }

        Ok(SpanId::new(
            NonZeroU64::new(u64::from_be_bytes(dst)).ok_or_else(|| ParseIdError {})?,
        ))
    }

    /**
    Try parse ASCII hex characters into a span id.

    If `hex` is not exactly 16 valid hex characters (`[a-fA-F0-9]`) then this method will fail.
    */
    pub fn try_from_hex(hex: impl fmt::Display) -> Result<Self, ParseIdError> {
        let mut buf = Buffer::<16>::new();

        Self::try_from_hex_slice(buf.buffer(hex)?)
    }
}

/*
Original implementation: https://github.com/uuid-rs/uuid/blob/main/src/parser.rs

Licensed under Apache 2.0
*/

const HEX_ENCODE_TABLE: [u8; 16] = [
    b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f',
];

const HEX_DECODE_TABLE: &[u8; 256] = &{
    let mut buf = [0; 256];
    let mut i: u8 = 0;

    loop {
        buf[i as usize] = match i {
            b'0'..=b'9' => i - b'0',
            b'a'..=b'f' => i - b'a' + 10,
            b'A'..=b'F' => i - b'A' + 10,
            _ => 0xff,
        };

        if i == 255 {
            break buf;
        }

        i += 1
    }
};

const SHL4_TABLE: &[u8; 256] = &{
    let mut buf = [0; 256];
    let mut i: u8 = 0;

    loop {
        buf[i as usize] = i.wrapping_shl(4);

        if i == 255 {
            break buf;
        }

        i += 1;
    }
};

/**
An error encountered attempting to parse a [`TraceId`] or [`SpanId`].
*/
#[derive(Debug)]
pub struct ParseIdError {}

impl fmt::Display for ParseIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "the input was not a valid id")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseIdError {}

struct Buffer<const N: usize> {
    value: [u8; N],
    idx: usize,
}

impl<const N: usize> Buffer<N> {
    fn new() -> Self {
        Buffer {
            value: [0; N],
            idx: 0,
        }
    }

    fn buffer(&mut self, value: impl fmt::Display) -> Result<&[u8], ParseIdError> {
        use fmt::Write as _;

        self.idx = 0;

        write!(self, "{}", value).map_err(|_| ParseIdError {})?;

        Ok(&self.value[..self.idx])
    }
}

impl<const N: usize> fmt::Write for Buffer<N> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let s = s.as_bytes();
        let next_idx = self.idx + s.len();

        if next_idx <= self.value.len() {
            self.value[self.idx..next_idx].copy_from_slice(s);
            self.idx = next_idx;

            Ok(())
        } else {
            Err(fmt::Error)
        }
    }
}

/**
A diagnostic event that represents a span in a distributed trace.

Spans are an extension of [`Event`]s that explicitly take the well-known properties that signal an event as being a span. See the [`mod@crate::span`] module for details.

A `SpanEvent` can be converted into an [`Event`] through its [`ToEvent`] implemenation, or passed directly to a [`crate::Emitter`] to emit it.
*/
pub struct Span<'a, P> {
    mdl: Path<'a>,
    name: Str<'a>,
    extent: Option<Extent>,
    tpl: Option<Template<'a>>,
    props: P,
}

impl<'a, P: Props> Span<'a, P> {
    /**
    Create a new span event from its parts.

    Each span consists of:

    - `mdl`: The module that executed the operation the span is tracking.
    - `name`: The name of the operation the span is tracking.
    - `extent`: The time the operation spent executing. The extent should be a span.
    - `props`: Additional [`Props`] to associate with the span. These may include the [`SpanCtxt`] with the trace and span ids for the span, or they may be part of the ambient context.
    */
    pub fn new(
        mdl: impl Into<Path<'a>>,
        name: impl Into<Str<'a>>,
        extent: impl ToExtent,
        props: P,
    ) -> Self {
        Span {
            mdl: mdl.into(),
            extent: extent.to_extent(),
            name: name.into(),
            tpl: None,
            props,
        }
    }

    /**
    Get the module that executed the operation.
    */
    pub fn mdl(&self) -> &Path<'a> {
        &self.mdl
    }

    /**
    Set the module of the span.
    */
    pub fn with_mdl(mut self, mdl: impl Into<Path<'a>>) -> Self {
        self.mdl = mdl.into();
        self
    }

    /**
    Get the name of the operation.
    */
    pub fn name(&self) -> &Str<'a> {
        &self.name
    }

    /**
    Set the name of the span.
    */
    pub fn with_name(mut self, name: impl Into<Str<'a>>) -> Self {
        self.name = name.into();
        self
    }

    /**
    Get the time the operation spent executing.
    */
    pub fn extent(&self) -> Option<&Extent> {
        self.extent.as_ref()
    }

    /**
    Set the extent of the span.
    */
    pub fn with_extent(mut self, extent: impl ToExtent) -> Self {
        self.extent = extent.to_extent();
        self
    }

    /**
    Get the extent of the metric as a point in time.

    If the span has an extent then this method will return `Some`, with the result of [`Extent::as_point`]. If the span doesn't have an extent then this method will return `None`.
    */
    pub fn ts(&self) -> Option<&Timestamp> {
        self.extent.as_ref().map(|extent| extent.as_point())
    }

    /**
    Get the start point of the extent of the span.

    If the span has an extent, and that extent covers a timespan then this method will return `Some`. Otherwise this method will return `None`.
    */
    pub fn ts_start(&self) -> Option<&Timestamp> {
        self.extent
            .as_ref()
            .and_then(|extent| extent.as_range())
            .map(|span| &span.start)
    }

    /**
    Get the additional properties associated with the span.
    */
    pub fn props(&self) -> &P {
        &self.props
    }

    /**
    Get exclusive access to the additional properties on the span.
    */
    pub fn props_mut(&mut self) -> &mut P {
        &mut self.props
    }

    /**
    Set the properties of the span.
    */
    pub fn with_props<U>(self, props: U) -> Span<'a, U> {
        Span {
            mdl: self.mdl,
            extent: self.extent,
            name: self.name,
            tpl: self.tpl,
            props,
        }
    }

    /**
    Map the properties of the span.
    */
    pub fn map_props<U>(self, map: impl FnOnce(P) -> U) -> Span<'a, U> {
        Span {
            mdl: self.mdl,
            extent: self.extent,
            name: self.name,
            tpl: self.tpl,
            props: map(self.props),
        }
    }

    /**
    Get the template that will be used to render the span.
    */
    pub fn tpl(&self) -> &Template<'a> {
        self.tpl.as_ref().unwrap_or(&END_TEMPLATE)
    }

    /**
    Set the template of the span.
    */
    pub fn with_tpl(mut self, tpl: impl Into<Template<'a>>) -> Self {
        self.tpl = Some(tpl.into());
        self
    }

    /**
    Get a type-erased span, borrowing data from this one.
    */
    pub fn erase<'b>(&'b self) -> Span<'b, &'b dyn ErasedProps> {
        Span {
            mdl: self.mdl.by_ref(),
            extent: self.extent.clone(),
            name: self.name.by_ref(),
            tpl: self.tpl.as_ref().map(|tpl| tpl.by_ref()),
            props: &self.props,
        }
    }
}

impl<'a, P: Props> fmt::Debug for Span<'a, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.to_event(), f)
    }
}

// "{span_name} started"
const START_TEMPLATE_PARTS: &'static [template::Part<'static>] = &[
    template::Part::hole("span_name"),
    template::Part::text(" started"),
];

static START_TEMPLATE: Template<'static> = Template::new(&START_TEMPLATE_PARTS);

// "{span_name} completed"
const END_TEMPLATE_PARTS: &'static [template::Part<'static>] = &[
    template::Part::hole("span_name"),
    template::Part::text(" completed"),
];

static END_TEMPLATE: Template<'static> = Template::new(&END_TEMPLATE_PARTS);

impl<'a, P: Props> ToEvent for Span<'a, P> {
    type Props<'b>
        = &'b Self
    where
        Self: 'b;

    fn to_event<'b>(&'b self) -> Event<'b, Self::Props<'b>> {
        Event::new(
            self.mdl.by_ref(),
            self.tpl().by_ref(),
            self.extent.clone(),
            &self,
        )
    }
}

impl<'a, P: Props> ToExtent for Span<'a, P> {
    fn to_extent(&self) -> Option<Extent> {
        self.extent().cloned()
    }
}

impl<'a, P: Props> Props for Span<'a, P> {
    fn for_each<'kv, F: FnMut(Str<'kv>, Value<'kv>) -> ControlFlow<()>>(
        &'kv self,
        mut for_each: F,
    ) -> ControlFlow<()> {
        for_each(KEY_EVT_KIND.to_str(), Kind::Span.to_value())?;
        for_each(KEY_SPAN_NAME.to_str(), self.name.to_value())?;

        self.props.for_each(&mut for_each)
    }
}

/**
The trace id, span id, and parent span id of a span.

These ids can be used to identify the distributed trace a span belongs to, and to identify the span itself within that trace.

The `SpanCtxt` for the currently executing span can be pulled from the ambient context with [`SpanCtxt::current`]. Once a `SpanCtxt` is constructed, a new child context can be generated by [`SpanCtxt::new_child`].

`SpanCtxt` should be pushed onto the ambient context with [`SpanCtxt::push`] so any events emitted during its execution are correlated to it.
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SpanCtxt {
    trace_id: Option<TraceId>,
    span_parent: Option<SpanId>,
    span_id: Option<SpanId>,
}

impl SpanCtxt {
    /**
    Create the context from a set of identifiers.

    The `trace_id` and `span_id` should both be `Some`, but `span_parent` may be `None` if the span is at the root of the distributed trace.

    If `trace_id` or `span_id` are `None` then the context is invalid, but can still be used.
    */
    pub const fn new(
        trace_id: Option<TraceId>,
        span_parent: Option<SpanId>,
        span_id: Option<SpanId>,
    ) -> Self {
        SpanCtxt {
            trace_id,
            span_parent,
            span_id,
        }
    }

    /**
    Create a context where all identifiers are `None`.
    */
    pub const fn empty() -> Self {
        Self {
            trace_id: None,
            span_parent: None,
            span_id: None,
        }
    }

    /**
    Generate a new context.
    */
    pub fn new_root(rng: impl Rng) -> Self {
        let trace_id = TraceId::random(&rng);
        let span_parent = None;
        let span_id = SpanId::random(&rng);

        SpanCtxt::new(trace_id, span_parent, span_id)
    }

    /**
    Read the current context from an ambient [`Ctxt`].

    This method will pull the [`TraceId`] from [`KEY_TRACE_ID`], the `SpanId` from [`KEY_SPAN_ID`], and the parent [`SpanId`] from [`KEY_SPAN_PARENT`].
    */
    pub fn current(ctxt: impl Ctxt) -> Self {
        ctxt.with_current(|current| {
            SpanCtxt::new(
                current.pull::<TraceId, _>(KEY_TRACE_ID),
                current.pull::<SpanId, _>(KEY_SPAN_PARENT),
                current.pull::<SpanId, _>(KEY_SPAN_ID),
            )
        })
    }

    /**
    Generate a new context that is a child of `self`.

    The new context will share the same trace id as `self`, use the span id of `self` as its parent span id, and generate a new random span id as its own through [`SpanId::random`].

    If [`Self::trace_id`] is `None` then a new trace id will be generated through [`TraceId::random`].
    */
    pub fn new_child(&self, rng: impl Rng) -> Self {
        let trace_id = self.trace_id.or_else(|| TraceId::random(&rng));
        let span_parent = self.span_id;
        let span_id = SpanId::random(&rng);

        SpanCtxt::new(trace_id, span_parent, span_id)
    }

    /**
    Get the trace id for the span.
    */
    pub fn trace_id(&self) -> Option<&TraceId> {
        self.trace_id.as_ref()
    }

    /**
    Get the parent of the span.
    */
    pub fn span_parent(&self) -> Option<&SpanId> {
        self.span_parent.as_ref()
    }

    /**
    Get the id of the span.
    */
    pub fn span_id(&self) -> Option<&SpanId> {
        self.span_id.as_ref()
    }

    /**
    Push the [`SpanCtxt`] onto the ambient context.

    The trace id, span id, and parent span id will be pushed to the context. This ensures diagnostics emitted during the execution of this span are properly linked to it.
    */
    pub fn push<T: Ctxt>(&self, ctxt: T) -> Frame<T> {
        Frame::push(ctxt, self)
    }
}

impl Props for SpanCtxt {
    fn for_each<'kv, F: FnMut(Str<'kv>, Value<'kv>) -> ControlFlow<()>>(
        &'kv self,
        mut for_each: F,
    ) -> ControlFlow<()> {
        if let Some(ref trace_id) = self.trace_id {
            for_each(KEY_TRACE_ID.to_str(), trace_id.to_value())?;
        }

        if let Some(ref span_id) = self.span_id {
            for_each(KEY_SPAN_ID.to_str(), span_id.to_value())?;
        }

        if let Some(ref span_parent) = self.span_parent {
            for_each(KEY_SPAN_PARENT.to_str(), span_parent.to_value())?;
        }

        ControlFlow::Continue(())
    }
}

/**
An error encountered attempting to parse a [`TraceId`] or [`SpanId`].
*/
#[derive(Debug)]
pub struct ParseKindError {}

impl fmt::Display for ParseKindError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "the input was not a valid kind")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseKindError {}

/**
A hint about the way a span and its child are linked.
*/
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SpanKind {
    /**
    Internal spans represent operations which do not cross a process boundary.
    */
    Internal,
    /**
    Server-side handling of an RPC or other remote network request.

    Paired with a `Client`.
    */
    Server,
    /**
    A request to some remote service.

    Paired with a `Server`.
    */
    Client,
    /**
    A producer sending a message to a broker.

    Paired with a `Consumer`.
    */
    Producer,
    /**
    A consumer receiving a message from a broker.

    Paired with a `Producer`.
    */
    Consumer,
}

impl SpanKind {
    /**
    Try parse a span kind from a formatted representation.
    */
    pub fn try_from_str(s: &str) -> Result<Self, ParseKindError> {
        s.parse()
    }

    /**
    Get the value of the span kind as a string.
    */
    pub fn as_str(&self) -> &'static str {
        match self {
            SpanKind::Internal => SPAN_KIND_INTERNAL,
            SpanKind::Server => SPAN_KIND_SERVER,
            SpanKind::Client => SPAN_KIND_CLIENT,
            SpanKind::Producer => SPAN_KIND_PRODUCER,
            SpanKind::Consumer => SPAN_KIND_CONSUMER,
        }
    }
}

impl FromStr for SpanKind {
    type Err = ParseKindError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();

        if s.eq_ignore_ascii_case(SPAN_KIND_INTERNAL) {
            return Ok(SpanKind::Internal);
        }

        if s.eq_ignore_ascii_case(SPAN_KIND_SERVER) {
            return Ok(SpanKind::Server);
        }

        if s.eq_ignore_ascii_case(SPAN_KIND_CLIENT) {
            return Ok(SpanKind::Client);
        }

        if s.eq_ignore_ascii_case(SPAN_KIND_PRODUCER) {
            return Ok(SpanKind::Producer);
        }

        if s.eq_ignore_ascii_case(SPAN_KIND_CONSUMER) {
            return Ok(SpanKind::Consumer);
        }

        Err(ParseKindError {})
    }
}

impl fmt::Debug for SpanKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{}\"", self)
    }
}

impl fmt::Display for SpanKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(feature = "sval")]
impl sval::Value for SpanKind {
    fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> sval::Result {
        stream.value(self.as_str())
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SpanKind {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.as_str().serialize(serializer)
    }
}

impl ToValue for SpanKind {
    fn to_value(&self) -> Value<'_> {
        Value::capture_display(self)
    }
}

impl<'v> FromValue<'v> for SpanKind {
    fn from_value(value: Value<'v>) -> Option<Self> {
        value
            .downcast_ref::<SpanKind>()
            .copied()
            .or_else(|| value.parse())
    }
}

/**
A link between two spans in potentially different traces.

A link belongs to a span, and contains the [`TraceId`] and [`SpanId`] of the span being linked to.
Links are usually created on the downstream span.

Links relate spans outside of the normal parent-child hierarchy.
Links are largely informative and may not be understood by downstream consumers.
In order to create a generic DAG out of span links, the spans would need to belong to separate traces, since the parent-child relationship is still required.
*/
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct SpanLink {
    trace_id: TraceId,
    span_id: SpanId,
}

impl SpanLink {
    /**
    Create a new link to the target span.
    */
    pub const fn new(trace_id: TraceId, span_id: SpanId) -> Self {
        SpanLink { trace_id, span_id }
    }

    /**
    Try parse a span link from a formatted representation.
    */
    pub fn try_from_str(s: &str) -> Result<Self, ParseLinkError> {
        Self::try_from_slice(s.as_bytes())
    }

    fn try_from_slice(s: &[u8]) -> Result<Self, ParseLinkError> {
        if s.len() != 49 {
            return Err(ParseLinkError {});
        }

        if s[32] != b'-' {
            return Err(ParseLinkError {});
        }

        let trace_id = TraceId::try_from_hex_slice(&s[0..32]).map_err(|_| ParseLinkError {})?;
        let span_id = SpanId::try_from_hex_slice(&s[33..49]).map_err(|_| ParseLinkError {})?;

        Ok(SpanLink::new(trace_id, span_id))
    }

    /**
    Try parse a span link from a formatted representation.
    */
    pub fn parse(s: impl fmt::Display) -> Result<Self, ParseLinkError> {
        let mut buf = Buffer::<49>::new();

        Self::try_from_slice(buf.buffer(s).map_err(|_| ParseLinkError {})?)
    }

    /**
    The [`TraceId`] of the linked span.
    */
    pub fn trace_id(&self) -> &TraceId {
        &self.trace_id
    }

    /**
    The [`SpanId`] of the linked span.
    */
    pub fn span_id(&self) -> &SpanId {
        &self.span_id
    }
}

impl FromStr for SpanLink {
    type Err = ParseLinkError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_str(s)
    }
}

impl fmt::Debug for SpanLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{}\"", self)
    }
}

impl fmt::Display for SpanLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut buf = [0; 49];

        buf[0..32].copy_from_slice(&self.trace_id.to_hex());
        buf[32] = b'-';
        buf[33..49].copy_from_slice(&self.span_id.to_hex());

        f.write_str(str::from_utf8(&buf).unwrap())
    }
}

#[cfg(feature = "sval")]
impl sval::Value for SpanLink {
    fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> sval::Result {
        sval::stream_display(stream, self)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SpanLink {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl ToValue for SpanLink {
    fn to_value(&self) -> Value<'_> {
        Value::capture_display(self)
    }
}

impl<'v> FromValue<'v> for SpanLink {
    fn from_value(value: Value<'v>) -> Option<Self> {
        value
            .downcast_ref::<SpanLink>()
            .copied()
            .or_else(|| SpanLink::parse(value).ok())
    }
}

/**
An error encountered attempting to parse a [`TraceId`] or [`SpanId`].
*/
#[derive(Debug)]
pub struct ParseLinkError {}

impl fmt::Display for ParseLinkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "the input was not a valid span link")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseLinkError {}

/**
An active span in a distributed trace.

## Creating active spans automatically

This type is created by the [`macro@crate::span!`] macro with the `guard` control parameter, or with the [`macro@crate::new_span!`] macro.

Call [`SpanGuard::complete_with`], or just drop the guard to complete it, passing the resulting [`Span`] to a [`Completion`].

## Creating active spans manually

The [`SpanGuard::new`] method can be used to construct a `SpanGuard` and [`Frame`] manually.

Call [`SpanGuard::start`] in the closure of [`Frame::call`] or async block of [`Frame::in_future`] on the returned [`Frame`] to begin the span. Once the span is started, it will complete automatically on drop, or manually through [`SpanGuard::complete`].

**Make sure you pass ownership of the returned `SpanGuard` into the closure in [`Frame::call`] or async block in [`Frame::in_future`]**. If you don't, the span will complete early, without its ambient context.
*/
pub struct SpanGuard<'a, T: Clock, P: Props, F: Completion> {
    state: SpanGuardState<T>,
    // `data` is `None` if the span is completed
    data: Option<SpanGuardData<'a, P>>,
    // `completion` is `None` if the span is disabled
    completion: Option<F>,
}

struct SpanGuardData<'a, P: Props> {
    mdl: Path<'a>,
    name: Str<'a>,
    ctxt: SpanCtxt,
    props: P,
}

enum SpanGuardState<T: Clock> {
    Initial(T),
    Started(Timer<T>),
    Completed,
}

impl<T: Clock> SpanGuardState<T> {
    fn take(&mut self) -> Self {
        mem::replace(self, SpanGuardState::Completed)
    }
}

impl<'a, T: Clock, P: Props, F: Completion> Drop for SpanGuard<'a, T, P, F> {
    fn drop(&mut self) {
        self.complete_default();
    }
}

impl<'a, T: Clock, P: Props, F: Completion> SpanGuard<'a, T, P, F> {
    /**
    Create a new active span.

    This method takes a number of parameters to construct a span. They are:

    - `filter`, `ctxt`, `clock`, `rng`: These typically come from a [`crate::runtime::Runtime`], like [`crate::runtime::shared`].
    - `completion`: A [`Completion`] that will be used by default when the returned `SpanGuard` is completed.
    - `ctxt_props`: A set of [`Props`] that will be pushed to the ambient context.
    - `span_mdl`, `span_name`, `span_props`: The input parameters to [`Span::new`] used to construct a span when the guard is completed.

    This method constructs a span based on the input properties and current context as follows:

    - A [`SpanCtxt`] for the span is generated using [`SpanCtxt::new_child`].
    - The filter is checked to see if the span should be enabled or disabled. The event passed to the filter is a [`Span`] carrying the generated span context, but without an extent.

    This method returns a tuple of a `SpanGuard` for starting and completing the span, and a [`Frame`] carrying the generated [`SpanCtxt`] and `ctxt_props`.

    Call [`SpanGuard::start`] in the closure of [`Frame::call`] or async block of [`Frame::in_future`] on the returned [`Frame`] to begin the span. Once the span is started, it will complete automatically on drop, or manually through [`SpanGuard::complete`].

    **Make sure you pass ownership of the returned `SpanGuard` into the closure in [`Frame::call`] or async block in [`Frame::in_future`]**. If you don't, the span will complete early, without its ambient context.
    */
    pub fn new<C: Ctxt>(
        filter: impl Filter,
        ctxt: C,
        clock: T,
        rng: impl Rng,
        completion: F,
        ctxt_props: impl Props,
        span_mdl: impl Into<Path<'a>>,
        span_name: impl Into<Str<'a>>,
        span_props: P,
    ) -> (Self, Frame<C>) {
        let span_mdl = span_mdl.into();
        let span_name = span_name.into();

        let span_ctxt = SpanCtxt::current(&ctxt).new_child(rng);

        // Check whether the span should be constructed using a dummy event
        let is_enabled = ctxt.with_current(|current_ctxt_props| {
            filter.matches(
                Span::new(
                    span_mdl.by_ref(),
                    span_name.by_ref(),
                    Empty,
                    (&span_props)
                        .and_props(&ctxt_props)
                        .and_props(span_ctxt)
                        .and_props(current_ctxt_props),
                )
                .to_event()
                .with_tpl(START_TEMPLATE.by_ref()),
            )
        });

        // Create a guard for the span
        // This can be completed automatically by dropping
        // or manually through the `complete` method
        let guard = SpanGuard {
            state: SpanGuardState::Initial(clock),
            data: Some(SpanGuardData {
                mdl: span_mdl,
                ctxt: span_ctxt,
                name: span_name,
                props: span_props,
            }),
            completion: if is_enabled { Some(completion) } else { None },
        };

        // Create a frame for the span props
        // This includes the trace and span ids
        let frame = guard.push_ctxt(ctxt, ctxt_props);

        (guard, frame)
    }

    fn push_ctxt<C: Ctxt>(&self, ctxt: C, ctxt_props: impl Props) -> Frame<C> {
        let span_ctxt = self.data.as_ref().expect("span is already complete").ctxt;

        if self.is_enabled() {
            Frame::push(ctxt, ctxt_props.and_props(span_ctxt))
        } else {
            Frame::disabled(ctxt, ctxt_props.and_props(span_ctxt))
        }
    }

    /**
    Start the span.

    From this point the span can be completed by either dropping this value, or by calling [`SpanGuard::complete`].
    */
    pub fn start(&mut self) {
        let state = mem::replace(&mut self.state, SpanGuardState::Completed);

        let SpanGuardState::Initial(clock) = state else {
            self.state = state;
            return;
        };

        self.state = SpanGuardState::Started(Timer::start(clock));
    }

    /**
    Whether the span will call its completion.

    If the filter called in [`SpanGuard::start`] evaluated to `false` then this method will also return `false`.
    */
    pub fn is_enabled(&self) -> bool {
        self.completion.is_some()
    }

    /**
    Set the default completion that will be called when the span is dropped or [`SpanGuard::complete`] is called.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn with_completion<U: Completion>(mut self, completion: U) -> SpanGuard<'a, T, P, U> {
        // Ensure this guard won't complete on drop
        self.completion.take();

        SpanGuard {
            state: self.state.take(),
            data: self.data.take(),
            completion: Some(completion),
        }
    }

    /**
    Set the module of the span.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn with_mdl(mut self, mdl: impl Into<Path<'a>>) -> Self {
        if let Some(ref mut data) = self.data {
            data.mdl = mdl.into();
        }
        self
    }

    /**
    Set the name of the span.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn with_name(mut self, name: impl Into<Str<'a>>) -> Self {
        if let Some(ref mut data) = self.data {
            data.name = name.into();
        }
        self
    }

    /**
    Set the properties of the span.

    If the span is disabled then this method is a no-op.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn with_props<U: Props>(self, props: U) -> SpanGuard<'a, T, U, F> {
        self.map_props(|_| props)
    }

    /**
    Map the properties of the span.

    If the span is disabled then this method is a no-op.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn map_props<U: Props>(mut self, map: impl FnOnce(P) -> U) -> SpanGuard<'a, T, U, F> {
        let data = self.data.take().map(|data| SpanGuardData {
            mdl: data.mdl,
            name: data.name,
            ctxt: data.ctxt,
            props: map(data.props),
        });

        SpanGuard {
            state: self.state.take(),
            data,
            completion: self.completion.take(),
        }
    }

    /**
    Push a property onto the span.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn push_prop<K: ToStr, V: ToValue>(
        self,
        key: K,
        value: V,
    ) -> SpanGuard<'a, T, And<(K, V), P>, F> {
        self.push_props((key, value))
    }

    /**
    Push a set of properties onto the span.
    */
    #[must_use = "this method returns a new `SpanGuard` that will be immediately dropped unless used"]
    pub fn push_props<U: Props>(self, props: U) -> SpanGuard<'a, T, And<U, P>, F> {
        self.map_props(|current| props.and_props(current))
    }

    /**
    Get exclusive access to the properties of the span.

    If the span is disabled this method will return `None`.
    */
    pub fn props_mut(&mut self) -> Option<&mut P> {
        self.data.as_mut().map(|data| &mut data.props)
    }

    /**
    Complete the span.

    If the span is disabled then this method is a no-op and will return `false`.
    */
    pub fn complete(mut self) -> bool {
        self.complete_default()
    }

    fn complete_default(&mut self) -> bool {
        if let (SpanGuardState::Started(timer), Some(data), Some(completion)) =
            (self.state.take(), self.data.take(), self.completion.take())
        {
            completion.complete(Span::new(data.mdl, data.name, timer, data.props));

            true
        } else {
            false
        }
    }

    /**
    Complete the span with the given closure.

    If the span is disabled then the `complete` closure won't be called and this method will return `false`.
    */
    pub fn complete_with(mut self, completion: impl Completion) -> bool {
        if let (SpanGuardState::Started(timer), Some(data), Some(_)) =
            (self.state.take(), self.data.take(), self.completion.take())
        {
            completion.complete(Span::new(data.mdl, data.name, timer, data.props));

            true
        } else {
            false
        }
    }
}

pub mod completion {
    /*!
    The [`Completion`] type.

    A [`Completion`] is a visitor for a [`Span`] that's called by a [`crate::span::SpanGuard`] when it completes.
    */

    use emit_core::{
        ctxt::Ctxt,
        emitter::Emitter,
        empty::Empty,
        event::ToEvent,
        props::{ErasedProps, Props},
        template::Template,
        value::{ToValue, Value},
        well_known::{KEY_ERR, KEY_LVL},
    };

    use crate::{level::Level, span::Span};

    use core::fmt;

    /**
    A receiver of [`Span`]s as they're completed by [`crate::span::SpanGuard`]s.
    */
    pub trait Completion {
        /**
        Receive a completing span.
        */
        fn complete<P: Props>(&self, span: Span<P>);
    }

    impl<'a, C: Completion + ?Sized> Completion for &'a C {
        fn complete<P: Props>(&self, span: Span<P>) {
            (**self).complete(span)
        }
    }

    impl Completion for Empty {
        fn complete<P: Props>(&self, _: Span<P>) {}
    }

    /**
    A default [`Completion`] that emits spans through an [`Emitter`].

    This type is a more sophisticated variant of [`FromEmitter`] that will:

    - Include ambient context from `C` on span events.
    - Detect panics and assign an error if it observes one.

    This type can be created directly, or via [`default`].
    */
    pub struct Default<'a, E, C, L = Level> {
        emitter: E,
        ctxt: C,
        tpl: Option<Template<'a>>,
        lvl: Option<L>,
        panic_lvl: Option<L>,
    }

    impl<'a, E: Emitter, C: Ctxt, L: ToValue> Completion for Default<'a, E, C, L> {
        fn complete<P: Props>(&self, span: Span<P>) {
            struct PanicError;

            impl fmt::Debug for PanicError {
                fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                    fmt::Display::fmt(self, f)
                }
            }

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

            #[cfg(feature = "std")]
            impl std::error::Error for PanicError {}

            impl ToValue for PanicError {
                fn to_value(&self) -> Value<'_> {
                    #[cfg(feature = "std")]
                    {
                        Value::capture_error(self)
                    }
                    #[cfg(not(feature = "std"))]
                    {
                        Value::capture_display(self)
                    }
                }
            }

            fn is_panicking() -> bool {
                #[cfg(feature = "std")]
                {
                    std::thread::panicking()
                }
                #[cfg(not(feature = "std"))]
                {
                    false
                }
            }

            let completion_props = if is_panicking() {
                [
                    self.panic_lvl
                        .as_ref()
                        .map(|lvl| Value::from_any(lvl))
                        .or_else(|| Some(Value::from_any(&Level::Error)))
                        .map(|lvl| (KEY_LVL, lvl)),
                    Some((KEY_ERR, Value::from_any(&PanicError))),
                ]
            } else {
                [
                    self.lvl
                        .as_ref()
                        .map(|lvl| Value::from_any(lvl))
                        .map(|lvl| (KEY_LVL, lvl)),
                    None,
                ]
            };

            let tpl = self.tpl.as_ref().unwrap_or_else(|| span.tpl()).by_ref();

            let evt = span
                .to_event()
                .with_tpl(tpl)
                .map_props(|span_props| completion_props.and_props(span_props));

            emit_core::emit(&self.emitter, Empty, &self.ctxt, Empty, evt);
        }
    }

    impl<'a, E, C, L> Default<'a, E, C, L> {
        /**
        Wrap the given emitter and context.
        */
        pub const fn new(emitter: E, ctxt: C) -> Self {
            Default {
                emitter,
                ctxt,
                tpl: None,
                lvl: None,
                panic_lvl: None,
            }
        }

        /**
        A level to assign to the span on completion.

        If the completion is called outside of a panic, this level will be used.
        */
        pub fn with_lvl(self, lvl: L) -> Self {
            Default {
                emitter: self.emitter,
                ctxt: self.ctxt,
                tpl: self.tpl,
                lvl: Some(lvl),
                panic_lvl: self.panic_lvl,
            }
        }

        /**
        A level to assign to the span on completion during a panic.
        */
        pub fn with_panic_lvl(self, lvl: L) -> Self {
            Default {
                emitter: self.emitter,
                ctxt: self.ctxt,
                tpl: self.tpl,
                lvl: self.lvl,
                panic_lvl: Some(lvl),
            }
        }

        /**
        A template to use for the span on completion.
        */
        pub fn with_tpl<'b>(self, tpl: impl Into<Template<'b>>) -> Default<'b, E, C, L> {
            Default {
                emitter: self.emitter,
                ctxt: self.ctxt,
                tpl: Some(tpl.into()),
                lvl: self.lvl,
                panic_lvl: self.panic_lvl,
            }
        }
    }

    /**
    Create a default [`Completion`] from an [`Emitter`] and [`Ctxt`].

    On completion, a [`Span`] will be emitted as an event using [`Span::to_event`].

    If the completion is called during a panic, it will attach an error to the span.
    */
    pub const fn default<'a, E: Emitter, C: Ctxt>(emitter: E, ctxt: C) -> Default<'a, E, C> {
        Default::new(emitter, ctxt)
    }

    /**
    A [`Completion`] from an [`Emitter`].

    On completion, a [`Span`] will be emitted as an event using [`Span::to_event`].

    This type can be created directly, or via [`from_emitter`].
    */
    pub struct FromEmitter<E>(E);

    impl<E: Emitter> Completion for FromEmitter<E> {
        fn complete<P: Props>(&self, span: Span<P>) {
            self.0.emit(span)
        }
    }

    impl<E> FromEmitter<E> {
        /**
        Wrap the given emitter.
        */
        pub const fn new(emitter: E) -> Self {
            FromEmitter(emitter)
        }
    }

    /**
    Create a [`Completion`] from an [`Emitter`].

    On completion, a [`Span`] will be emitted as an event using [`Span::to_event`].
    */
    pub const fn from_emitter<E: Emitter>(emitter: E) -> FromEmitter<E> {
        FromEmitter(emitter)
    }

    /**
    A [`Completion`] from a function.

    This type can be created directly, or via [`from_fn`].
    */
    pub struct FromFn<F = fn(Span<&dyn ErasedProps>)>(F);

    /**
    Create a [`Completion`] from a function.
    */
    pub const fn from_fn<F: Fn(Span<&dyn ErasedProps>)>(f: F) -> FromFn<F> {
        FromFn(f)
    }

    impl<F> FromFn<F> {
        /**
        Wrap the given completion function.
        */
        pub const fn new(completion: F) -> FromFn<F> {
            FromFn(completion)
        }
    }

    impl<F: Fn(Span<&dyn ErasedProps>)> Completion for FromFn<F> {
        fn complete<P: Props>(&self, span: Span<P>) {
            (self.0)(span.erase())
        }
    }

    mod internal {
        use super::*;

        pub trait DispatchCompletion {
            fn dispatch_complete(&self, span: Span<&dyn ErasedProps>);
        }

        pub trait SealedCompletion {
            fn erase_completion(&self) -> crate::internal::Erased<&dyn DispatchCompletion>;
        }
    }

    /**
    An object-safe [`Completion`].

    A `dyn ErasedCompletion` can be treated as `impl Completion`.
    */
    pub trait ErasedCompletion: internal::SealedCompletion {}

    impl<T: Completion> ErasedCompletion for T {}

    impl<T: Completion> internal::SealedCompletion for T {
        fn erase_completion(&self) -> crate::internal::Erased<&dyn internal::DispatchCompletion> {
            crate::internal::Erased(self)
        }
    }

    impl<T: Completion> internal::DispatchCompletion for T {
        fn dispatch_complete(&self, span: Span<&dyn ErasedProps>) {
            self.complete(span)
        }
    }

    impl<'a> Completion for dyn ErasedCompletion + 'a {
        fn complete<P: Props>(&self, span: Span<P>) {
            self.erase_completion().0.dispatch_complete(span.erase())
        }
    }

    impl<'a> Completion for dyn ErasedCompletion + Send + Sync + 'a {
        fn complete<P: Props>(&self, span: Span<P>) {
            (self as &(dyn ErasedCompletion + 'a)).complete(span)
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::cell::Cell;

        use emit_core::{emitter, path::Path};

        #[test]
        fn from_fn_completion() {
            let called = Cell::new(false);

            let completion = from_fn(|span| {
                assert_eq!("test", span.name());

                called.set(true);
            });

            completion.complete(Span::new(Path::new_raw("test"), "test", Empty, Empty));

            assert!(called.get());
        }

        #[test]
        fn erased_completion() {
            let called = Cell::new(false);

            let completion = from_fn(|span| {
                assert_eq!("test", span.name());

                called.set(true);
            });

            let completion = &completion as &dyn ErasedCompletion;

            completion.complete(Span::new(Path::new_raw("test"), "test", Empty, Empty));

            assert!(called.get());
        }

        #[test]
        fn default_completion() {
            let called = Cell::new(false);

            let completion = default(
                emitter::from_fn(|_| {
                    called.set(true);
                }),
                Empty,
            );

            completion.complete(Span::new(Path::new_raw("test"), "test", Empty, Empty));

            assert!(called.get());
        }

        #[test]
        fn default_completion_uses_lvl() {
            let called = Cell::new(false);

            let completion = default(
                emitter::from_fn(|evt| {
                    assert_eq!(Level::Info, evt.props().pull("lvl").unwrap());

                    called.set(true);
                }),
                Empty,
            )
            .with_lvl(Level::Info);

            completion.complete(Span::new(Path::new_raw("test"), "test", Empty, Empty));

            assert!(called.get());
        }

        #[test]
        fn default_completion_uses_tpl() {
            let called = Cell::new(false);

            let completion = default(
                emitter::from_fn(|evt| {
                    assert_eq!("test template", evt.msg().to_string());

                    called.set(true);
                }),
                Empty,
            )
            .with_lvl(Level::Info)
            .with_tpl(Template::literal("test template"));

            completion.complete(Span::new(Path::new_raw("test"), "test", Empty, Empty));

            assert!(called.get());
        }

        #[cfg(feature = "std")]
        #[cfg(not(target_arch = "wasm32"))]
        struct Guard<T: Completion>(T);

        #[cfg(feature = "std")]
        #[cfg(not(target_arch = "wasm32"))]
        impl<T: Completion> Drop for Guard<T> {
            fn drop(&mut self) {
                self.0
                    .complete(Span::new(Path::new_raw("test"), "test", Empty, Empty));
            }
        }

        #[test]
        #[cfg(feature = "std")]
        #[cfg(not(target_arch = "wasm32"))]
        fn default_completion_detects_panics() {
            let called = Cell::new(false);

            let completion = default(
                emitter::from_fn(|evt| {
                    assert_eq!(Level::Error, evt.props().pull("lvl").unwrap());
                    assert!(evt.props().get("err").is_some());

                    called.set(true);
                }),
                Empty,
            );

            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
                let _guard = Guard(completion);

                panic!("explicit panic")
            }));

            assert!(called.get());
        }

        #[test]
        #[cfg(feature = "std")]
        #[cfg(not(target_arch = "wasm32"))]
        fn default_completion_uses_panic_lvl() {
            let called = Cell::new(false);

            let completion = default(
                emitter::from_fn(|evt| {
                    assert_eq!(Level::Warn, evt.props().pull("lvl").unwrap());

                    called.set(true);
                }),
                Empty,
            )
            .with_panic_lvl(Level::Warn);

            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
                let _guard = Guard(completion);

                panic!("explicit panic")
            }));

            assert!(called.get());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    use emit_core::filter;

    use std::time::Duration;

    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    use std::cell::Cell;

    use crate::Timestamp;

    #[test]
    fn span_id_parse() {
        for (case, expected) in [
            (
                "0123456789abcdef",
                Ok(SpanId::from_u64(0x0123456789abcdef).unwrap()),
            ),
            (
                "0000000000000001",
                Ok(SpanId::from_u64(0x0000000000000001).unwrap()),
            ),
            ("0000000000000000", Err(ParseIdError {})),
            ("0x00000000000001", Err(ParseIdError {})),
            ("0x0000000000000001", Err(ParseIdError {})),
            ("1", Err(ParseIdError {})),
            ("", Err::<SpanId, ParseIdError>(ParseIdError {})),
        ] {
            match expected {
                Ok(expected) => {
                    assert_eq!(expected, SpanId::try_from_hex(case).unwrap());
                    assert_eq!(expected, SpanId::try_from_hex(case).unwrap());
                }
                Err(e) => assert_eq!(
                    e.to_string(),
                    SpanId::try_from_hex(case).unwrap_err().to_string()
                ),
            }
        }
    }

    #[test]
    fn trace_id_parse() {
        for (case, expected) in [
            (
                "0123456789abcdef0123456789abcdef",
                Ok(TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap()),
            ),
            (
                "00000000000000000000000000000001",
                Ok(TraceId::from_u128(0x00000000000000000000000000000001).unwrap()),
            ),
            ("00000000000000000000000000000000", Err(ParseIdError {})),
            ("0x000000000000000000000000000001", Err(ParseIdError {})),
            ("0x00000000000000000000000000000001", Err(ParseIdError {})),
            ("1", Err(ParseIdError {})),
            ("", Err::<TraceId, ParseIdError>(ParseIdError {})),
        ] {
            match expected {
                Ok(expected) => assert_eq!(expected, TraceId::try_from_hex(case).unwrap()),
                Err(e) => assert_eq!(
                    e.to_string(),
                    TraceId::try_from_hex(case).unwrap_err().to_string()
                ),
            }
        }
    }

    #[test]
    fn span_id_fmt() {
        for (case, expected) in [
            (SpanId::from_u64(1).unwrap(), "0000000000000001"),
            (
                SpanId::from_u64(0x0123456789abcdef).unwrap(),
                "0123456789abcdef",
            ),
        ] {
            assert_eq!(expected, case.to_string());
            assert_eq!(expected, str::from_utf8(&case.to_hex()).unwrap());
        }
    }

    #[test]
    fn trace_id_fmt() {
        for (case, expected) in [
            (
                TraceId::from_u128(1).unwrap(),
                "00000000000000000000000000000001",
            ),
            (
                TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
                "0123456789abcdef0123456789abcdef",
            ),
        ] {
            assert_eq!(expected, case.to_string());
            assert_eq!(expected, str::from_utf8(&case.to_hex()).unwrap());
        }
    }

    #[test]
    fn span_id_roundtrip() {
        let id = SpanId::new(NonZeroU64::new(u64::MAX / 2).unwrap());

        let fmt = id.to_string();

        let parsed: SpanId = fmt.parse().unwrap();

        assert_eq!(id, parsed, "{}", fmt);
    }

    #[test]
    fn trace_id_roundtrip() {
        let id = TraceId::new(NonZeroU128::new(u128::MAX / 2).unwrap());

        let fmt = id.to_string();

        let parsed: TraceId = fmt.parse().unwrap();

        assert_eq!(id, parsed, "{}", fmt);
    }

    #[test]
    fn span_id_random_empty() {
        assert!(SpanId::random(Empty).is_none());
    }

    #[test]
    #[cfg(feature = "rand")]
    fn span_id_random_rand() {
        assert!(SpanId::random(crate::platform::DefaultRng::new()).is_some());
    }

    #[test]
    fn trace_id_random_empty() {
        assert!(TraceId::random(Empty).is_none());
    }

    #[test]
    #[cfg(feature = "rand")]
    fn trace_id_random_rand() {
        assert!(TraceId::random(crate::platform::DefaultRng::new()).is_some());
    }

    #[test]
    fn span_id_to_from_value() {
        let id = SpanId::from_u64(u64::MAX / 2).unwrap();

        assert_eq!(id, SpanId::from_value(id.to_value()).unwrap());
    }

    #[test]
    fn span_id_from_value_string() {
        assert_eq!(
            SpanId::from_u64(0x0123456789abcdef).unwrap(),
            Value::from("0123456789abcdef").cast().unwrap()
        );
    }

    #[test]
    fn span_id_from_value_u64() {
        assert_eq!(
            SpanId::from_u64(0x0123456789abcdef).unwrap(),
            Value::from(0x0123456789abcdefu64).cast().unwrap()
        );
    }

    #[test]
    fn trace_id_to_from_value() {
        let id = TraceId::from_u128(u128::MAX / 2).unwrap();

        assert_eq!(id, TraceId::from_value(id.to_value()).unwrap());
    }

    #[test]
    fn trace_id_from_value_string() {
        assert_eq!(
            TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            Value::from("0123456789abcdef0123456789abcdef")
                .cast()
                .unwrap()
        );
    }

    #[test]
    fn trace_id_from_value_u128() {
        assert_eq!(
            TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            Value::from(0x0123456789abcdef0123456789abcdefu128)
                .cast()
                .unwrap()
        );
    }

    #[cfg(feature = "sval")]
    #[test]
    fn span_id_stream() {
        sval_test::assert_tokens(
            &SpanId::from_u64(0x0123456789abcdef).unwrap(),
            &[
                sval_test::Token::TextBegin(None),
                sval_test::Token::TextFragmentComputed("0123456789abcdef".to_owned()),
                sval_test::Token::TextEnd,
            ],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn span_id_serialize() {
        serde_test::assert_ser_tokens(
            &SpanId::from_u64(0x0123456789abcdef).unwrap(),
            &[serde_test::Token::Str("0123456789abcdef")],
        );
    }

    #[cfg(feature = "sval")]
    #[test]
    fn trace_id_stream() {
        sval_test::assert_tokens(
            &TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            &[
                sval_test::Token::TextBegin(None),
                sval_test::Token::TextFragmentComputed(
                    "0123456789abcdef0123456789abcdef".to_owned(),
                ),
                sval_test::Token::TextEnd,
            ],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn trace_id_serialize() {
        serde_test::assert_ser_tokens(
            &TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            &[serde_test::Token::Str("0123456789abcdef0123456789abcdef")],
        );
    }

    #[test]
    fn span_link_parse() {
        for (case, expected) in [
            (
                "0123456789abcdef0123456789abcdef-0123456789abcdef",
                Ok::<SpanLink, ParseLinkError>(SpanLink::new(
                    TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
                    SpanId::from_u64(0x0123456789abcdef).unwrap(),
                )),
            ),
            (
                "00000000000000000000000000000001-0000000000000001",
                Ok::<SpanLink, ParseLinkError>(SpanLink::new(
                    TraceId::from_u128(0x1).unwrap(),
                    SpanId::from_u64(0x1).unwrap(),
                )),
            ),
            (
                "00000000000000000000000000000000-0000000000000000",
                Err(ParseLinkError {}),
            ),
            (
                "0123456789abcdef0123456789abcde-0123456789abcdef",
                Err(ParseLinkError {}),
            ),
            (
                "0123456789abcdef0123456789abcdef-0123456789abcde",
                Err(ParseLinkError {}),
            ),
            (
                "0123456789abcdef0123456789abcdef 0123456789abcdef",
                Err(ParseLinkError {}),
            ),
            (
                "0123456789abcdef0123456789abcdef0123456789abcdef",
                Err(ParseLinkError {}),
            ),
        ] {
            match expected {
                Ok(expected) => assert_eq!(expected, SpanLink::try_from_str(case).unwrap()),
                Err(e) => assert_eq!(
                    e.to_string(),
                    SpanLink::try_from_str(case).unwrap_err().to_string()
                ),
            }
        }
    }

    #[test]
    fn span_link_fmt() {
        let link = SpanLink::new(
            TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            SpanId::from_u64(0x0123456789abcdef).unwrap(),
        );

        assert_eq!(
            "0123456789abcdef0123456789abcdef-0123456789abcdef",
            link.to_string()
        );
    }

    #[test]
    fn span_link_roundtrip() {
        let link = SpanLink::new(
            TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            SpanId::from_u64(0x0123456789abcdef).unwrap(),
        );

        assert_eq!(link, SpanLink::parse(link).unwrap());
    }

    #[test]
    fn span_link_to_from_value() {
        let link = SpanLink::new(
            TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
            SpanId::from_u64(0x0123456789abcdef).unwrap(),
        );

        assert_eq!(link, SpanLink::from_value(link.to_value()).unwrap());
    }

    #[test]
    fn span_link_from_value_string() {
        assert_eq!(
            SpanLink::new(
                TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
                SpanId::from_u64(0x0123456789abcdef).unwrap(),
            ),
            Value::from("0123456789abcdef0123456789abcdef-0123456789abcdef")
                .cast()
                .unwrap()
        );
    }

    #[cfg(feature = "sval")]
    #[test]
    fn span_link_stream() {
        sval_test::assert_tokens(
            &SpanLink::new(
                TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
                SpanId::from_u64(0x0123456789abcdef).unwrap(),
            ),
            &[
                sval_test::Token::TextBegin(None),
                sval_test::Token::TextFragmentComputed(
                    "0123456789abcdef0123456789abcdef-0123456789abcdef".to_owned(),
                ),
                sval_test::Token::TextEnd,
            ],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn span_link_serialize() {
        serde_test::assert_ser_tokens(
            &SpanLink::new(
                TraceId::from_u128(0x0123456789abcdef0123456789abcdef).unwrap(),
                SpanId::from_u64(0x0123456789abcdef).unwrap(),
            ),
            &[serde_test::Token::Str(
                "0123456789abcdef0123456789abcdef-0123456789abcdef",
            )],
        );
    }

    #[test]
    fn span_kind_parse() {
        for (case, expected) in [
            ("internal", Some(SpanKind::Internal)),
            (" internal ", Some(SpanKind::Internal)),
            ("server", Some(SpanKind::Server)),
            ("client", Some(SpanKind::Client)),
            ("producer", Some(SpanKind::Producer)),
            ("consumer", Some(SpanKind::Consumer)),
            ("", None),
            ("int", None),
            ("internalx", None),
        ] {
            assert_eq!(expected, SpanKind::try_from_str(case).ok());
        }
    }

    #[test]
    fn span_kind_roundtrip() {
        for case in [
            SpanKind::Internal,
            SpanKind::Server,
            SpanKind::Client,
            SpanKind::Producer,
            SpanKind::Consumer,
        ] {
            assert_eq!(case, SpanKind::try_from_str(&case.to_string()).unwrap());
        }
    }

    #[cfg(feature = "sval")]
    #[test]
    fn span_kind_stream() {
        sval_test::assert_tokens(
            &SpanKind::Internal,
            &[
                sval_test::Token::TextBegin(Some(8)),
                sval_test::Token::TextFragment("internal"),
                sval_test::Token::TextEnd,
            ],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn span_kind_serialize() {
        serde_test::assert_ser_tokens(&SpanKind::Internal, &[serde_test::Token::Str("internal")]);
    }

    #[test]
    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    fn span_ctxt_new() {
        let rng = crate::platform::DefaultRng::new();
        let ctxt = crate::platform::DefaultCtxt::new();

        // Span context from an empty source is empty
        let root = SpanCtxt::current(&ctxt);
        assert_eq!(SpanCtxt::empty(), root);

        // New root context has a new trace id and span id, but no parent
        let root = SpanCtxt::new_root(&rng);

        assert!(root.span_id.is_some());
        assert!(root.trace_id.is_some());
        assert!(root.span_parent.is_none());

        // Push the span context onto the source
        let mut frame = ctxt.open_push(root);

        ctxt.enter(&mut frame);

        // Span context from a non-empty source is the last pushed
        let current = SpanCtxt::current(&ctxt);
        assert_eq!(root, current);
        let root = current;

        // A child span shares the same trace id, but has a new span id
        // The span id of the parent becomes the span parent
        let child = SpanCtxt::new_child(&root, &rng);

        assert_eq!(root.trace_id, child.trace_id);
        assert_ne!(root.span_id, child.span_id);
        assert!(child.span_id.is_some());
        assert_eq!(root.span_id, child.span_parent);

        ctxt.exit(&mut frame);
        ctxt.close(frame);
    }

    #[test]
    fn span_new() {
        let span = Span::new(
            Path::new_raw("test"),
            "my span",
            Timestamp::from_unix(Duration::from_secs(1)),
            ("span_prop", true),
        );

        assert_eq!("test", span.mdl());
        assert_eq!(
            Timestamp::from_unix(Duration::from_secs(1)).unwrap(),
            span.extent().unwrap().as_point()
        );
        assert_eq!("my span", span.name());
        assert_eq!(true, span.props().pull::<bool, _>("span_prop").unwrap());
    }

    #[test]
    fn span_to_event() {
        let span = Span::new(
            Path::new_raw("test"),
            "my span",
            Timestamp::from_unix(Duration::from_secs(1)),
            ("span_prop", true),
        );

        let evt = span.to_event();

        assert_eq!("test", evt.mdl());
        assert_eq!(
            Timestamp::from_unix(Duration::from_secs(1)).unwrap(),
            evt.extent().unwrap().as_point()
        );
        assert_eq!("my span completed", evt.msg().to_string());
        assert_eq!(
            "my span",
            evt.props().pull::<Str, _>(KEY_SPAN_NAME).unwrap()
        );
        assert_eq!(true, evt.props().pull::<bool, _>("span_prop").unwrap());
        assert_eq!(
            Kind::Span,
            evt.props().pull::<Kind, _>(KEY_EVT_KIND).unwrap()
        );
    }

    #[test]
    fn span_to_event_uses_tpl() {
        assert_eq!(
            "test",
            Span::new(
                Path::new_raw("test"),
                "my span",
                Timestamp::from_unix(Duration::from_secs(1)),
                ("span_prop", true),
            )
            .with_tpl(Template::literal("test"))
            .to_event()
            .msg()
            .to_string(),
        );
    }

    #[test]
    fn span_to_extent() {
        for (case, expected) in [
            (
                Some(Timestamp::from_unix(Duration::from_secs(1)).unwrap()),
                Some(Extent::point(
                    Timestamp::from_unix(Duration::from_secs(1)).unwrap(),
                )),
            ),
            (None, None),
        ] {
            let span = Span::new(Path::new_raw("test"), "my span", case, ("span_prop", true));

            let extent = span.to_extent();

            assert_eq!(
                expected.map(|extent| extent.as_range().cloned()),
                extent.map(|extent| extent.as_range().cloned())
            );
        }
    }

    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    struct MyClock(Cell<u64>);

    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    impl Clock for MyClock {
        fn now(&self) -> Option<crate::Timestamp> {
            let ts = crate::Timestamp::from_unix(Duration::from_secs(self.0.get()));
            self.0.set(self.0.get() + 1);
            ts
        }
    }

    #[test]
    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    fn active_span_new() {
        let clock = MyClock(Cell::new(0));
        let rng = crate::platform::DefaultRng::new();
        let ctxt = crate::platform::DefaultCtxt::new();

        let complete_called = Cell::new(false);

        let (mut guard, frame) = SpanGuard::new(
            filter::from_fn(|evt| {
                assert_eq!(2, evt.props().pull::<usize, _>("ctxt_prop").unwrap());

                assert!(evt.props().get("trace_id").is_some());
                assert!(evt.props().get("span_id").is_some());

                true
            }),
            &ctxt,
            &clock,
            &rng,
            completion::from_fn(|evt| {
                assert_eq!(
                    Timestamp::from_unix(Duration::from_secs(0)).unwrap(),
                    evt.extent().unwrap().as_range().unwrap().start
                );
                assert_eq!(
                    Timestamp::from_unix(Duration::from_secs(1)).unwrap(),
                    evt.extent().unwrap().as_range().unwrap().end
                );

                assert_eq!("test", evt.mdl());
                assert_eq!("span", evt.name());

                assert_eq!(1, evt.props().pull::<usize, _>("event_prop").unwrap());

                ctxt.with_current(|props| {
                    assert_eq!(2, props.pull::<usize, _>("ctxt_prop").unwrap());
                });

                let current_ctxt = SpanCtxt::current(&ctxt);

                assert_ne!(current_ctxt, SpanCtxt::empty());

                complete_called.set(true);
            }),
            ("ctxt_prop", 2),
            Path::new_raw("test"),
            "span",
            ("event_prop", 1),
        );

        assert!(guard.is_enabled());

        frame.call(move || {
            guard.start();

            drop(guard);
        });

        assert!(complete_called.get());
    }

    #[test]
    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    fn active_span_unstarted_complete() {
        let clock = MyClock(Cell::new(0));
        let rng = crate::platform::DefaultRng::new();
        let ctxt = crate::platform::DefaultCtxt::new();

        let complete_called = Cell::new(false);

        let (guard, frame) = SpanGuard::new(
            filter::from_fn(|_| true),
            &ctxt,
            &clock,
            &rng,
            completion::from_fn(|_| {}),
            Empty,
            Path::new_raw("test"),
            "span",
            Empty,
        );

        assert!(guard.is_enabled());

        frame.call(move || {
            drop(guard);
        });

        assert!(!complete_called.get());
    }

    #[test]
    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    fn active_span_new_disabled() {
        let rng = crate::platform::DefaultRng::new();
        let clock = crate::platform::DefaultClock::new();
        let ctxt = crate::platform::DefaultCtxt::new();

        let complete_called = Cell::new(false);

        let (mut guard, frame) = SpanGuard::new(
            filter::from_fn(|_| false),
            &ctxt,
            &clock,
            &rng,
            completion::from_fn(|_| {
                complete_called.set(true);
            }),
            Empty,
            Path::new_raw("test"),
            "span",
            Empty,
        );

        assert!(!guard.is_enabled());

        frame.call(move || {
            guard.start();

            drop(guard);
        });

        assert!(!complete_called.get());
    }

    #[test]
    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    fn active_span_custom_complete() {
        let ctxt = crate::platform::DefaultCtxt::new();
        let clock = crate::platform::DefaultClock::new();
        let rng = crate::platform::DefaultRng::new();

        let custom_complete_called = Cell::new(false);
        let default_complete_called = Cell::new(false);

        let (mut guard, _) = SpanGuard::new(
            filter::from_fn(|_| true),
            &ctxt,
            &clock,
            &rng,
            completion::from_fn(|_| {
                default_complete_called.set(true);
            }),
            Empty,
            Path::new_raw("test"),
            "span",
            Empty,
        );

        assert!(guard.is_enabled());

        guard.start();

        guard.complete_with(completion::from_fn(|_| {
            custom_complete_called.set(true);
        }));

        assert!(!default_complete_called.get());
        assert!(custom_complete_called.get());
    }

    #[test]
    #[cfg(all(feature = "std", feature = "rand", not(miri)))]
    fn active_span_with_props() {
        let clock = MyClock(Cell::new(0));
        let rng = crate::platform::DefaultRng::new();
        let ctxt = crate::platform::DefaultCtxt::new();

        let complete_called = Cell::new(false);

        let (mut guard, frame) = SpanGuard::new(
            filter::from_fn(|_| true),
            &ctxt,
            &clock,
            &rng,
            completion::from_fn(|evt| {
                assert_eq!(2, evt.props().pull::<usize, _>("event_prop").unwrap());

                complete_called.set(true);
            }),
            Empty,
            Path::new_raw("test"),
            "span",
            ("event_prop", 1),
        );

        frame.call(move || {
            guard.start();

            let guard = guard.with_props(("event_prop", 2));

            drop(guard);
        });

        assert!(complete_called.get());
    }
}