fuchsia_trace/
lib.rs

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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use pin_project::pin_project;
use std::ffi::CStr;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::Poll;
use std::{mem, ptr};

pub use sys::{
    trace_site_t, TRACE_BLOB_TYPE_DATA, TRACE_BLOB_TYPE_LAST_BRANCH, TRACE_BLOB_TYPE_PERFETTO,
};

/// `Scope` represents the scope of a trace event.
#[derive(Copy, Clone)]
pub enum Scope {
    Thread,
    Process,
    Global,
}

impl Scope {
    fn into_raw(self) -> sys::trace_scope_t {
        match self {
            Scope::Thread => sys::TRACE_SCOPE_THREAD,
            Scope::Process => sys::TRACE_SCOPE_PROCESS,
            Scope::Global => sys::TRACE_SCOPE_GLOBAL,
        }
    }
}

/// Returns true if tracing is enabled.
#[inline]
pub fn is_enabled() -> bool {
    // Trivial no-argument function that will not race
    unsafe { sys::trace_state() != sys::TRACE_STOPPED }
}

/// Returns true if tracing has been enabled for the given category.
pub fn category_enabled(category: &'static CStr) -> bool {
    // Function requires a pointer to a static null-terminated string literal,
    // which `&'static CStr` is.
    unsafe { sys::trace_is_category_enabled(category.as_ptr()) }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TraceState {
    Stopped,
    Started,
    Stopping,
}

pub fn trace_state() -> TraceState {
    match unsafe { sys::trace_state() } {
        sys::TRACE_STOPPED => TraceState::Stopped,
        sys::TRACE_STARTED => TraceState::Started,
        sys::TRACE_STOPPING => TraceState::Stopping,
        s => panic!("Unknown trace state {:?}", s),
    }
}

/// An identifier for flows and async spans.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id(u64);

impl Id {
    /// Creates a new `Id`. `Id`s created by separate calls to `new` in the same process are
    /// guaranteed to be distinct.
    ///
    /// WARNING: `Id::new` is likely to hit the UI bug where UIs group async
    /// durations with the same trace id but different process ids. Use
    /// `Id::random` instead. (Until https://fxbug.dev/42054669 is fixed.)
    pub fn new() -> Self {
        // Trivial no-argument function that cannot race.
        Self(unsafe { sys::trace_generate_nonce() })
    }

    /// Creates a new `Id` based on the current montonic time and a random `u16` to, with high
    /// probability, avoid the bug where UIs group async durations with the same trace id but
    /// different process ids.
    /// `Id::new` is likely to hit the UI bug because it (per process) generates trace ids
    /// consecutively starting from 1.
    /// https://cs.opensource.google/fuchsia/fuchsia/+/main:zircon/system/ulib/trace-engine/nonce.cc;l=15-17;drc=b1c2f508a59e6c87c617852ed3e424693a392646
    /// TODO(https://fxbug.dev/42054669) Delete this and migrate clients to `Id::new` once UIs stop grouping
    /// async durations with the same trace id but different process ids.
    pub fn random() -> Self {
        let ts = zx::BootInstant::get().into_nanos() as u64;
        let high_order = ts << 16;
        let low_order = rand::random::<u16>() as u64;
        Self(high_order | low_order)
    }
}

impl From<u64> for Id {
    fn from(u: u64) -> Self {
        Self(u)
    }
}

impl From<Id> for u64 {
    fn from(id: Id) -> Self {
        id.0
    }
}

/// `Arg` holds an argument to a tracing function, which can be one of many types.
#[repr(transparent)]
pub struct Arg<'a>(sys::trace_arg_t, PhantomData<&'a ()>);

/// A trait for types that can be the values of an argument set.
///
/// This trait is not implementable by users of the library.
/// Users should instead use one of the common types which implements
/// `ArgValue`, such as `i32`, `f64`, or `&str`.
pub trait ArgValue {
    fn of<'a>(key: &'a str, value: Self) -> Arg<'a>
    where
        Self: 'a;
}

// Implements `arg_from` for many types.
// $valname is the name to which to bind the `Self` value in the $value expr
// $ty is the type
// $tag is the union tag indicating the variant of trace_arg_union_t being used
// $value is the union value for that particular type
macro_rules! arg_from {
    ($valname:ident, $(($type:ty, $tag:expr, $value:expr))*) => {
        $(
            impl ArgValue for $type {
                #[inline]
                fn of<'a>(key: &'a str, $valname: Self) -> Arg<'a>
                    where Self: 'a
                {
                    #[allow(unused)]
                    let $valname = $valname;

                    Arg(sys::trace_arg_t {
                        name_ref: trace_make_inline_string_ref(key),
                        value: sys::trace_arg_value_t {
                            type_: $tag,
                            value: $value,
                        },
                    }, PhantomData)
                }
            }
        )*
    }
}

// Implement ArgFrom for a variety of types
#[rustfmt::skip]
arg_from!(val,
    ((), sys::TRACE_ARG_NULL, sys::trace_arg_union_t { int32_value: 0 })
    (bool, sys::TRACE_ARG_BOOL, sys::trace_arg_union_t { bool_value: val })
    (i32, sys::TRACE_ARG_INT32, sys::trace_arg_union_t { int32_value: val })
    (u32, sys::TRACE_ARG_UINT32, sys::trace_arg_union_t { uint32_value: val })
    (i64, sys::TRACE_ARG_INT64, sys::trace_arg_union_t { int64_value: val })
    (u64, sys::TRACE_ARG_UINT64, sys::trace_arg_union_t { uint64_value: val })
    (isize, sys::TRACE_ARG_INT64, sys::trace_arg_union_t { int64_value: val as i64 })
    (usize, sys::TRACE_ARG_UINT64, sys::trace_arg_union_t { uint64_value: val as u64 })
    (f64, sys::TRACE_ARG_DOUBLE, sys::trace_arg_union_t { double_value: val })
    (zx::Koid, sys::TRACE_ARG_KOID, sys::trace_arg_union_t { koid_value: val.raw_koid() })
);

impl<T> ArgValue for *const T {
    #[inline]
    fn of<'a>(key: &'a str, val: Self) -> Arg<'a>
    where
        Self: 'a,
    {
        Arg(
            sys::trace_arg_t {
                name_ref: trace_make_inline_string_ref(key),
                value: sys::trace_arg_value_t {
                    type_: sys::TRACE_ARG_POINTER,
                    value: sys::trace_arg_union_t { pointer_value: val as usize },
                },
            },
            PhantomData,
        )
    }
}

impl<T> ArgValue for *mut T {
    #[inline]
    fn of<'a>(key: &'a str, val: Self) -> Arg<'a>
    where
        Self: 'a,
    {
        Arg(
            sys::trace_arg_t {
                name_ref: trace_make_inline_string_ref(key),
                value: sys::trace_arg_value_t {
                    type_: sys::TRACE_ARG_POINTER,
                    value: sys::trace_arg_union_t { pointer_value: val as usize },
                },
            },
            PhantomData,
        )
    }
}

