tracepoint_decode 0.4.1

Rust API for decoding tracepoints
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use core::fmt;
use core::fmt::Write;
#[cfg(feature = "rustc_1_77")]
use core::net;
use core::str;

use eventheader_types::Guid;

use crate::charconv;
use crate::filters::*;
use crate::EventHeaderItemInfo;
use crate::PerfConvertOptions;
use crate::PerfTextEncoding;

/// If ch32 is valid, returns the char. Otherwise, returns the replacement character.
#[inline]
fn char_from_u32(ch32: u32) -> char {
    return char::from_u32(ch32).unwrap_or(char::REPLACEMENT_CHARACTER);
}

#[cfg(windows)]
pub mod date_time {
    #[repr(C)]
    pub struct DateTime {
        year: u16,
        month_of_year: u16,
        day_of_week: u16,
        day_of_month: u16,
        hour: u16,
        minute: u16,
        second: u16,
        milliseconds: u16,
    }

    impl DateTime {
        pub fn new(value: i64) -> Self {
            let mut this = Self {
                year: 0,
                month_of_year: 0,
                day_of_week: 0,
                day_of_month: 0,
                hour: 0,
                minute: 0,
                second: 0,
                milliseconds: 0,
            };

            if (-11644473600..=910692730085).contains(&value) {
                let ft = (value + 11644473600) * 10000000;
                if 0 == unsafe { FileTimeToSystemTime(&ft, &mut this) } {
                    this.month_of_year = 0;
                }
            }

            return this;
        }

        pub const fn valid(&self) -> bool {
            return self.month_of_year != 0;
        }

        pub const fn year(&self) -> u32 {
            return self.year as u32;
        }

        pub const fn month_of_year(&self) -> u8 {
            return self.month_of_year as u8;
        }

        pub const fn day_of_month(&self) -> u8 {
            return self.day_of_month as u8;
        }

        pub const fn hour(&self) -> u8 {
            return self.hour as u8;
        }

        pub const fn minute(&self) -> u8 {
            return self.minute as u8;
        }

        pub const fn second(&self) -> u8 {
            return self.second as u8;
        }
    }

    extern "system" {
        fn FileTimeToSystemTime(file_time: *const i64, system_time: *mut DateTime) -> i32;
    }
}

#[cfg(unix)]
pub mod date_time {
    pub struct DateTime {
        tm: libc::tm,
    }

    impl DateTime {
        pub fn new(value: i64) -> Self {
            let mut this = Self {
                tm: unsafe { core::mem::zeroed() },
            };

            if unsafe { core::ptr::null() == libc::gmtime_r(&value, &mut this.tm) } {
                this.tm.tm_mday = 0;
            }

            return this;
        }

        pub const fn valid(&self) -> bool {
            return self.tm.tm_mday != 0;
        }

        pub const fn year(&self) -> u32 {
            return self.tm.tm_year.wrapping_add(1900) as u32;
        }

        pub const fn month_of_year(&self) -> u8 {
            return self.tm.tm_mon as u8 + 1;
        }

        pub const fn day_of_month(&self) -> u8 {
            return self.tm.tm_mday as u8;
        }

        pub const fn hour(&self) -> u8 {
            return self.tm.tm_hour as u8;
        }

        pub const fn minute(&self) -> u8 {
            return self.tm.tm_min as u8;
        }

        pub const fn second(&self) -> u8 {
            return self.tm.tm_sec as u8;
        }
    }
}

#[cfg(not(any(windows, unix)))]
pub mod date_time {
    pub struct DateTime {}

    impl DateTime {
        pub const fn new(_value: i64) -> Self {
            return Self {};
        }

        pub const fn valid(&self) -> bool {
            return false;
        }

        pub const fn year(&self) -> u32 {
            return 0;
        }

        pub const fn month_of_year(&self) -> u8 {
            return 0;
        }

        pub const fn day_of_month(&self) -> u8 {
            return 0;
        }

        pub const fn hour(&self) -> u8 {
            return 0;
        }

        pub const fn minute(&self) -> u8 {
            return 0;
        }

        pub const fn second(&self) -> u8 {
            return 0;
        }
    }
}

/// Writes JSON values to a `fmt::Write` destination.
pub struct JsonWriter<'wri, W: fmt::Write + ?Sized>(ValueWriter<'wri, W>);

impl<'wri, W: fmt::Write + ?Sized> JsonWriter<'wri, W> {
    /// Creates a new `JsonWriter` with the specified destination and options.
    /// `json_comma` specifies whether a comma should be written before the first JSON item.
    pub fn new(
        writer: &'wri mut W,
        options: PerfConvertOptions,
        json_comma: bool,
    ) -> JsonWriter<'wri, W> {
        return JsonWriter(ValueWriter {
            dest: WriteFilter::new(writer),
            options,
            json_comma,
            json_space: json_comma && options.has_flag(PerfConvertOptions::Space),
        });
    }

    /// Returns true if a comma will need to be written before the next JSON item.
    ///
    /// This is true after `}`, `]`, and after writing a value or member.
    ///
    /// This is false after `{`, `[`, `json_newline_before_value`, and `json_property_name`.
    pub fn comma(&self) -> bool {
        return self.0.json_comma;
    }

    /// For use before a value or member.
    /// Writes: comma?-newline-indent? i.e. `,\n  `.
    #[cfg(test)]
    pub fn write_newline_before_value(&mut self, indent: usize) -> fmt::Result {
        if self.0.json_comma {
            self.0.dest.write_ascii(b',')?;
        }

        if cfg!(windows) {
            self.0.dest.write_str("\r\n")?;
        } else {
            self.0.dest.write_ascii(b'\n')?;
        }

        self.0.json_comma = false;

        if self.0.json_space {
            for _ in 0..indent {
                self.0.dest.write_ascii(b' ')?;
            }
        }
        self.0.json_space = false;

        return Ok(());
    }

    /// Writes: `, "escaped-name":`
    #[cfg(test)]
    pub fn write_property_name(&mut self, name: &str) -> fmt::Result {
        self.write_raw_comma_space()?;
        self.0.json_comma = false;

        self.0.dest.write_ascii(b'"')?;
        JsonEscapeFilter::new(&mut self.0.dest).write_str(name)?;
        return self.0.dest.write_str("\":");
    }

    /// Writes: `, "name":` (assumes it is already escaped for JSON).
    pub fn write_property_name_json_safe(&mut self, name: &str) -> fmt::Result {
        self.write_raw_comma_space()?;
        self.0.json_comma = false;

        self.0.dest.write_ascii(b'"')?;
        self.0.dest.write_str(name)?;
        return self.0.dest.write_str("\":");
    }

    /// If yes tag, writes: `, "escaped-name;tag=0xTAG":`.
    ///
    /// If no tag, writes: `, "escaped-name":`.
    pub fn write_property_name_from_item_info(
        &mut self,
        item_info: &EventHeaderItemInfo,
    ) -> fmt::Result {
        self.write_raw_comma_space()?;
        self.0.json_comma = false;

        self.0.dest.write_ascii(b'"')?;
        self.0.write_utf8_with_json_escape(item_info.name_bytes())?;
        if self.0.options.has_flag(PerfConvertOptions::FieldTag) {
            let tag = item_info.metadata().field_tag();
            if tag != 0 {
                write!(self.0.dest, ";tag=0x{:X}", tag)?;
            }
        }

        return self.0.dest.write_str("\":");
    }

    /// Writes: `, {`
    pub fn write_object_begin(&mut self) -> fmt::Result {
        self.write_raw_comma_space()?;
        self.0.json_comma = false;

        return self.0.dest.write_ascii(b'{');
    }

    /// Writes: ` }`
    pub fn write_object_end(&mut self) -> fmt::Result {
        self.0.json_comma = true;
        if self.0.json_space {
            self.0.dest.write_ascii(b' ')?;
        }
        return self.0.dest.write_ascii(b'}');
    }

    /// Writes: `, [`
    pub fn write_array_begin(&mut self) -> fmt::Result {
        self.write_raw_comma_space()?;
        self.0.json_comma = false;

        return self.0.dest.write_ascii(b'[');
    }

    /// Writes: ` ]`
    pub fn write_array_end(&mut self) -> fmt::Result {
        self.0.json_comma = true;
        if self.0.json_space {
            self.0.dest.write_ascii(b' ')?;
        }
        return self.0.dest.write_ascii(b']');
    }

    /// Writes leading comma/space if needed,
    /// then invokes `f` to write the value.
    pub fn write_value<F, R>(&mut self, f: F) -> Result<R, fmt::Error>
    where
        F: FnOnce(&mut ValueWriter<'wri, W>) -> Result<R, fmt::Error>,
    {
        self.write_raw_comma_space()?;
        self.0.json_comma = true;

        return f(&mut self.0);
    }

    /// Writes leading comma/space if needed, then writes `"`,
    /// then invokes `f` to write the value, then writes `"`.
    pub fn write_value_quoted<F, R>(&mut self, f: F) -> Result<R, fmt::Error>
    where
        F: FnOnce(&mut ValueWriter<'wri, W>) -> Result<R, fmt::Error>,
    {
        self.write_raw_comma_space()?;
        self.0.json_comma = true;

        return self.0.write_quoted(f);
    }

    /// Writes comma and space as needed.
    /// Updates `json_space`. Does NOT update `json_comma`.
    fn write_raw_comma_space(&mut self) -> fmt::Result {
        let need_space = self.0.json_space;
        self.0.json_space = self.0.options.has_flag(PerfConvertOptions::Space);
        return if need_space {
            if self.0.json_comma {
                self.0.dest.write_str(", ")
            } else {
                self.0.dest.write_ascii(b' ')
            }
        } else if self.0.json_comma {
            self.0.dest.write_ascii(b',')
        } else {
            Ok(())
        };
    }
}

/// Writes values to a `fmt::Write` destination.
pub struct ValueWriter<'wri, W: fmt::Write + ?Sized> {
    dest: WriteFilter<'wri, W>,
    options: PerfConvertOptions,

    // The following fields are used only when this is part of a `JsonWriter`.
    // They are stored in the `ValueWriter` because they are in space that
    // would otherwise be padding.
    /// Should the next JSON item be preceded by a comma?
    /// e.g. true after '{', false after '}'.
    json_comma: bool,

    /// Should the next JSON item be preceded by a space?
    json_space: bool,
}