impl<'a> ArgValue for &'a str {
    #[inline]
    fn of<'b>(key: &'b str, val: Self) -> Arg<'b>
    where
        Self: 'b,
    {
        Arg(
            sys::trace_arg_t {
                name_ref: trace_make_inline_string_ref(key),
                value: sys::trace_arg_value_t {
                    type_: sys::TRACE_ARG_STRING,
                    value: sys::trace_arg_union_t {
                        string_value_ref: trace_make_inline_string_ref(val),
                    },
                },
            },
            PhantomData,
        )
    }
}

/// Convenience macro for the `instant` function.
///
/// Example:
///
/// ```rust
/// instant!(c"foo", c"bar", Scope::Process, "x" => 5, "y" => "boo");
/// ```
///
/// is equivalent to
///
/// ```rust
/// instant(c"foo", c"bar", Scope::Process,
///     &[ArgValue::of("x", 5), ArgValue::of("y", "boo")]);
/// ```
/// or
/// ```rust
/// const FOO: &'static CStr = c"foo";
/// const BAR: &'static CStr = c"bar";
/// instant(FOO, BAR, Scope::Process,
///     &[ArgValue::of("x", 5), ArgValue::of("y", "boo")]);
/// ```
#[macro_export]
macro_rules! instant {
    ($category:expr, $name:expr, $scope:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::instant(&context, $name, $scope, &[$($crate::ArgValue::of($key, $val)),*]);
            }
        }
    }
}

/// Writes an instant event representing a single moment in time.
/// The number of `args` must not be greater than 15.
#[inline]
pub fn instant(
    context: &TraceCategoryContext,
    name: &'static CStr,
    scope: Scope,
    args: &[Arg<'_>],
) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_instant(name_ref, scope, args);
}

/// Convenience macro for the `alert` function.
///
/// Example:
///
/// ```rust
/// alert!(c"foo", c"bar");
/// ```
///
/// is equivalent to
///
/// ```rust
/// alert(c"foo", c"bar");
/// ```
#[macro_export]
macro_rules! alert {
    ($category:expr, $name:expr) => {
        $crate::alert($category, $name)
    };
}

/// Sends an alert, which can be mapped to an action.
pub fn alert(category: &'static CStr, name: &'static CStr) {
    // trace_context_write_xxx functions require that:
    // - category and name are static null-terminated strings (`&'static CStr).
    // - the refs must be valid for the given call
    unsafe {
        let mut category_ref = mem::MaybeUninit::<sys::trace_string_ref_t>::uninit();
        let context =
            sys::trace_acquire_context_for_category(category.as_ptr(), category_ref.as_mut_ptr());
        if context != ptr::null() {
            sys::trace_context_send_alert(context, name.as_ptr());
            sys::trace_release_context(context);
        }
    }
}

/// Convenience macro for the `counter` function.
///
/// Example:
///
/// ```rust
/// let id = 555;
/// counter!(c"foo", c"bar", id, "x" => 5, "y" => 10);
/// ```
///
/// is equivalent to
///
/// ```rust
/// let id = 555;
/// counter(c"foo", c"bar", id,
///     &[ArgValue::of("x", 5), ArgValue::of("y", 10)]);
/// ```
#[macro_export]
macro_rules! counter {
    ($category:expr, $name:expr, $counter_id:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::counter(&context, $name, $counter_id,
                    &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    }
}

/// Writes a counter event with the specified id.
///
/// The arguments to this event are numeric samples and are typically
/// represented by the visualizer as a stacked area chart. The id serves to
/// distinguish multiple instances of counters which share the same category
/// and name within the same process.
///
/// 1 to 15 numeric arguments can be associated with an event, each of which is
/// interpreted as a distinct time series.
pub fn counter(
    context: &TraceCategoryContext,
    name: &'static CStr,
    counter_id: u64,
    args: &[Arg<'_>],
) {
    assert!(args.len() >= 1, "trace counter args must include at least one numeric argument");
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_counter(name_ref, counter_id, args);
}

/// The scope of a duration event, returned by the `duration` function and the `duration!` macro.
/// The duration will be `end'ed` when this object is dropped.
#[must_use = "DurationScope must be `end`ed to be recorded"]
pub struct DurationScope<'a> {
    category: &'static CStr,
    name: &'static CStr,
    args: &'a [Arg<'a>],
    start_time: zx::BootTicks,
}

impl<'a> DurationScope<'a> {
    /// Starts a new duration scope that starts now and will be end'ed when
    /// this object is dropped.
    pub fn begin(category: &'static CStr, name: &'static CStr, args: &'a [Arg<'_>]) -> Self {
        let start_time = zx::BootTicks::get();
        Self { category, name, args, start_time }
    }
}

impl<'a> Drop for DurationScope<'a> {
    fn drop(&mut self) {
        if let Some(context) = TraceCategoryContext::acquire(self.category) {
            let name_ref = context.register_string_literal(self.name);
            context.write_duration(name_ref, self.start_time, self.args);
        }
    }
}

/// Write a "duration complete" record representing both the beginning and end of a duration.
pub fn complete_duration(
    category: &'static CStr,
    name: &'static CStr,
    start_time: zx::BootTicks,
    args: &[Arg<'_>],
) {
    if let Some(context) = TraceCategoryContext::acquire(category) {
        let name_ref = context.register_string_literal(name);
        context.write_duration(name_ref, start_time, args);
    }
}

/// Convenience macro for the `duration` function that can be used to trace
/// the duration of a scope. If you need finer grained control over when a
/// duration starts and stops, see `duration_begin` and `duration_end`.
///
/// Example:
///
/// ```rust
///   {
///       duration!(c"foo", c"bar", "x" => 5, "y" => 10);
///       ...
///       ...
///       // event will be recorded on drop.
///   }
/// ```
///
/// is equivalent to
///
/// ```rust
///   {
///       let args = [ArgValue::of("x", 5), ArgValue::of("y", 10)];
///       let _scope = duration(c"foo", c"bar", &args);
///       ...
///       ...
///       // event will be recorded on drop.
///   }
/// ```
#[macro_export]
macro_rules! duration {
    ($category:expr, $name:expr $(, $key:expr => $val:expr)* $(,)?) => {
        let mut args;
        let _scope =  {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                args = [$($crate::ArgValue::of($key, $val)),*];
                Some($crate::duration($category, $name, &args))
            } else {
                None
            }
        };
    }
}

/// Writes a duration event which ends when the current scope exits, or the
/// `end` method is manually called.
///
/// Durations describe work which is happening synchronously on one thread.
/// They can be nested to represent a control flow stack.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the duration with additional information.
pub fn duration<'a>(
    category: &'static CStr,
    name: &'static CStr,
    args: &'a [Arg<'_>],
) -> DurationScope<'a> {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");
    DurationScope::begin(category, name, args)
}

/// Convenience macro for the `duration_begin` function.
///
/// Examples:
///
/// ```rust
/// duration_begin!(c"foo", c"bar", "x" => 5, "y" => "boo");
/// ```
///
/// ```rust
/// const FOO: &'static CStr = c"foo";
/// const BAR: &'static CStr = c"bar";
/// duration_begin!(FOO, BAR, "x" => 5, "y" => "boo");
/// ```
#[macro_export]
macro_rules! duration_begin {
    ($category:expr, $name:expr $(, $key:expr => $val:expr)* $(,)?) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::duration_begin(&context, $name,
                                       &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    };
}

/// Convenience macro for the `duration_end` function.
///
/// Examples:
///
/// ```rust
/// duration_end!(c"foo", c"bar", "x" => 5, "y" => "boo");
/// ```
///
/// ```rust
/// const FOO: &'static CStr = c"foo";
/// const BAR: &'static CStr = c"bar";
/// duration_end!(FOO, BAR, "x" => 5, "y" => "boo");
/// ```
#[macro_export]
macro_rules! duration_end {
    ($category:expr, $name:expr $(, $key:expr => $val:expr)* $(,)?) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::duration_end(&context, $name, &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    };
}

/// Writes a duration begin event only.
/// This event must be matched by a duration end event with the same category and name.
///
/// Durations describe work which is happening synchronously on one thread.
/// They can be nested to represent a control flow stack.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the duration with additional information.  The arguments provided
/// to matching duration begin and duration end events are combined together in
/// the trace; it is not necessary to repeat them.
pub fn duration_begin(context: &TraceCategoryContext, name: &'static CStr, args: &[Arg<'_>]) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_duration_begin(name_ref, args);
}

/// Writes a duration end event only.
///
/// Durations describe work which is happening synchronously on one thread.
/// They can be nested to represent a control flow stack.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the duration with additional information.  The arguments provided
/// to matching duration begin and duration end events are combined together in
/// the trace; it is not necessary to repeat them.
pub fn duration_end(context: &TraceCategoryContext, name: &'static CStr, args: &[Arg<'_>]) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_duration_end(name_ref, args);
}

/// AsyncScope maintains state around the context of async events generated via the
/// async_enter! macro.
#[must_use = "emits an end event when dropped, so if dropped immediately creates an essentially \
              zero length duration that should just be an instant instead"]
pub struct AsyncScope {
    // AsyncScope::end uses std::mem::forget to bypass AsyncScope's Drop impl, so if any fields
    // with Drop impls are added, AsyncScope::end should be updated.
    id: Id,
    category: &'static CStr,
    name: &'static CStr,
}
impl AsyncScope {
    /// Starts a new async event scope, generating a begin event now, and ended when the
    /// object is dropped.
    pub fn begin(id: Id, category: &'static CStr, name: &'static CStr, args: &[Arg<'_>]) -> Self {
        async_begin(id, category, name, args);
        Self { id, category, name }
    }

    /// Manually end the async event scope with `args` instead of waiting until the guard is
    /// dropped (which would end the event scope with an empty `args`).
    pub fn end(self, args: &[Arg<'_>]) {
        let Self { id, category, name } = self;
        async_end(id, category, name, args);
        std::mem::forget(self);
    }
}

impl Drop for AsyncScope {
    fn drop(&mut self) {
        // AsyncScope::end uses std::mem::forget to bypass this Drop impl (to avoid emitting
        // extraneous end events), so any logic added to this Drop impl (or any fields added to
        // AsyncScope that have Drop impls) should addressed (if necessary) in AsyncScope::end.
        let Self { id, category, name } = *self;
        async_end(id, category, name, &[]);
    }
}

/// Writes an async event which ends when the current scope exits, or the `end` method is is
/// manually called.
///
/// Async events describe concurrently-scheduled work items that may migrate between threads. They
/// may be nested by sharing id, and are otherwise differentiated by their id.
///
/// 0 to 15 arguments can be associated with the event, each of which is used to annotate the
/// duration with additional information.
pub fn async_enter(
    id: Id,
    category: &'static CStr,
    name: &'static CStr,
    args: &[Arg<'_>],
) -> AsyncScope {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");
    AsyncScope::begin(id, category, name, args)
}

/// Convenience macro for the `async_enter` function, which can be used to trace the duration of a
/// scope containing async code. This macro returns the drop guard, which the caller may then
/// choose to manage.
///
/// Example:
///
/// ```rust
/// {
///     let id = Id::new();
///     let _guard = async_enter!(id, c"foo", c"bar", "x" => 5, "y" => 10);
///     ...
///     ...
///     // event recorded on drop
/// }
/// ```
///
/// is equivalent to
///
/// ```rust
/// {
///     let id = Id::new();
///     let _guard = AsyncScope::begin(id, c"foo", c"bar", &[ArgValue::of("x", 5),
///         ArgValue::of("y", 10)]);
///     ...
///     ...
///     // event recorded on drop
/// }
/// ```
///
/// Calls to async_enter! may be nested.
#[macro_export]
macro_rules! async_enter {
    ($id:expr, $category:expr, $name:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                Some($crate::AsyncScope::begin($id, $category, $name, &[$($crate::ArgValue::of($key, $val)),*]))
            } else {
                None
            }
        }
    }
}

/// Convenience macro for the `async_instant` function, which can be used to emit an async instant
/// event.
///
/// Example:
///
/// ```rust
/// {
///     let id = Id::new();
///     async_instant!(id, c"foo", c"bar", "x" => 5, "y" => 10);
/// }
/// ```
///
/// is equivalent to
///
/// ```rust
/// {
///     let id = Id::new();
///     async_instant(
///         id, c"foo", c"bar",
///         &[ArgValue::of(c"x", 5), ArgValue::of("y", 10)]
///     );
/// }
/// ```
#[macro_export]
macro_rules! async_instant {
    ($id:expr, $category:expr, $name:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::async_instant($id, &context, $name, &[$($crate::ArgValue::of($key, $val)),*]);
            }
        }
    }
}

/// Writes an async begin event. This event must be matched by an async end event with the same
/// id, category, and name. This function is intended to be called through use of the
/// `async_enter!` macro.
///
/// Async events describe concurrent work that may or may not migrate threads, or be otherwise
/// interleaved with other work on the same thread. They can be nested to represent a control
/// flow stack.
///
/// 0 to 15 arguments can be associated with the event, each of which is used to annotate the
/// async event with additional information. Arguments provided in matching async begin and end
/// events are combined together in the trace; it is not necessary to repeat them.
pub fn async_begin(id: Id, category: &'static CStr, name: &'static CStr, args: &[Arg<'_>]) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    if let Some(context) = TraceCategoryContext::acquire(category) {
        let name_ref = context.register_string_literal(name);
        context.write_async_begin(id, name_ref, args);
    }
}