impl<'wri, W: fmt::Write + ?Sized> ValueWriter<'wri, W> {
    const ERRNO_STRINGS: [&'static str; 134] = [
        "ERRNO(0)",
        "EPERM(1)",
        "ENOENT(2)",
        "ESRCH(3)",
        "EINTR(4)",
        "EIO(5)",
        "ENXIO(6)",
        "E2BIG(7)",
        "ENOEXEC(8)",
        "EBADF(9)",
        "ECHILD(10)",
        "EAGAIN(11)",
        "ENOMEM(12)",
        "EACCES(13)",
        "EFAULT(14)",
        "ENOTBLK(15)",
        "EBUSY(16)",
        "EEXIST(17)",
        "EXDEV(18)",
        "ENODEV(19)",
        "ENOTDIR(20)",
        "EISDIR(21)",
        "EINVAL(22)",
        "ENFILE(23)",
        "EMFILE(24)",
        "ENOTTY(25)",
        "ETXTBSY(26)",
        "EFBIG(27)",
        "ENOSPC(28)",
        "ESPIPE(29)",
        "EROFS(30)",
        "EMLINK(31)",
        "EPIPE(32)",
        "EDOM(33)",
        "ERANGE(34)",
        "EDEADLK(35)",
        "ENAMETOOLONG(36)",
        "ENOLCK(37)",
        "ENOSYS(38)",
        "ENOTEMPTY(39)",
        "ELOOP(40)",
        "ERRNO(41)",
        "ENOMSG(42)",
        "EIDRM(43)",
        "ECHRNG(44)",
        "EL2NSYNC(45)",
        "EL3HLT(46)",
        "EL3RST(47)",
        "ELNRNG(48)",
        "EUNATCH(49)",
        "ENOCSI(50)",
        "EL2HLT(51)",
        "EBADE(52)",
        "EBADR(53)",
        "EXFULL(54)",
        "ENOANO(55)",
        "EBADRQC(56)",
        "EBADSLT(57)",
        "ERRNO(58)",
        "EBFONT(59)",
        "ENOSTR(60)",
        "ENODATA(61)",
        "ETIME(62)",
        "ENOSR(63)",
        "ENONET(64)",
        "ENOPKG(65)",
        "EREMOTE(66)",
        "ENOLINK(67)",
        "EADV(68)",
        "ESRMNT(69)",
        "ECOMM(70)",
        "EPROTO(71)",
        "EMULTIHOP(72)",
        "EDOTDOT(73)",
        "EBADMSG(74)",
        "EOVERFLOW(75)",
        "ENOTUNIQ(76)",
        "EBADFD(77)",
        "EREMCHG(78)",
        "ELIBACC(79)",
        "ELIBBAD(80)",
        "ELIBSCN(81)",
        "ELIBMAX(82)",
        "ELIBEXEC(83)",
        "EILSEQ(84)",
        "ERESTART(85)",
        "ESTRPIPE(86)",
        "EUSERS(87)",
        "ENOTSOCK(88)",
        "EDESTADDRREQ(89)",
        "EMSGSIZE(90)",
        "EPROTOTYPE(91)",
        "ENOPROTOOPT(92)",
        "EPROTONOSUPPORT(93)",
        "ESOCKTNOSUPPORT(94)",
        "EOPNOTSUPP(95)",
        "EPFNOSUPPORT(96)",
        "EAFNOSUPPORT(97)",
        "EADDRINUSE(98)",
        "EADDRNOTAVAIL(99)",
        "ENETDOWN(100)",
        "ENETUNREACH(101)",
        "ENETRESET(102)",
        "ECONNABORTED(103)",
        "ECONNRESET(104)",
        "ENOBUFS(105)",
        "EISCONN(106)",
        "ENOTCONN(107)",
        "ESHUTDOWN(108)",
        "ETOOMANYREFS(109)",
        "ETIMEDOUT(110)",
        "ECONNREFUSED(111)",
        "EHOSTDOWN(112)",
        "EHOSTUNREACH(113)",
        "EALREADY(114)",
        "EINPROGRESS(115)",
        "ESTALE(116)",
        "EUCLEAN(117)",
        "ENOTNAM(118)",
        "ENAVAIL(119)",
        "EISNAM(120)",
        "EREMOTEIO(121)",
        "EDQUOT(122)",
        "ENOMEDIUM(123)",
        "EMEDIUMTYPE(124)",
        "ECANCELED(125)",
        "ENOKEY(126)",
        "EKEYEXPIRED(127)",
        "EKEYREVOKED(128)",
        "EKEYREJECTED(129)",
        "EOWNERDEAD(130)",
        "ENOTRECOVERABLE(131)",
        "ERFKILL(132)",
        "EHWPOISON(133)",
    ];