/// Writes an async end event. This event must be associated with a prior async begin event
/// with the same id, category, and name. This function is intended to be called implicitly
/// when the `AsyncScope` object created through use of the `async_enter!` macro is dropped.
///
/// Async events describe concurrent work that may or may not migrate threads, or be otherwise
/// interleaved with other work on the same thread. They can be nested to represent a control
/// flow stack.
///
/// 0 to 15 arguments can be associated with the event, each of which is used to annotate the
/// async event with additional information. Arguments provided in matching async begin and end
/// events are combined together in the trace; it is not necessary to repeat them.
pub fn async_end(id: Id, category: &'static CStr, name: &'static CStr, args: &[Arg<'_>]) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    if let Some(context) = TraceCategoryContext::acquire(category) {
        let name_ref = context.register_string_literal(name);
        context.write_async_end(id, name_ref, args);
    }
}

/// Writes an async instant event with the specified id.
///
/// Asynchronous events describe work that is happening asynchronously and that
/// may span multiple threads.  Asynchronous events do not nest.  The id serves
/// to correlate the progress of distinct asynchronous operations that share
/// the same category and name within the same process.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the asynchronous operation with additional information.  The
/// arguments provided to matching async begin, async instant, and async end
/// events are combined together in the trace; it is not necessary to repeat them.
pub fn async_instant(
    id: Id,
    context: &TraceCategoryContext,
    name: &'static CStr,
    args: &[Arg<'_>],
) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_async_instant(id, name_ref, args);
}

#[macro_export]
macro_rules! blob {
    ($category:expr, $name:expr, $bytes:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::blob_fn(&context, $name, $bytes, &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    }
}
pub fn blob_fn(
    context: &TraceCategoryContext,
    name: &'static CStr,
    bytes: &[u8],
    args: &[Arg<'_>],
) {
    let name_ref = context.register_string_literal(name);
    context.write_blob(name_ref, bytes, args);
}

/// Convenience macro for the `flow_begin` function.
///
/// Example:
///
/// ```rust
/// let flow_id = 1234;
/// flow_begin!(c"foo", c"bar", flow_id, "x" => 5, "y" => "boo");
/// ```
///
/// ```rust
/// const FOO: &'static CStr = c"foo";
/// const BAR: &'static CStr = c"bar";
/// flow_begin!(c"foo", c"bar", flow_id);
/// ```
#[macro_export]
macro_rules! flow_begin {
    ($category:expr, $name:expr, $flow_id:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::flow_begin(&context, $name, $flow_id,
                                   &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    }
}

/// Convenience macro for the `flow_step` function.
///
/// Example:
///
/// ```rust
/// let flow_id = 1234;
/// flow_step!(c"foo", c"bar", flow_id, "x" => 5, "y" => "boo");
/// ```
///
/// ```rust
/// const FOO: &'static CStr = c"foo";
/// const BAR: &'static CStr = c"bar";
/// flow_step!(c"foo", c"bar", flow_id);
/// ```
#[macro_export]
macro_rules! flow_step {
    ($category:expr, $name:expr, $flow_id:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::flow_step(&context, $name, $flow_id,
                                  &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    }
}

/// Convenience macro for the `flow_end` function.
///
/// Example:
///
/// ```rust
/// let flow_id = 1234;
/// flow_end!(c"foo", c"bar", flow_id, "x" => 5, "y" => "boo");
/// ```
///
/// ```rust
/// const FOO: &'static CStr = c"foo";
/// const BAR: &'static CStr = c"bar";
/// flow_end!(c"foo", c"bar", flow_id);
/// ```
#[macro_export]
macro_rules! flow_end {
    ($category:expr, $name:expr, $flow_id:expr $(, $key:expr => $val:expr)*) => {
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            if let Some(context) = $crate::TraceCategoryContext::acquire_cached($category, &CACHE) {
                $crate::flow_end(&context, $name, $flow_id,
                                 &[$($crate::ArgValue::of($key, $val)),*])
            }
        }
    }
}

/// Writes a flow begin event with the specified id.
/// This event may be followed by flow steps events and must be matched by
/// a flow end event with the same category, name, and id.
///
/// Flow events describe control flow handoffs between threads or across processes.
/// They are typically represented as arrows in a visualizer.  Flow arrows are
/// from the end of the duration event which encloses the beginning of the flow
/// to the beginning of the duration event which encloses the next step or the
/// end of the flow.  The id serves to correlate flows which share the same
/// category and name across processes.
///
/// This event must be enclosed in a duration event which represents where
/// the flow handoff occurs.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the flow with additional information.  The arguments provided
/// to matching flow begin, flow step, and flow end events are combined together
/// in the trace; it is not necessary to repeat them.
pub fn flow_begin(
    context: &TraceCategoryContext,
    name: &'static CStr,
    flow_id: Id,
    args: &[Arg<'_>],
) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_flow_begin(name_ref, flow_id, args);
}

/// Writes a flow end event with the specified id.
///
/// Flow events describe control flow handoffs between threads or across processes.
/// They are typically represented as arrows in a visualizer.  Flow arrows are
/// from the end of the duration event which encloses the beginning of the flow
/// to the beginning of the duration event which encloses the next step or the
/// end of the flow.  The id serves to correlate flows which share the same
/// category and name across processes.
///
/// This event must be enclosed in a duration event which represents where
/// the flow handoff occurs.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the flow with additional information.  The arguments provided
/// to matching flow begin, flow step, and flow end events are combined together
/// in the trace; it is not necessary to repeat them.
pub fn flow_end(
    context: &TraceCategoryContext,
    name: &'static CStr,
    flow_id: Id,
    args: &[Arg<'_>],
) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_flow_end(name_ref, flow_id, args);
}

/// Writes a flow step event with the specified id.
///
/// Flow events describe control flow handoffs between threads or across processes.
/// They are typically represented as arrows in a visualizer.  Flow arrows are
/// from the end of the duration event which encloses the beginning of the flow
/// to the beginning of the duration event which encloses the next step or the
/// end of the flow.  The id serves to correlate flows which share the same
/// category and name across processes.
///
/// This event must be enclosed in a duration event which represents where
/// the flow handoff occurs.
///
/// 0 to 15 arguments can be associated with the event, each of which is used
/// to annotate the flow with additional information.  The arguments provided
/// to matching flow begin, flow step, and flow end events are combined together
/// in the trace; it is not necessary to repeat them.
pub fn flow_step(
    context: &TraceCategoryContext,
    name: &'static CStr,
    flow_id: Id,
    args: &[Arg<'_>],
) {
    assert!(args.len() <= 15, "no more than 15 trace arguments are supported");

    let name_ref = context.register_string_literal(name);
    context.write_flow_step(name_ref, flow_id, args);
}

// translated from trace-engine/types.h for inlining
const fn trace_make_empty_string_ref() -> sys::trace_string_ref_t {
    sys::trace_string_ref_t {
        encoded_value: sys::TRACE_ENCODED_STRING_REF_EMPTY,
        inline_string: ptr::null(),
    }
}

#[inline]
fn trim_to_last_char_boundary(string: &str, max_len: usize) -> &[u8] {
    let mut len = string.len();
    if string.len() > max_len {
        // Trim to the last unicode character that fits within the max length.
        // We search for the last character boundary that is immediately followed
        // by another character boundary (end followed by beginning).
        len = max_len;
        while len > 0 {
            if string.is_char_boundary(len - 1) && string.is_char_boundary(len) {
                break;
            }
            len -= 1;
        }
    }
    &string.as_bytes()[0..len]
}

// translated from trace-engine/types.h for inlining
// The resulting `trace_string_ref_t` only lives as long as the input `string`.
#[inline]
fn trace_make_inline_string_ref(string: &str) -> sys::trace_string_ref_t {
    let len = string.len() as u32;
    if len == 0 {
        return trace_make_empty_string_ref();
    }

    let string =
        trim_to_last_char_boundary(string, sys::TRACE_ENCODED_STRING_REF_MAX_LENGTH as usize);

    sys::trace_string_ref_t {
        encoded_value: sys::TRACE_ENCODED_STRING_REF_INLINE_FLAG | len,
        inline_string: string.as_ptr() as *const libc::c_char,
    }
}

/// RAII wrapper for a trace context for a specific category.
pub struct TraceCategoryContext {
    raw: *const sys::trace_context_t,
    category_ref: sys::trace_string_ref_t,
}

impl TraceCategoryContext {
    #[inline]
    pub fn acquire_cached(
        category: &'static CStr,
        site: &sys::trace_site_t,
    ) -> Option<TraceCategoryContext> {
        unsafe {
            // SAFETY: The call to `trace_acquire_context_for_category_cached` is sound because
            // all arguments are live and non-null. If this function returns a non-null
            // pointer then it also guarantees that `category_ref` will have been initialized.
            // Internally, it uses relaxed atomic semantics to load and store site.
            let mut category_ref = mem::MaybeUninit::<sys::trace_string_ref_t>::uninit();
            let raw = sys::trace_acquire_context_for_category_cached(
                category.as_ptr(),
                site.as_ptr(),
                category_ref.as_mut_ptr(),
            );
            if raw != ptr::null() {
                Some(TraceCategoryContext { raw, category_ref: category_ref.assume_init() })
            } else {
                None
            }
        }
    }

    pub fn acquire(category: &'static CStr) -> Option<TraceCategoryContext> {
        unsafe {
            let mut category_ref = mem::MaybeUninit::<sys::trace_string_ref_t>::uninit();
            let raw = sys::trace_acquire_context_for_category(
                category.as_ptr(),
                category_ref.as_mut_ptr(),
            );
            if raw != ptr::null() {
                Some(TraceCategoryContext { raw, category_ref: category_ref.assume_init() })
            } else {
                None
            }
        }
    }

    #[inline]
    pub fn register_string_literal(&self, name: &'static CStr) -> sys::trace_string_ref_t {
        unsafe {
            let mut name_ref = mem::MaybeUninit::<sys::trace_string_ref_t>::uninit();
            sys::trace_context_register_string_literal(
                self.raw,
                name.as_ptr(),
                name_ref.as_mut_ptr(),
            );
            name_ref.assume_init()
        }
    }

    #[inline]
    fn register_current_thread(&self) -> sys::trace_thread_ref_t {
        unsafe {
            let mut thread_ref = mem::MaybeUninit::<sys::trace_thread_ref_t>::uninit();
            sys::trace_context_register_current_thread(self.raw, thread_ref.as_mut_ptr());
            thread_ref.assume_init()
        }
    }

    #[inline]
    pub fn write_instant(&self, name_ref: sys::trace_string_ref_t, scope: Scope, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_instant_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                scope.into_raw(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_instant_with_inline_name(&self, name: &str, scope: Scope, args: &[Arg<'_>]) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_instant(name_ref, scope, args)
    }

    fn write_counter(&self, name_ref: sys::trace_string_ref_t, counter_id: u64, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_counter_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                counter_id,
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_counter_with_inline_name(&self, name: &str, counter_id: u64, args: &[Arg<'_>]) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_counter(name_ref, counter_id, args);
    }

    fn write_duration(
        &self,
        name_ref: sys::trace_string_ref_t,
        start_time: zx::BootTicks,
        args: &[Arg<'_>],
    ) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_duration_event_record(
                self.raw,
                start_time.into_raw(),
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_duration_with_inline_name(
        &self,
        name: &str,
        start_time: zx::BootTicks,
        args: &[Arg<'_>],
    ) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_duration(name_ref, start_time, args);
    }

    fn write_duration_begin(&self, name_ref: sys::trace_string_ref_t, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_duration_begin_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_duration_begin_with_inline_name(&self, name: &str, args: &[Arg<'_>]) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_duration_begin(name_ref, args);
    }

    fn write_duration_end(&self, name_ref: sys::trace_string_ref_t, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_duration_end_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_duration_end_with_inline_name(&self, name: &str, args: &[Arg<'_>]) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_duration_end(name_ref, args);
    }

    fn write_async_begin(&self, id: Id, name_ref: sys::trace_string_ref_t, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_async_begin_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                id.into(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_async_begin_with_inline_name(&self, id: Id, name: &str, args: &[Arg<'_>]) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_async_begin(id, name_ref, args);
    }

    fn write_async_end(&self, id: Id, name_ref: sys::trace_string_ref_t, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_async_end_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                id.into(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    pub fn write_async_end_with_inline_name(&self, id: Id, name: &str, args: &[Arg<'_>]) {
        let name_ref = trace_make_inline_string_ref(name);
        self.write_async_end(id, name_ref, args);
    }

    fn write_async_instant(&self, id: Id, name_ref: sys::trace_string_ref_t, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_async_instant_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                id.into(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    fn write_blob(&self, name_ref: sys::trace_string_ref_t, bytes: &[u8], args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_blob_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                bytes.as_ptr() as *const core::ffi::c_void,
                bytes.len(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    fn write_flow_begin(&self, name_ref: sys::trace_string_ref_t, flow_id: Id, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_flow_begin_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                flow_id.into(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    fn write_flow_end(&self, name_ref: sys::trace_string_ref_t, flow_id: Id, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_flow_end_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                flow_id.into(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }

    fn write_flow_step(&self, name_ref: sys::trace_string_ref_t, flow_id: Id, args: &[Arg<'_>]) {
        let ticks = zx::BootTicks::get();
        let thread_ref = self.register_current_thread();
        unsafe {
            sys::trace_context_write_flow_step_event_record(
                self.raw,
                ticks.into_raw(),
                &thread_ref,
                &self.category_ref,
                &name_ref,
                flow_id.into(),
                args.as_ptr() as *const sys::trace_arg_t,
                args.len(),
            );
        }
    }
}

impl std::ops::Drop for TraceCategoryContext {
    fn drop(&mut self) {
        unsafe {
            sys::trace_release_context(self.raw);
        }
    }
}

/// RAII wrapper for trace contexts without a specific associated category.
pub struct Context {
    context: *const sys::trace_context_t,
}

impl Context {
    #[inline]
    pub fn acquire() -> Option<Self> {
        let context = unsafe { sys::trace_acquire_context() };
        if context.is_null() {
            None
        } else {
            Some(Self { context })
        }
    }

    #[inline]
    pub fn register_string_literal(&self, s: &'static CStr) -> sys::trace_string_ref_t {
        unsafe {
            let mut s_ref = mem::MaybeUninit::<sys::trace_string_ref_t>::uninit();
            sys::trace_context_register_string_literal(
                self.context,
                s.as_ptr(),
                s_ref.as_mut_ptr(),
            );
            s_ref.assume_init()
        }
    }

    pub fn write_blob_record(
        &self,
        type_: sys::trace_blob_type_t,
        name_ref: &sys::trace_string_ref_t,
        data: &[u8],
    ) {
        unsafe {
            sys::trace_context_write_blob_record(
                self.context,
                type_,
                name_ref as *const sys::trace_string_ref_t,
                data.as_ptr() as *const libc::c_void,
                data.len(),
            );
        }
    }
}

impl std::ops::Drop for Context {
    fn drop(&mut self) {
        unsafe { sys::trace_release_context(self.context) }
    }
}

pub struct ProlongedContext {
    context: *const sys::trace_prolonged_context_t,
}

impl ProlongedContext {
    pub fn acquire() -> Option<Self> {
        let context = unsafe { sys::trace_acquire_prolonged_context() };
        if context.is_null() {
            None
        } else {
            Some(Self { context })
        }
    }
}

impl Drop for ProlongedContext {
    fn drop(&mut self) {
        unsafe { sys::trace_release_prolonged_context(self.context) }
    }
}

unsafe impl Send for ProlongedContext {}

mod sys {
    #![allow(non_camel_case_types, unused)]
    use zx::sys::{zx_handle_t, zx_koid_t, zx_obj_type_t, zx_status_t, zx_ticks_t};

    pub type trace_ticks_t = zx_ticks_t;
    pub type trace_counter_id_t = u64;
    pub type trace_async_id_t = u64;
    pub type trace_flow_id_t = u64;
    pub type trace_thread_state_t = u32;
    pub type trace_cpu_number_t = u32;
    pub type trace_string_index_t = u32;
    pub type trace_thread_index_t = u32;
    pub type trace_context_t = libc::c_void;
    pub type trace_prolonged_context_t = libc::c_void;

    pub type trace_encoded_string_ref_t = u32;
    pub const TRACE_ENCODED_STRING_REF_EMPTY: trace_encoded_string_ref_t = 0;
    pub const TRACE_ENCODED_STRING_REF_INLINE_FLAG: trace_encoded_string_ref_t = 0x8000;
    pub const TRACE_ENCODED_STRING_REF_LENGTH_MASK: trace_encoded_string_ref_t = 0x7fff;
    pub const TRACE_ENCODED_STRING_REF_MAX_LENGTH: trace_encoded_string_ref_t = 32000;
    pub const TRACE_ENCODED_STRING_REF_MIN_INDEX: trace_encoded_string_ref_t = 0x1;
    pub const TRACE_ENCODED_STRING_REF_MAX_INDEX: trace_encoded_string_ref_t = 0x7fff;

    pub type trace_encoded_thread_ref_t = u32;
    pub const TRACE_ENCODED_THREAD_REF_INLINE: trace_encoded_thread_ref_t = 0;
    pub const TRACE_ENCODED_THREAD_MIN_INDEX: trace_encoded_thread_ref_t = 0x01;
    pub const TRACE_ENCODED_THREAD_MAX_INDEX: trace_encoded_thread_ref_t = 0xff;

    pub type trace_state_t = libc::c_int;
    pub const TRACE_STOPPED: trace_state_t = 0;
    pub const TRACE_STARTED: trace_state_t = 1;
    pub const TRACE_STOPPING: trace_state_t = 2;

    pub type trace_scope_t = libc::c_int;
    pub const TRACE_SCOPE_THREAD: trace_scope_t = 0;
    pub const TRACE_SCOPE_PROCESS: trace_scope_t = 1;
    pub const TRACE_SCOPE_GLOBAL: trace_scope_t = 2;

    pub type trace_blob_type_t = libc::c_int;
    pub const TRACE_BLOB_TYPE_DATA: trace_blob_type_t = 1;
    pub const TRACE_BLOB_TYPE_LAST_BRANCH: trace_blob_type_t = 2;
    pub const TRACE_BLOB_TYPE_PERFETTO: trace_blob_type_t = 3;

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct trace_string_ref_t {
        pub encoded_value: trace_encoded_string_ref_t,
        pub inline_string: *const libc::c_char,
    }

    // trace_site_t is an opaque type that trace-engine uses per callsite to cache if the trace
    // point is enabled. Internally, it is a 8 byte allocation accessed with relaxed atomic
    // semantics.
    pub type trace_site_t = std::sync::atomic::AtomicU64;

    // A trace_string_ref_t object is created from a string slice.
    // The trace_string_ref_t object is contained inside an Arg object.
    // whose lifetime matches the string slice to ensure that the memory
    // cannot be de-allocated during the trace.
    //
    // trace_string_ref_t is safe for Send + Sync because the memory that
    // inline_string points to is guaranteed to be valid throughout the trace.
    //
    // For more information, see the ArgValue implementation for &str in this file.
    unsafe impl Send for trace_string_ref_t {}
    unsafe impl Sync for trace_string_ref_t {}

    #[repr(C)]
    pub struct trace_thread_ref_t {
        pub encoded_value: trace_encoded_thread_ref_t,
        pub inline_process_koid: zx_koid_t,
        pub inline_thread_koid: zx_koid_t,
    }

    #[repr(C)]
    pub struct trace_arg_t {
        pub name_ref: trace_string_ref_t,
        pub value: trace_arg_value_t,
    }

    #[repr(C)]
    pub union trace_arg_union_t {
        pub int32_value: i32,
        pub uint32_value: u32,
        pub int64_value: i64,
        pub uint64_value: u64,
        pub double_value: libc::c_double,
        pub string_value_ref: trace_string_ref_t,
        pub pointer_value: libc::uintptr_t,
        pub koid_value: zx_koid_t,
        pub bool_value: bool,
        pub reserved_for_future_expansion: [libc::uintptr_t; 2],
    }

    pub type trace_arg_type_t = libc::c_int;
    pub const TRACE_ARG_NULL: trace_arg_type_t = 0;
    pub const TRACE_ARG_INT32: trace_arg_type_t = 1;
    pub const TRACE_ARG_UINT32: trace_arg_type_t = 2;
    pub const TRACE_ARG_INT64: trace_arg_type_t = 3;
    pub const TRACE_ARG_UINT64: trace_arg_type_t = 4;
    pub const TRACE_ARG_DOUBLE: trace_arg_type_t = 5;
    pub const TRACE_ARG_STRING: trace_arg_type_t = 6;
    pub const TRACE_ARG_POINTER: trace_arg_type_t = 7;
    pub const TRACE_ARG_KOID: trace_arg_type_t = 8;
    pub const TRACE_ARG_BOOL: trace_arg_type_t = 9;

    #[repr(C)]
    pub struct trace_arg_value_t {
        pub type_: trace_arg_type_t,
        pub value: trace_arg_union_t,
    }

    #[repr(C)]
    pub struct trace_handler_ops_t {
        pub is_category_enabled:
            unsafe fn(handler: *const trace_handler_t, category: *const libc::c_char) -> bool,
        pub trace_started: unsafe fn(handler: *const trace_handler_t),
        pub trace_stopped: unsafe fn(
            handler: *const trace_handler_t,
            async_ptr: *const (), //async_t,
            disposition: zx_status_t,
            buffer_bytes_written: libc::size_t,
        ),
        pub buffer_overflow: unsafe fn(handler: *const trace_handler_t),
    }

    #[repr(C)]
    pub struct trace_handler_t {
        pub ops: *const trace_handler_ops_t,
    }

    // From libtrace-engine.so
    extern "C" {
        // From trace-engine/context.h

        pub fn trace_context_is_category_enabled(
            context: *const trace_context_t,
            category_literal: *const libc::c_char,
        ) -> bool;

        pub fn trace_context_register_string_copy(
            context: *const trace_context_t,
            string: *const libc::c_char,
            length: libc::size_t,
            out_ref: *mut trace_string_ref_t,
        );

        pub fn trace_context_register_string_literal(
            context: *const trace_context_t,
            string_literal: *const libc::c_char,
            out_ref: *mut trace_string_ref_t,
        );

        pub fn trace_context_register_category_literal(
            context: *const trace_context_t,
            category_literal: *const libc::c_char,
            out_ref: *mut trace_string_ref_t,
        ) -> bool;

        pub fn trace_context_register_current_thread(
            context: *const trace_context_t,
            out_ref: *mut trace_thread_ref_t,
        );

        pub fn trace_context_register_thread(
            context: *const trace_context_t,
            process_koid: zx_koid_t,
            thread_koid: zx_koid_t,
            out_ref: *mut trace_thread_ref_t,
        );

        pub fn trace_context_write_kernel_object_record(
            context: *const trace_context_t,
            koid: zx_koid_t,
            type_: zx_obj_type_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_kernel_object_record_for_handle(
            context: *const trace_context_t,
            handle: zx_handle_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_process_info_record(
            context: *const trace_context_t,
            process_koid: zx_koid_t,
            process_name_ref: *const trace_string_ref_t,
        );

        pub fn trace_context_write_thread_info_record(
            context: *const trace_context_t,
            process_koid: zx_koid_t,
            thread_koid: zx_koid_t,
            thread_name_ref: *const trace_string_ref_t,
        );

        pub fn trace_context_write_context_switch_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            cpu_number: trace_cpu_number_t,
            outgoing_thread_state: trace_thread_state_t,
            outgoing_thread_ref: *const trace_thread_ref_t,
            incoming_thread_ref: *const trace_thread_ref_t,
        );

        pub fn trace_context_write_log_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            log_message: *const libc::c_char,
            log_message_length: libc::size_t,
        );

        pub fn trace_context_write_instant_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            scope: trace_scope_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_send_alert(context: *const trace_context_t, name: *const libc::c_char);

        pub fn trace_context_write_counter_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            counter_id: trace_counter_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_duration_event_record(
            context: *const trace_context_t,
            start_time: trace_ticks_t,
            end_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_blob_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            blob: *const libc::c_void,
            blob_size: libc::size_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_duration_begin_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_duration_end_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_async_begin_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            async_id: trace_async_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_async_instant_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            async_id: trace_async_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_async_end_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            async_id: trace_async_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_flow_begin_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            flow_id: trace_flow_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_flow_step_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            flow_id: trace_flow_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_flow_end_event_record(
            context: *const trace_context_t,
            event_time: trace_ticks_t,
            thread_ref: *const trace_thread_ref_t,
            category_ref: *const trace_string_ref_t,
            name_ref: *const trace_string_ref_t,
            flow_id: trace_flow_id_t,
            args: *const trace_arg_t,
            num_args: libc::size_t,
        );

        pub fn trace_context_write_initialization_record(
            context: *const trace_context_t,
            ticks_per_second: u64,
        );

        pub fn trace_context_write_string_record(
            context: *const trace_context_t,
            index: trace_string_index_t,
            string: *const libc::c_char,
            length: libc::size_t,
        );

        pub fn trace_context_write_thread_record(
            context: *const trace_context_t,
            index: trace_thread_index_t,
            procss_koid: zx_koid_t,
            thread_koid: zx_koid_t,
        );

        pub fn trace_context_write_blob_record(
            context: *const trace_context_t,
            type_: trace_blob_type_t,
            name_ref: *const trace_string_ref_t,
            data: *const libc::c_void,
            size: libc::size_t,
        );

        pub fn trace_context_alloc_record(
            context: *const trace_context_t,
            num_bytes: libc::size_t,
        ) -> *const libc::c_void;

        // From trace-engine/handler.h
        /*
        pub fn trace_start_engine(
            async_ptr: *const async_t,
            handler: *const trace_handler_t,
            buffer: *const (),
            buffer_num_bytes: libc::size_t) -> zx_status_t;
            */

        pub fn trace_stop_engine(disposition: zx_status_t) -> zx_status_t;

        // From trace-engine/instrumentation.h

        pub fn trace_generate_nonce() -> u64;

        pub fn trace_state() -> trace_state_t;

        pub fn trace_is_category_enabled(category_literal: *const libc::c_char) -> bool;

        pub fn trace_acquire_context() -> *const trace_context_t;

        pub fn trace_acquire_context_for_category(
            category_literal: *const libc::c_char,
            out_ref: *mut trace_string_ref_t,
        ) -> *const trace_context_t;

        pub fn trace_acquire_context_for_category_cached(
            category_literal: *const libc::c_char,
            trace_site: *const u64,
            out_ref: *mut trace_string_ref_t,
        ) -> *const trace_context_t;

        pub fn trace_release_context(context: *const trace_context_t);

        pub fn trace_acquire_prolonged_context() -> *const trace_prolonged_context_t;

        pub fn trace_release_prolonged_context(context: *const trace_prolonged_context_t);

        pub fn trace_register_observer(event: zx_handle_t) -> zx_status_t;

        pub fn trace_unregister_observer(event: zx_handle_t) -> zx_status_t;

        pub fn trace_notify_observer_updated(event: zx_handle_t);
    }
}

/// Arguments for `TraceFuture` and `TraceFutureExt`. Use `trace_future_args!` to construct this
/// object.
pub struct TraceFutureArgs<'a> {
    pub category: &'static CStr,
    pub name: &'static CStr,

    /// `TraceFuture::new` and `trace_future_args!` both check if the trace category is enabled. The
    /// trace context is acquired in `trace_future_args!` and is passed to `TraceFuture::new` to
    /// avoid acquiring it twice.
    pub context: Option<TraceCategoryContext>,

    /// The trace arguments to appear in every duration event written by the `TraceFuture`. `args`
    /// should be empty if `context` is `None`.
    pub args: Vec<Arg<'a>>,

    /// The flow id to use in the flow events that connect the duration events together. A flow id
    /// will be constructed with `Id::new()` if not provided.
    pub flow_id: Option<Id>,

    /// Use `trace_future_args!` to construct this object.
    pub _use_trace_future_args: (),
}

#[doc(hidden)]
#[macro_export]
macro_rules! __impl_trace_future_args {
    ($category:expr, $name:expr, $flow_id:expr $(, $key:expr => $val:expr)*) => {{
        {
            static CACHE: $crate::trace_site_t = $crate::trace_site_t::new(0);
            let context = $crate::TraceCategoryContext::acquire_cached($category, &CACHE);
            let args = if context.is_some() {
                vec![$($crate::ArgValue::of($key, $val)),*]
            } else {
                vec![]
            };
            $crate::TraceFutureArgs {
                category: $category,
                name: $name,
                context: context,
                args: args,
                flow_id: $flow_id,
                _use_trace_future_args: (),
            }
        }
    }};
}

/// Macro for constructing `TraceFutureArgs`. The trace arguments won't be constructed if the
/// category is not enabled. If the category becomes enabled while the `TraceFuture` is still alive
/// then the duration events will still be written but without the trace arguments.
///
/// Example:
///
/// ```
/// async move {
///     ....
/// }.trace(trace_future_args!(c"category", c"name", "x" => 5, "y" => 10)).await;
/// ```
#[macro_export]
macro_rules! trace_future_args {
    ($category:expr, $name:expr $(, $key:expr => $val:expr)*) => {
        $crate::__impl_trace_future_args!($category, $name, None $(,$key => $val)*)
    };
    ($category:expr, $name:expr, $flow_id:expr $(, $key:expr => $val:expr)*) => {
        $crate::__impl_trace_future_args!($category, $name, Some($flow_id) $(,$key => $val)*)
    };
}

/// Extension trait for tracing futures.
pub trait TraceFutureExt: Future + Sized {
    /// Wraps a `Future` in a `TraceFuture`.
    ///
    /// Example:
    ///
    /// ```rust
    /// future.trace(trace_future_args!(c"category", c"name")).await;
    /// ```
    ///
    /// Which is equivalent to:
    ///
    /// ```rust
    /// TraceFuture::new(trace_future_args!(c"category", c"name"), future).await;
    /// ```
    fn trace<'a>(self, args: TraceFutureArgs<'a>) -> TraceFuture<'a, Self> {
        TraceFuture::new(args, self)
    }
}

impl<T: Future + Sized> TraceFutureExt for T {}

/// Wraps a `Future` and writes duration events when the future is created, dropped, and every time
/// it's polled. The duration events are connected by flow events.
#[pin_project(PinnedDrop)]
pub struct TraceFuture<'a, Fut: Future> {
    category: &'static CStr,
    name: &'static CStr,
    args: Vec<Arg<'a>>,
    flow_id: Option<Id>,
    #[pin]
    future: Fut,
}

impl<'a, Fut: Future> TraceFuture<'a, Fut> {
    pub fn new(args: TraceFutureArgs<'a>, future: Fut) -> Self {
        debug_assert!(
            args.context.is_some() || args.args.is_empty(),
            "There should not be any trace arguments when the category is disabled"
        );
        let mut this = Self {
            category: args.category,
            name: args.name,
            args: args.args,
            flow_id: args.flow_id,
            future: future,
        };
        if let Some(context) = args.context {
            this.trace_create(context);
        }
        this
    }

    #[cold]
    fn trace_create(&mut self, context: TraceCategoryContext) {
        let name_ref = context.register_string_literal(self.name);
        let flow_id = self.flow_id.get_or_insert_with(Id::new);
        let duration_start = zx::BootTicks::get();
        context.write_flow_begin(name_ref, *flow_id, &[]);
        self.args.push(ArgValue::of("state", "created"));
        context.write_duration(name_ref, duration_start, &self.args);
        self.args.pop();
    }

    #[cold]
    fn trace_poll(
        self: Pin<&mut Self>,
        context: TraceCategoryContext,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Fut::Output> {
        let this = self.project();
        let name_ref = context.register_string_literal(this.name);
        let flow_id = this.flow_id.get_or_insert_with(Id::new);
        let duration_start = zx::BootTicks::get();
        context.write_flow_step(name_ref, *flow_id, &[]);
        let result = this.future.poll(cx);
        let result_str: &'static str = if result.is_pending() { "pending" } else { "ready" };
        this.args.push(ArgValue::of("state", result_str));
        context.write_duration(name_ref, duration_start, &this.args);
        this.args.pop();
        result
    }

    #[cold]
    fn trace_drop(self: Pin<&mut Self>, context: TraceCategoryContext) {
        let this = self.project();
        let name_ref = context.register_string_literal(this.name);
        let flow_id = this.flow_id.get_or_insert_with(Id::new);
        let duration_start = zx::BootTicks::get();
        context.write_flow_end(name_ref, *flow_id, &[]);
        this.args.push(ArgValue::of("state", "dropped"));
        context.write_duration(name_ref, duration_start, &this.args);
        this.args.pop();
    }
}

impl<Fut: Future> Future for TraceFuture<'_, Fut> {
    type Output = Fut::Output;
    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Fut::Output> {
        if let Some(context) = TraceCategoryContext::acquire(self.as_ref().get_ref().category) {
            self.trace_poll(context, cx)
        } else {
            self.project().future.poll(cx)
        }
    }
}

#[pin_project::pinned_drop]
impl<Fut: Future> PinnedDrop for TraceFuture<'_, Fut> {
    fn drop(self: Pin<&mut Self>) {
        if let Some(context) = TraceCategoryContext::acquire(self.as_ref().get_ref().category) {
            self.trace_drop(context);
        }
    }
}

#[cfg(test)]
mod test {
    use super::{trim_to_last_char_boundary, Id};

    #[test]
    fn trim_to_last_char_boundary_trims_to_last_character_boundary() {
        assert_eq!(b"x", trim_to_last_char_boundary("x", 5));
        assert_eq!(b"x", trim_to_last_char_boundary("x", 1));
        assert_eq!(b"", trim_to_last_char_boundary("x", 0));
        assert_eq!(b"xxxxx", trim_to_last_char_boundary("xxxxx", 6));
        assert_eq!(b"xxxxx", trim_to_last_char_boundary("xxxxx", 5));
        assert_eq!(b"xxxx", trim_to_last_char_boundary("xxxxx", 4));

        assert_eq!("💩".as_bytes(), trim_to_last_char_boundary("💩", 5));
        assert_eq!("💩".as_bytes(), trim_to_last_char_boundary("💩", 4));
        assert_eq!(b"", trim_to_last_char_boundary("💩", 3));
    }

    // Here, we're looking to make sure that successive calls to the function generate distinct
    // values. How those values are distinct is not particularly meaningful; the current
    // implementation yields sequential values, but that's not a behavior to rely on.
    #[test]
    fn test_id_new() {
        assert_ne!(Id::new(), Id::new());
    }
}