    /// Creates a new `ValueWriter` with the specified destination and options.
    pub fn new(writer: &'wri mut W, options: PerfConvertOptions) -> ValueWriter<'wri, W> {
        return ValueWriter {
            dest: WriteFilter::new(writer),
            options,
            json_comma: false,
            json_space: false,
        };
    }

    /// Writes `"`, then invokes f, then writes `"`.
    pub fn write_quoted<F, R>(&mut self, f: F) -> Result<R, fmt::Error>
    where
        F: FnOnce(&mut ValueWriter<'wri, W>) -> Result<R, fmt::Error>,
    {
        self.dest.write_ascii(b'"')?;
        let result = f(self)?;
        self.dest.write_ascii(b'"')?;
        return Ok(result);
    }

    /// Calls the `write_*_with_control_chars_filter` function corresponding to `encoding`.
    pub fn write_with_control_chars_filter(
        &mut self,
        bytes: &[u8],
        encoding: PerfTextEncoding,
    ) -> fmt::Result {
        match encoding {
            PerfTextEncoding::Latin1 => self.write_latin1_with_control_chars_filter(bytes),
            PerfTextEncoding::Utf8 => self.write_utf8_with_control_chars_filter(bytes),
            PerfTextEncoding::Utf16BE => self.write_utf16be_with_control_chars_filter(bytes),
            PerfTextEncoding::Utf16LE => self.write_utf16le_with_control_chars_filter(bytes),
            PerfTextEncoding::Utf32BE => self.write_utf32be_with_control_chars_filter(bytes),
            PerfTextEncoding::Utf32LE => self.write_utf32le_with_control_chars_filter(bytes),
        }
    }

    /// Calls the `write_*_with_json_escape` function corresponding to `encoding`.
    pub fn write_with_json_escape(
        &mut self,
        bytes: &[u8],
        encoding: PerfTextEncoding,
    ) -> fmt::Result {
        match encoding {
            PerfTextEncoding::Latin1 => self.write_latin1_with_json_escape(bytes),
            PerfTextEncoding::Utf8 => self.write_utf8_with_json_escape(bytes),
            PerfTextEncoding::Utf16BE => self.write_utf16be_with_json_escape(bytes),
            PerfTextEncoding::Utf16LE => self.write_utf16le_with_json_escape(bytes),
            PerfTextEncoding::Utf32BE => self.write_utf32be_with_json_escape(bytes),
            PerfTextEncoding::Utf32LE => self.write_utf32le_with_json_escape(bytes),
        }
    }

    /// Writes a string with no filtering of control characters.
    pub fn write_str_with_no_filter(&mut self, value: &str) -> fmt::Result {
        return self.dest.write_str(value);
    }

    /// Writes a string with JSON filtering of control/punctuation characters.
    pub fn write_str_with_json_escape(&mut self, value: &str) -> fmt::Result {
        return JsonEscapeFilter::new(&mut self.dest).write_str(value);
    }

    /// Writes a string with no filtering of control characters.
    pub fn write_fmt_with_no_filter(&mut self, args: fmt::Arguments) -> fmt::Result {
        return self.dest.write_fmt(args);
    }

    /// Writes string from Latin-1 bytes with no filtering of control characters.
    pub fn write_latin1_with_no_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_latin1_to(bytes, &mut self.dest);
    }

    /// Writes string from Latin-1 bytes with JSON filtering of control/punctuation characters.
    pub fn write_latin1_with_json_escape(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_latin1_to(bytes, &mut JsonEscapeFilter::new(&mut self.dest));
    }

    /// Writes string from Latin-1 bytes with filtering of control characters as specified by
    /// the [`PerfConvertOptions::StringControlCharsMask`] flags in `options`.
    pub fn write_latin1_with_control_chars_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return match self.options.and(PerfConvertOptions::StringControlCharsMask) {
            PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                charconv::write_latin1_to(bytes, &mut ControlCharsSpaceFilter::new(&mut self.dest))
            }
            PerfConvertOptions::StringControlCharsJsonEscape => {
                charconv::write_latin1_to(bytes, &mut ControlCharsJsonFilter::new(&mut self.dest))
            }
            _ => self.write_latin1_with_no_filter(bytes),
        };
    }

    /// Writes string from UTF-8 (with Latin-1 fallback) bytes with no filtering of control characters.
    pub fn write_utf8_with_no_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf8_with_latin1_fallback_to(bytes, &mut self.dest);
    }

    /// Writes string from UTF-8 (with Latin-1 fallback) bytes with JSON filtering of control/punctuation characters.
    pub fn write_utf8_with_json_escape(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf8_with_latin1_fallback_to(
            bytes,
            &mut JsonEscapeFilter::new(&mut self.dest),
        );
    }

    /// Writes string from UTF-8 (with Latin-1 fallback) bytes with filtering of control characters as specified by
    /// the [`PerfConvertOptions::StringControlCharsMask`] flags in `options`.
    pub fn write_utf8_with_control_chars_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return match self.options.and(PerfConvertOptions::StringControlCharsMask) {
            PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                charconv::write_utf8_with_latin1_fallback_to(
                    bytes,
                    &mut ControlCharsSpaceFilter::new(&mut self.dest),
                )
            }
            PerfConvertOptions::StringControlCharsJsonEscape => {
                charconv::write_utf8_with_latin1_fallback_to(
                    bytes,
                    &mut ControlCharsJsonFilter::new(&mut self.dest),
                )
            }
            _ => self.write_utf8_with_no_filter(bytes),
        };
    }

    /// Writes string from UTF-16BE bytes with no filtering of control characters.
    pub fn write_utf16be_with_no_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf16be_to(bytes, &mut self.dest);
    }

    /// Writes string from UTF-16BE bytes with JSON filtering of control/punctuation characters.
    pub fn write_utf16be_with_json_escape(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf16be_to(bytes, &mut JsonEscapeFilter::new(&mut self.dest));
    }

    /// Writes string from UTF-16BE bytes with filtering of control characters as specified by
    /// the [`PerfConvertOptions::StringControlCharsMask`] flags in `options`.
    pub fn write_utf16be_with_control_chars_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return match self.options.and(PerfConvertOptions::StringControlCharsMask) {
            PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                charconv::write_utf16be_to(bytes, &mut ControlCharsSpaceFilter::new(&mut self.dest))
            }
            PerfConvertOptions::StringControlCharsJsonEscape => {
                charconv::write_utf16be_to(bytes, &mut ControlCharsJsonFilter::new(&mut self.dest))
            }
            _ => self.write_utf16be_with_no_filter(bytes),
        };
    }

    /// Writes string from UTF-16LE bytes with no filtering of control characters.
    pub fn write_utf16le_with_no_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf16le_to(bytes, &mut self.dest);
    }

    /// Writes string from UTF-16LE bytes with JSON filtering of control/punctuation characters.
    pub fn write_utf16le_with_json_escape(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf16le_to(bytes, &mut JsonEscapeFilter::new(&mut self.dest));
    }

    /// Writes string from UTF-16LE bytes with filtering of control characters as specified by
    /// the [`PerfConvertOptions::StringControlCharsMask`] flags in `options`.
    pub fn write_utf16le_with_control_chars_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return match self.options.and(PerfConvertOptions::StringControlCharsMask) {
            PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                charconv::write_utf16le_to(bytes, &mut ControlCharsSpaceFilter::new(&mut self.dest))
            }
            PerfConvertOptions::StringControlCharsJsonEscape => {
                charconv::write_utf16le_to(bytes, &mut ControlCharsJsonFilter::new(&mut self.dest))
            }
            _ => self.write_utf16le_with_no_filter(bytes),
        };
    }

    /// Writes string from UTF-32BE bytes with no filtering of control characters.
    pub fn write_utf32be_with_no_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf32be_to(bytes, &mut self.dest);
    }

    /// Writes string from UTF-32BE bytes with JSON filtering of control/punctuation characters.
    pub fn write_utf32be_with_json_escape(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf32be_to(bytes, &mut JsonEscapeFilter::new(&mut self.dest));
    }

    /// Writes string from UTF-32BE bytes with filtering of control characters as specified by
    /// the [`PerfConvertOptions::StringControlCharsMask`] flags in `options`.
    pub fn write_utf32be_with_control_chars_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return match self.options.and(PerfConvertOptions::StringControlCharsMask) {
            PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                charconv::write_utf32be_to(bytes, &mut ControlCharsSpaceFilter::new(&mut self.dest))
            }
            PerfConvertOptions::StringControlCharsJsonEscape => {
                charconv::write_utf32be_to(bytes, &mut ControlCharsJsonFilter::new(&mut self.dest))
            }
            _ => self.write_utf32be_with_no_filter(bytes),
        };
    }

    /// Writes string from UTF-32LE bytes with no filtering of control characters.
    pub fn write_utf32le_with_no_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf32le_to(bytes, &mut self.dest);
    }

    /// Writes string from UTF-32LE bytes with JSON filtering of control/punctuation characters.
    pub fn write_utf32le_with_json_escape(&mut self, bytes: &[u8]) -> fmt::Result {
        return charconv::write_utf32le_to(bytes, &mut JsonEscapeFilter::new(&mut self.dest));
    }

    /// Writes string from UTF-32LE bytes with filtering of control characters as specified by
    /// the [`PerfConvertOptions::StringControlCharsMask`] flags in `options`.
    pub fn write_utf32le_with_control_chars_filter(&mut self, bytes: &[u8]) -> fmt::Result {
        return match self.options.and(PerfConvertOptions::StringControlCharsMask) {
            PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                charconv::write_utf32le_to(bytes, &mut ControlCharsSpaceFilter::new(&mut self.dest))
            }
            PerfConvertOptions::StringControlCharsJsonEscape => {
                charconv::write_utf32le_to(bytes, &mut ControlCharsJsonFilter::new(&mut self.dest))
            }
            _ => self.write_utf32le_with_no_filter(bytes),
        };
    }

    /// If `value` is a control char, write it respecting [`PerfConvertOptions::StringControlCharsMask`].
    /// Otherwise, if `value` is a valid Unicode code point, write it.
    /// Otherwise, write the replacement character.
    pub fn write_char32_with_control_chars_filter(&mut self, value: u32) -> fmt::Result {
        let result = if value >= 0x20 {
            self.dest.write_char(char_from_u32(value))
        } else {
            match self.options.and(PerfConvertOptions::StringControlCharsMask) {
                PerfConvertOptions::StringControlCharsReplaceWithSpace => {
                    self.dest.write_ascii(b' ')
                }
                PerfConvertOptions::StringControlCharsJsonEscape => {
                    ControlCharsJsonFilter::new(&mut self.dest).write_ascii(value as u8)
                }
                _ => self.dest.write_ascii(value as u8),
            }
        };
        return result;
    }

    /// Otherwise, if `value` is a valid Unicode code point, write it with JSON escape.
    /// Otherwise, write the replacement character.
    pub fn write_char32_with_json_escape(&mut self, value: u32) -> fmt::Result {
        let result = if value >= ('\\' as u32) {
            self.dest.write_char(char_from_u32(value))
        } else {
            JsonEscapeFilter::new(&mut self.dest).write_ascii(value as u8)
        };
        return result;
    }

    /// Writes e.g. `a3a2a1a0-b1b0-c1c0-d7d6-d5d4d3d2d1d0`.
    pub fn write_uuid(&mut self, value: &[u8; 16]) -> fmt::Result {
        let tmp = Guid::from_bytes_be(value).to_utf8_bytes();
        return self.dest.write_str(unsafe {
            str::from_utf8_unchecked(&tmp)
        });
    }

    /// Writes e.g. `01 1f f0`.
    pub fn write_hexbytes(&mut self, bytes: &[u8]) -> fmt::Result {
        if !bytes.is_empty() {
            write!(self.dest, "{:02X}", bytes[0])?;
            for b in bytes.iter().skip(1) {
                write!(self.dest, " {:02X}", b)?;
            }
        }
        return Ok(());
    }

    /// Writes any [`fmt::Display`] using `{}` formatting.
    pub fn write_display_with_no_filter<D: fmt::Display>(&mut self, value: D) -> fmt::Result {
        return write!(self.dest, "{}", value);
    }

    /// Writes hex integer e.g. `0x1FF`.
    pub fn write_hex32(&mut self, value: u32) -> fmt::Result {
        return write!(self.dest, "0x{:X}", value);
    }

    /// Writes hex integer e.g. `0x1FF`.
    pub fn write_hex64(&mut self, value: u64) -> fmt::Result {
        return write!(self.dest, "0x{:X}", value);
    }

    /// Writes an IPv4 address, e.g. `127.0.0.1`.
    pub fn write_ipv4(&mut self, value: [u8; 4]) -> fmt::Result {
        return write!(
            self.dest,
            "{}.{}.{}.{}",
            value[0], value[1], value[2], value[3]
        );
    }

    /// Writes an IPv6 address, e.g. `ffff::1234`.
    pub fn write_ipv6(&mut self, value: &[u8; 16]) -> fmt::Result {
        #[cfg(feature = "rustc_1_77")]
        return write!(self.dest, "{}", net::Ipv6Addr::from(*value));
        #[cfg(not(feature = "rustc_1_77"))]
        return write!(
            self.dest,
            "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
            u16::from_be_bytes(value[0..2].try_into().unwrap()),
            u16::from_be_bytes(value[2..4].try_into().unwrap()),
            u16::from_be_bytes(value[4..6].try_into().unwrap()),
            u16::from_be_bytes(value[6..8].try_into().unwrap()),
            u16::from_be_bytes(value[8..10].try_into().unwrap()),
            u16::from_be_bytes(value[10..12].try_into().unwrap()),
            u16::from_be_bytes(value[12..14].try_into().unwrap()),
            u16::from_be_bytes(value[14..16].try_into().unwrap()),
        );
    }

    /// Writes hex string or decimal, respecting [`PerfConvertOptions::IntHexAsString`],
    /// e.g. `"0xFF"` or `255`.
    pub fn write_json_hex32(&mut self, value: u32) -> fmt::Result {
        let result = if self.options.has_flag(PerfConvertOptions::IntHexAsString) {
            write!(self.dest, "\"0x{:X}\"", value)
        } else {
            write!(self.dest, "{}", value)
        };
        return result;
    }

    /// Writes hex string or decimal, respecting [`PerfConvertOptions::IntHexAsString`],
    /// e.g. `"0xFF"` or `255`.
    pub fn write_json_hex64(&mut self, value: u64) -> fmt::Result {
        let result = if self.options.has_flag(PerfConvertOptions::IntHexAsString) {
            write!(self.dest, "\"0x{:X}\"", value)
        } else {
            write!(self.dest, "{}", value)
        };
        return result;
    }

    /// Writes a boolean, respecting [`PerfConvertOptions::BoolOutOfRangeAsString`]. e.g. `true`,
    /// `false`, `BOOL(-12)`, or `-12`. For values other than 0 and 1, the value is treated as a
    /// signed integer, but the parameter is a `u32` because bool8 and bool16 should NOT be
    /// sign-extended.
    pub fn write_bool(&mut self, value: u32) -> fmt::Result {
        let result = match value {
            0 => self.dest.write_str("false"),
            1 => self.dest.write_str("true"),
            _ => {
                if self
                    .options
                    .has_flag(PerfConvertOptions::BoolOutOfRangeAsString)
                {
                    write!(self.dest, "BOOL({})", value as i32)
                } else {
                    write!(self.dest, "{}", value as i32)
                }
            }
        };
        return result;
    }

    /// Writes a boolean, respecting [`PerfConvertOptions::BoolOutOfRangeAsString`]. e.g. `true`,
    /// `false`, `"BOOL(-12)"`, or `-12`. For values other than 0 and 1, the value is treated as a
    /// signed integer, but the parameter is a `u32` because bool8 and bool16 should NOT be
    /// sign-extended.
    pub fn write_json_bool(&mut self, value: u32) -> fmt::Result {
        let result = match value {
            0 => self.dest.write_str("false"),
            1 => self.dest.write_str("true"),
            _ => {
                if self
                    .options
                    .has_flag(PerfConvertOptions::BoolOutOfRangeAsString)
                {
                    write!(self.dest, "\"BOOL({})\"", value as i32)
                } else {
                    write!(self.dest, "{}", value as i32)
                }
            }
        };
        return result;
    }

    /// Writes an errno, respecting [`PerfConvertOptions::ErrnoUnknownAsString`],
    /// e.g. `ENOENT(2)`, `ERRNO(-12)`, or `-12`.
    pub fn write_errno(&mut self, value: u32) -> fmt::Result {
        let result = if value < Self::ERRNO_STRINGS.len() as u32 {
            self.dest.write_str(Self::ERRNO_STRINGS[value as usize])
        } else if self
            .options
            .has_flag(PerfConvertOptions::ErrnoUnknownAsString)
        {
            write!(self.dest, "ERRNO({})", value as i32)
        } else {
            write!(self.dest, "{}", value as i32)
        };
        return result;
    }

    /// Writes an errno, respecting [`PerfConvertOptions::ErrnoKnownAsString`] and
    /// [`PerfConvertOptions::ErrnoUnknownAsString`],
    /// e.g. `"ENOENT(2)"`, `"ERRNO(-12)"`, or `-12`.
    pub fn write_json_errno(&mut self, value: u32) -> fmt::Result {
        if value < Self::ERRNO_STRINGS.len() as u32 {
            if self
                .options
                .has_flag(PerfConvertOptions::ErrnoKnownAsString)
            {
                return write!(self.dest, "\"{}\"", Self::ERRNO_STRINGS[value as usize]);
            }
        } else if self
            .options
            .has_flag(PerfConvertOptions::ErrnoUnknownAsString)
        {
            return write!(self.dest, "\"ERRNO({})\"", value as i32);
        }

        return write!(self.dest, "{}", value as i32);
    }

    /// Writes a time64, respecting [`PerfConvertOptions::UnixTimeOutOfRangeAsString`],
    /// e.g. `2020-02-02T02:02:02Z`, `TIME(1234567890)`, or `1234567890`.
    pub fn write_time64(&mut self, value: i64) -> fmt::Result {
        let dt = date_time::DateTime::new(value);
        if dt.valid() {
            return write!(
                self.dest,
                "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
                dt.year(),
                dt.month_of_year(),
                dt.day_of_month(),
                dt.hour(),
                dt.minute(),
                dt.second()
            );
        } else if self
            .options
            .has_flag(PerfConvertOptions::UnixTimeOutOfRangeAsString)
        {
            return write!(self.dest, "TIME({})", value);
        }

        return write!(self.dest, "{}", value);
    }

    /// Writes a JSON time64, respecting [`PerfConvertOptions::UnixTimeOutOfRangeAsString`]
    /// and [`PerfConvertOptions::UnixTimeWithinRangeAsString`],
    /// e.g. `2020-02-02T02:02:02Z`, `TIME(1234567890)`, or `1234567890`.
    pub fn write_json_time64(&mut self, value: i64) -> fmt::Result {
        let dt = date_time::DateTime::new(value);
        if dt.valid() {
            if self
                .options
                .has_flag(PerfConvertOptions::UnixTimeWithinRangeAsString)
            {
                return write!(
                    self.dest,
                    "\"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z\"",
                    dt.year(),
                    dt.month_of_year(),
                    dt.day_of_month(),
                    dt.hour(),
                    dt.minute(),
                    dt.second()
                );
            }
        } else if self
            .options
            .has_flag(PerfConvertOptions::UnixTimeOutOfRangeAsString)
        {
            return write!(self.dest, "\"TIME({})\"", value);
        }

        return write!(self.dest, "{}", value);
    }

    /// Writes an `f32`, respecting [`PerfConvertOptions::FloatExtraPrecision`] flag.
    pub fn write_float32(&mut self, value: f32) -> fmt::Result {
        let abs_value = if value >= 0.0 { value } else { -value };
        let e = abs_value >= 1.0e+9 || (abs_value != 0.0 && abs_value < 1.0e-4);
        let result = if self
            .options
            .has_flag(PerfConvertOptions::FloatExtraPrecision)
        {
            if e {
                write!(self.dest, "{:.9e}", value)
            } else {
                write!(self.dest, "{:.9}", value)
            }
        } else if e {
            write!(self.dest, "{:e}", value)
        } else {
            write!(self.dest, "{:}", value)
        };
        return result;
    }

    /// Writes an `f64`, respecting [`PerfConvertOptions::FloatExtraPrecision`] flag.
    pub fn write_float64(&mut self, value: f64) -> fmt::Result {
        let abs_value = if value >= 0.0 { value } else { -value };
        let e = abs_value >= 1.0e+17 || (abs_value != 0.0 && abs_value < 1.0e-4);
        let result = if self
            .options
            .has_flag(PerfConvertOptions::FloatExtraPrecision)
        {
            if e {
                write!(self.dest, "{:.17e}", value)
            } else {
                write!(self.dest, "{:.17}", value)
            }
        } else if e {
            write!(self.dest, "{:e}", value)
        } else {
            write!(self.dest, "{:}", value)
        };
        return result;
    }

    /// Writes an `f32`, respecting [`PerfConvertOptions::FloatExtraPrecision`] and
    /// [`PerfConvertOptions::FloatNonFiniteAsString`] flags.
    pub fn write_json_float32(&mut self, value: f32) -> fmt::Result {
        let result = if value.is_finite() {
            self.write_float32(value)
        } else if self
            .options
            .has_flag(PerfConvertOptions::FloatNonFiniteAsString)
        {
            write!(self.dest, "\"{}\"", value)
        } else {
            self.dest.write_str("null")
        };
        return result;
    }

    /// Writes an `f64`, respecting [`PerfConvertOptions::FloatExtraPrecision`] and
    /// [`PerfConvertOptions::FloatNonFiniteAsString`] flags.
    pub fn write_json_float64(&mut self, value: f64) -> fmt::Result {
        let result = if value.is_finite() {
            self.write_float64(value)
        } else if self
            .options
            .has_flag(PerfConvertOptions::FloatNonFiniteAsString)
        {
            write!(self.dest, "\"{}\"", value)
        } else {
            self.dest.write_str("null")
        };
        return result;
    }
}