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
// Copyright 2020 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.

//! Encoding diagnostic records using the Fuchsia Tracing format.

use crate::{ArgType, Header, Metatag, SeverityExt, StringRef};
use fidl_fuchsia_diagnostics::Severity;
use fidl_fuchsia_diagnostics_stream as fstream;
use fuchsia_zircon as zx;
use std::{array::TryFromSliceError, borrow::Borrow, fmt::Debug, io::Cursor, ops::Deref};
use thiserror::Error;
use tracing::{Event, Metadata, Subscriber};
use tracing_core::{
    field::{Field, Visit},
    span,
};
use tracing_log::NormalizeEvent;
use tracing_subscriber::{
    layer::Context,
    registry::{LookupSpan, Scope},
};

/// An `Encoder` wraps any value implementing `MutableBuffer` and writes diagnostic stream records
/// into it.
pub struct Encoder<B> {
    pub(crate) buf: B,
    found_error: Option<EncodingError>,
}

/// Parameters for `Encoder/write_event`.
pub struct WriteEventParams<'a, E, T, MS> {
    /// The event to write as a record.
    pub event: E,
    /// Tags associated with the log event.
    pub tags: &'a [T],
    /// Metatags associated with the log event.
    pub metatags: MS,
    /// The process that emitted the log.
    pub pid: zx::Koid,
    /// The thread that emitted the log.
    pub tid: zx::Koid,
    /// Number of events that were dropped before this one.
    pub dropped: u32,
}

impl<B> Encoder<B>
where
    B: MutableBuffer,
{
    /// Create a new `Encoder` from the provided buffer.
    pub fn new(buf: B) -> Self {
        Self { buf, found_error: None }
    }

    /// Returns a reference to the underlying buffer being used for encoding.
    pub fn inner(&self) -> &B {
        &self.buf
    }

    /// Writes a [`tracing::Event`] to the buffer as a record.
    ///
    /// Fails if there is insufficient space in the buffer for encoding.
    pub fn write_event<'a, E, MS, T>(
        &mut self,
        params: WriteEventParams<'a, E, T, MS>,
    ) -> Result<(), EncodingError>
    where
        E: RecordEvent,
        MS: Iterator<Item = &'a Metatag>,
        T: AsRef<str>,
    {
        let WriteEventParams { event, tags, metatags, pid, tid, dropped } = params;
        let severity = event.severity();
        self.write_inner(event.timestamp(), severity, |this| {
            this.write_argument(Argument { name: "pid", value: pid.into() })?;
            this.write_argument(Argument { name: "tid", value: tid.into() })?;
            if dropped > 0 {
                this.write_argument(Argument { name: "num_dropped", value: dropped.into() })?;
            }

            // If the severity is ERROR or higher, we add the file and line information.
            if severity >= Severity::Error.into_primitive() {
                if let Some(mut file) = event.file() {
                    let split = file.split("../");
                    file = split.last().unwrap();
                    this.write_argument(Argument { name: "file", value: Value::Text(file) })?;
                }

                if let Some(line) = event.line() {
                    this.write_argument(Argument { name: "line", value: line.into() })?;
                }
            }

            // Write the metatags as tags (if any were given)
            for metatag in metatags {
                match metatag {
                    Metatag::Target => this.write_argument(Argument {
                        name: "tag",
                        value: Value::Text(event.target()),
                    })?,
                }
            }

            event.write_arguments(this)?;

            for tag in tags {
                this.write_argument(Argument { name: "tag", value: Value::Text(tag.as_ref()) })?;
            }
            Ok(())
        })?;
        Ok(())
    }

    /// Writes a Record to the buffer.
    pub fn write_record<R>(&mut self, record: &R) -> Result<(), EncodingError>
    where
        R: RecordFields,
    {
        self.write_inner(record.timestamp(), record.severity(), |this| record.write_arguments(this))
    }

    fn write_inner<F>(
        &mut self,
        timestamp: zx::Time,
        severity: fstream::RawSeverity,
        write_args: F,
    ) -> Result<(), EncodingError>
    where
        F: FnOnce(&mut Self) -> Result<(), EncodingError>,
    {
        // TODO(https://fxbug.dev/42138121): on failure, zero out the region we were using
        let starting_idx = self.buf.cursor();
        // Prepare the header, we'll finish writing once we know the full size of the record.
        let header_slot = self.buf.put_slot(std::mem::size_of::<u64>())?;
        self.write_i64(timestamp.into_nanos())?;

        write_args(self)?;

        let mut header = Header(0);
        header.set_type(crate::TRACING_FORMAT_LOG_RECORD_TYPE);
        header.set_severity(severity);

        let length = self.buf.cursor() - starting_idx;
        header.set_len(length);

        assert_eq!(length % 8, 0, "all records must be written 8-byte aligned");
        self.buf.fill_slot(header_slot, &header.0.to_le_bytes());
        Ok(())
    }

    /// Writes an argument with this encoder.
    pub fn write_argument<'a>(
        &mut self,
        argument: impl Borrow<Argument<'a>>,
    ) -> Result<(), EncodingError> {
        let argument = argument.borrow();
        let starting_idx = self.buf.cursor();

        let header_slot = self.buf.put_slot(std::mem::size_of::<Header>())?;

        let mut header = Header(0);

        self.write_string(argument.name)?;
        header.set_name_ref(StringRef::for_str(argument.name).mask());

        match &argument.value {
            Value::SignedInt(s) => {
                header.set_type(ArgType::I64 as u8);
                self.write_i64(*s)
            }
            Value::UnsignedInt(u) => {
                header.set_type(ArgType::U64 as u8);
                self.write_u64(*u)
            }
            Value::Floating(f) => {
                header.set_type(ArgType::F64 as u8);
                self.write_f64(*f)
            }
            Value::Text(t) => {
                header.set_type(ArgType::String as u8);
                header.set_value_ref(StringRef::for_str(t).mask());
                self.write_string(t)
            }
            Value::Boolean(b) => {
                header.set_type(ArgType::Bool as u8);
                header.set_bool_val(*b);
                Ok(())
            }
        }?;

        let record_len = self.buf.cursor() - starting_idx;
        assert_eq!(record_len % 8, 0, "arguments must be 8-byte aligned");

        header.set_size_words((record_len / 8) as u16);
        self.buf.fill_slot(header_slot, &header.0.to_le_bytes());

        Ok(())
    }

    fn maybe_write_argument<'a>(
        &mut self,
        field: &Field,
        value: impl Into<Value<'a>>,
    ) -> Result<(), EncodingError> {
        let name = field.name();
        if !matches!(name, "log.target" | "log.module_path" | "log.file" | "log.line") {
            self.write_argument(Argument { name, value: value.into() })?;
        }
        Ok(())
    }

    /// Write an unsigned integer.
    fn write_u64(&mut self, n: u64) -> Result<(), EncodingError> {
        self.buf.put_u64_le(n).map_err(|_| EncodingError::BufferTooSmall)
    }

    /// Write a signed integer.
    fn write_i64(&mut self, n: i64) -> Result<(), EncodingError> {
        self.buf.put_i64_le(n).map_err(|_| EncodingError::BufferTooSmall)
    }

    /// Write a floating-point number.
    fn write_f64(&mut self, n: f64) -> Result<(), EncodingError> {
        self.buf.put_f64(n).map_err(|_| EncodingError::BufferTooSmall)
    }

    /// Write a string padded to 8-byte alignment.
    fn write_string(&mut self, src: &str) -> Result<(), EncodingError> {
        self.write_bytes(src.as_bytes())
    }

    /// Write bytes padded to 8-byte alignment.
    fn write_bytes(&mut self, src: &[u8]) -> Result<(), EncodingError> {
        self.buf.put_slice(src).map_err(|_| EncodingError::BufferTooSmall)?;
        unsafe {
            let align = std::mem::size_of::<u64>();
            let num_padding_bytes = (align - src.len() % align) % align;
            // TODO(https://fxbug.dev/42138122) need to enforce that the buffer is zeroed
            self.buf.advance_cursor(num_padding_bytes);
        }
        Ok(())
    }
}

/// The attributes of a Span pre-encoded for usage in child events.
pub struct EncodedSpanArguments {
    encoder: Encoder<Cursor<ResizableBuffer>>,
}

impl EncodedSpanArguments {
    /// Encodes the given span attributes.
    pub fn new(attrs: &span::Attributes<'_>) -> Result<Self, EncodingError> {
        let mut encoder = Encoder::new(Cursor::new(ResizableBuffer(Vec::new())));
        attrs.record(&mut encoder);
        if let Some(err) = encoder.found_error {
            return Err(err);
        }
        Ok(Self { encoder })
    }

    /// Encodes the given span attributes, replacing existing ones.
    // TODO(b/312805612): this should update rather than overwrite.
    pub fn from_record(record: &span::Record<'_>) -> Result<Self, EncodingError> {
        let mut encoder = Encoder::new(Cursor::new(ResizableBuffer(Vec::new())));
        record.record(&mut encoder);
        if let Some(err) = encoder.found_error {
            return Err(err);
        }
        Ok(Self { encoder })
    }

    fn copy_to<B: MutableBuffer>(&self, encoder: &mut Encoder<B>) -> Result<(), EncodingError> {
        let buffer = self.encoder.inner();
        let end = buffer.cursor().min(buffer.get_ref().0.len());
        encoder.write_bytes(&buffer.get_ref().0[..end])
    }
}

impl<B: MutableBuffer> Visit for Encoder<B> {
    fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
        if let Err(err) = self.maybe_write_argument(field, format!("{value:?}").as_str()) {
            self.found_error = Some(err);
        };
    }

    fn record_str(&mut self, field: &Field, value: &str) {
        if let Err(err) = self.maybe_write_argument(field, value) {
            self.found_error = Some(err);
        }
    }

    fn record_i64(&mut self, field: &Field, value: i64) {
        if let Err(err) = self.maybe_write_argument(field, value) {
            self.found_error = Some(err);
        }
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        if let Err(err) = self.maybe_write_argument(field, value) {
            self.found_error = Some(err);
        }
    }

    fn record_bool(&mut self, field: &Field, value: bool) {
        if let Err(err) = self.maybe_write_argument(field, value) {
            self.found_error = Some(err);
        }
    }
}

/// An argument for the logging format.
#[derive(Clone, Debug, PartialEq)]
pub struct Argument<'a> {
    /// The name of the logging argument.
    pub name: &'a str,
    /// The value of the logging argument.
    pub value: Value<'a>,
}

/// The value of a logging argument.
#[derive(Clone, Debug, PartialEq)]
pub enum Value<'a> {
    /// A signed integer value for a logging argument.
    SignedInt(i64),
    /// An unsigned integer value for a logging argument.
    UnsignedInt(u64),
    /// A floating point value for a logging argument.
    Floating(f64),
    /// A boolean value for a logging argument.
    Boolean(bool),
    /// A string value for a logging argument.
    Text(&'a str),
}

impl From<i64> for Value<'_> {
    fn from(number: i64) -> Value<'static> {
        Value::SignedInt(number)
    }
}

impl From<u64> for Value<'_> {
    fn from(number: u64) -> Value<'static> {
        Value::UnsignedInt(number)
    }
}

impl From<u32> for Value<'_> {
    fn from(number: u32) -> Value<'static> {
        Value::UnsignedInt(number as u64)
    }
}

impl From<zx::Koid> for Value<'_> {
    fn from(koid: zx::Koid) -> Value<'static> {
        Value::UnsignedInt(koid.raw_koid())
    }
}

impl From<f64> for Value<'_> {
    fn from(number: f64) -> Value<'static> {
        Value::Floating(number)
    }
}

impl<'a> From<&'a str> for Value<'a> {
    fn from(text: &'a str) -> Value<'a> {
        Value::Text(text)
    }
}

impl From<bool> for Value<'static> {
    fn from(boolean: bool) -> Value<'static> {
        Value::Boolean(boolean)
    }
}

/// Trait implemented by types which can be written by the Encoder.
pub trait RecordEvent {
    /// Returns the record severity.
    fn severity(&self) -> u8;
    /// Returns the name of the file where the record was emitted.
    fn file(&self) -> Option<&str>;
    /// Returns the number of the line in the file where the record was emitted.
    fn line(&self) -> Option<u32>;
    /// Returns the target of the record.
    fn target(&self) -> &str;
    /// Consumes this type and writes all the arguments.
    fn write_arguments<B: MutableBuffer>(
        self,
        writer: &mut Encoder<B>,
    ) -> Result<(), EncodingError>;
    /// Returns the timestamp associated to this record.
    fn timestamp(&self) -> zx::Time;
}

/// Trait implemented by complete Records.
pub trait RecordFields {
    /// Returns the record severity.
    fn severity(&self) -> u8;

    /// Returns the timestamp associated to this record.
    fn timestamp(&self) -> zx::Time;

    /// Consumes this type and writes all the arguments.
    fn write_arguments<B: MutableBuffer>(
        &self,
        writer: &mut Encoder<B>,
    ) -> Result<(), EncodingError>;
}

/// An event emitted by `tracing`.
pub struct TracingEvent<'a, S> {
    event: &'a Event<'a>,
    context: Option<Context<'a, S>>,
    metadata: StoredMetadata<'a>,
    timestamp: zx::Time,
}

// Just like Cow, but without requiring the inner type to be Clone.
enum StoredMetadata<'a> {
    Borrowed(&'a Metadata<'a>),
    Owned(Metadata<'a>),
}

impl<'a> Deref for StoredMetadata<'a> {
    type Target = Metadata<'a>;
    fn deref(&self) -> &Self::Target {
        match self {
            Self::Borrowed(meta) => meta,
            Self::Owned(meta) => meta,
        }
    }
}

impl<'a, S> TracingEvent<'a, S> {
    /// Wraps a tracing event with its associated context.
    pub fn new(event: &'a Event<'_>, context: Context<'a, S>) -> TracingEvent<'a, S> {
        Self::inner(event, Some(context))
    }

    // Just for benchmark purposes since we can't construct a Context manually.
    #[doc(hidden)]
    pub fn from_event(event: &'a Event<'_>) -> TracingEvent<'a, S> {
        Self::inner(event, None)
    }

    fn inner(event: &'a Event<'_>, context: Option<Context<'a, S>>) -> TracingEvent<'a, S> {
        // normalizing is needed to get log records to show up in trace metadata correctly
        if let Some(metadata) = event.normalized_metadata() {
            Self {
                event,
                context,
                metadata: StoredMetadata::Owned(metadata),
                timestamp: zx::Time::get_monotonic(),
            }
        } else {
            Self {
                event,
                context,
                metadata: StoredMetadata::Borrowed(event.metadata()),
                timestamp: zx::Time::get_monotonic(),
            }
        }
    }
}

impl<'a, S> RecordEvent for TracingEvent<'a, S>
where
    for<'lookup> S: Subscriber + LookupSpan<'lookup>,
{
    fn severity(&self) -> fstream::RawSeverity {
        self.metadata.raw_severity()
    }

    fn file(&self) -> Option<&str> {
        self.metadata.file()
    }

    fn line(&self) -> Option<u32> {
        self.metadata.line()
    }

    fn target(&self) -> &str {
        self.metadata.target()
    }

    fn timestamp(&self) -> zx::Time {
        self.timestamp
    }

    fn write_arguments<B: MutableBuffer>(
        self,
        writer: &mut Encoder<B>,
    ) -> Result<(), EncodingError> {
        writer.found_error = None;
        if let Some(context) = self.context {
            let span_iter =
                context.event_scope(self.event).map(Scope::from_root).into_iter().flatten();
            for span in span_iter {
                let extensions = span.extensions();
                if let Some(encoded) = extensions.get::<EncodedSpanArguments>() {
                    encoded.copy_to(writer)?;
                }
            }
        }
        self.event.record(writer);
        if let Some(err) = writer.found_error.take() {
            return Err(err);
        }
        Ok(())
    }
}

/// Arguments to create a record for testing purposes.
pub struct TestRecord<'a> {
    /// Severity of the log
    pub severity: fstream::RawSeverity,
    /// Timestamp of the test record.
    pub timestamp: zx::Time,
    /// File that emitted the log.
    pub file: Option<&'a str>,
    /// Line in the file that emitted the log.
    pub line: Option<u32>,
    /// Additional record arguments.
    pub record_arguments: Vec<Argument<'a>>,
}

impl TestRecord<'_> {
    /// Creates a test record from a record.
    pub fn from<'a>(file: &'a str, line: u32, record: &'a fstream::Record) -> TestRecord<'a> {
        TestRecord {
            severity: record.severity,
            timestamp: zx::Time::from_nanos(record.timestamp),
            file: Some(file),
            line: Some(line),
            record_arguments: record.arguments.iter().map(Argument::from).collect(),
        }
    }
}

impl RecordEvent for TestRecord<'_> {
    fn severity(&self) -> fstream::RawSeverity {
        self.severity
    }

    fn file(&self) -> Option<&str> {
        self.file
    }

    fn line(&self) -> Option<u32> {
        self.line
    }

    fn target(&self) -> &str {
        unimplemented!("Unused at the moment");
    }

    fn timestamp(&self) -> zx::Time {
        self.timestamp
    }

    fn write_arguments<B: MutableBuffer>(
        self,
        writer: &mut Encoder<B>,
    ) -> Result<(), EncodingError> {
        for argument in self.record_arguments {
            writer.write_argument(argument)?;
        }
        Ok(())
    }
}

impl RecordFields for fstream::Record {
    fn severity(&self) -> u8 {
        self.severity
    }

    fn write_arguments<B: MutableBuffer>(
        &self,
        writer: &mut Encoder<B>,
    ) -> Result<(), EncodingError> {
        for arg in &self.arguments {
            writer.write_argument(Argument::from(arg))?;
        }
        Ok(())
    }

    fn timestamp(&self) -> zx::Time {
        zx::Time::from_nanos(self.timestamp)
    }
}

impl<'a> PartialEq<fstream::Argument> for Argument<'a> {
    fn eq(&self, other: &fstream::Argument) -> bool {
        let arg = Argument::from(other);
        *self == arg
    }
}

impl<'a> From<&'a fstream::Argument> for Argument<'a> {
    fn from(arg: &'a fstream::Argument) -> Argument<'a> {
        let value = match &arg.value {
            fstream::Value::SignedInt(value) => Value::SignedInt(*value),
            fstream::Value::UnsignedInt(value) => Value::UnsignedInt(*value),
            fstream::Value::Floating(value) => Value::Floating(*value),
            fstream::Value::Text(value) => Value::Text(value.as_str()),
            fstream::Value::Boolean(value) => Value::Boolean(*value),
            _ => unreachable!("we should have covered all values"),
        };
        Argument { name: arg.name.as_str(), value }
    }
}

/// Analogous to `bytes::BufMut` with some additions to be able to write at specific offsets.
pub trait MutableBuffer {
    /// Returns the number of total bytes this container can store. Shared memory buffers are not
    /// expected to resize and this should return the same value during the entire lifetime of the
    /// buffer.
    fn capacity(&self) -> usize;

    /// Returns the current position into which the next write is expected.
    fn cursor(&self) -> usize;

    /// Advance the write cursor by `n` bytes.
    ///
    /// # Safety
    ///
    /// This is marked unsafe because a malformed caller may
    /// cause a subsequent out-of-bounds write.
    unsafe fn advance_cursor(&mut self, n: usize);

    /// Write a copy of the `src` slice into the buffer, starting at the provided offset.
    ///
    /// # Safety
    ///
    /// Implementations are not expected to bounds check the requested copy, although they may do
    /// so and still satisfy this trait's contract.
    unsafe fn put_slice_at(&mut self, src: &[u8], offset: usize);

    /// Returns whether the buffer has sufficient remaining capacity to write an incoming value.
    fn has_remaining(&self, num_bytes: usize) -> bool;

    /// Advances the write cursor without immediately writing any bytes to the buffer. The returned
    /// struct offers the ability to later write to the provided portion of the buffer.
    fn put_slot(&mut self, width: usize) -> Result<WriteSlot, EncodingError> {
        if self.has_remaining(width) {
            let slot = WriteSlot { range: self.cursor()..(self.cursor() + width) };
            unsafe {
                self.advance_cursor(width);
            }
            Ok(slot)
        } else {
            Err(EncodingError::BufferTooSmall)
        }
    }

    /// Write `src` into the provided slot that was created at a previous point in the stream.
    fn fill_slot(&mut self, slot: WriteSlot, src: &[u8]) {
        assert_eq!(
            src.len(),
            slot.range.end - slot.range.start,
            "WriteSlots can only insert exactly-sized content into the buffer"
        );
        unsafe {
            self.put_slice_at(src, slot.range.start);
        }
    }

    /// Writes the contents of the `src` buffer to `self`, starting at `self.cursor()` and
    /// advancing the cursor by `src.len()`.
    ///
    /// # Panics
    ///
    /// This function panics if there is not enough remaining capacity in `self`.
    fn put_slice(&mut self, src: &[u8]) -> Result<(), EncodingError> {
        if self.has_remaining(src.len()) {
            unsafe {
                self.put_slice_at(src, self.cursor());
                self.advance_cursor(src.len());
            }
            Ok(())
        } else {
            Err(EncodingError::NoCapacity)
        }
    }

    /// Writes an unsigned 64 bit integer to `self` in little-endian byte order.
    ///
    /// Advances the cursor by 8 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes::BufMut;
    ///
    /// let mut buf = vec![0; 8];
    /// buf.put_u64_le_at(0x0102030405060708, 0);
    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
    /// ```
    ///
    /// # Panics
    ///
    /// This function panics if there is not enough remaining capacity in `self`.
    fn put_u64_le(&mut self, n: u64) -> Result<(), EncodingError> {
        self.put_slice(&n.to_le_bytes())
    }

    /// Writes a signed 64 bit integer to `self` in little-endian byte order.
    ///
    /// The cursor position is advanced by 8.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes::BufMut;
    ///
    /// let mut buf = vec![0; 8];
    /// buf.put_i64_le_at(0x0102030405060708, 0);
    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
    /// ```
    ///
    /// # Panics
    ///
    /// This function panics if there is not enough remaining capacity in `self`.
    fn put_i64_le(&mut self, n: i64) -> Result<(), EncodingError> {
        self.put_slice(&n.to_le_bytes())
    }

    /// Writes a double-precision IEEE 754 floating point number to `self`.
    ///
    /// The cursor position is advanced by 8.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes::BufMut;
    ///
    /// let mut buf = vec![];
    /// buf.put_i64_le(0x0102030405060708);
    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
    /// ```
    ///
    /// # Panics
    ///
    /// This function panics if there is not enough remaining capacity in `self`.
    fn put_f64(&mut self, n: f64) -> Result<(), EncodingError> {
        self.put_slice(&n.to_bits().to_ne_bytes())
    }
}

/// A region of the buffer which was advanced past and can later be filled in.
#[must_use]
pub struct WriteSlot {
    range: std::ops::Range<usize>,
}

#[derive(Debug)]
struct ResizableBuffer(Vec<u8>);

impl MutableBuffer for Cursor<ResizableBuffer> {
    fn capacity(&self) -> usize {
        self.get_ref().0.len()
    }

    fn cursor(&self) -> usize {
        self.position() as usize
    }

    fn has_remaining(&self, _num_bytes: usize) -> bool {
        true
    }

    unsafe fn advance_cursor(&mut self, n: usize) {
        self.set_position(self.position() + n as u64);
    }

    unsafe fn put_slice_at(&mut self, to_put: &[u8], offset: usize) {
        let this = &mut self.get_mut().0;
        if offset < this.len() {
            let available = this.len() - offset;

            // Copy the elements that fit into the buffer.
            let min = available.min(to_put.len());
            let dest = &mut this[offset..(offset + min)];
            dest.copy_from_slice(&to_put[..min]);

            // If we couldn't fit all elements, then extend the buffer with the remaining elements.
            if available < to_put.len() {
                this.extend_from_slice(&to_put[available..]);
            }
        } else {
            // If the offset is bigger than the length, fill with zeros up to the offset and then
            // write the slice.
            this.resize(offset, 0);
            this.extend_from_slice(to_put);
        }
    }
}

impl<'a, T: MutableBuffer + ?Sized> MutableBuffer for &'a mut T {
    fn has_remaining(&self, num_bytes: usize) -> bool {
        (**self).has_remaining(num_bytes)
    }
    fn capacity(&self) -> usize {
        (**self).capacity()
    }

    fn cursor(&self) -> usize {
        (**self).cursor()
    }

    unsafe fn advance_cursor(&mut self, n: usize) {
        (**self).advance_cursor(n);
    }

    unsafe fn put_slice_at(&mut self, to_put: &[u8], offset: usize) {
        (**self).put_slice_at(to_put, offset);
    }
}

impl<T: MutableBuffer + ?Sized> MutableBuffer for Box<T> {
    fn has_remaining(&self, num_bytes: usize) -> bool {
        (**self).has_remaining(num_bytes)
    }
    fn capacity(&self) -> usize {
        (**self).capacity()
    }

    fn cursor(&self) -> usize {
        (**self).cursor()
    }

    unsafe fn advance_cursor(&mut self, n: usize) {
        (**self).advance_cursor(n);
    }

    unsafe fn put_slice_at(&mut self, to_put: &[u8], offset: usize) {
        (**self).put_slice_at(to_put, offset);
    }
}

impl MutableBuffer for Cursor<Vec<u8>> {
    fn has_remaining(&self, num_bytes: usize) -> bool {
        (self.cursor() + num_bytes) <= self.capacity()
    }

    fn capacity(&self) -> usize {
        self.get_ref().len()
    }

    fn cursor(&self) -> usize {
        self.position() as usize
    }

    unsafe fn advance_cursor(&mut self, n: usize) {
        self.set_position(self.position() + n as u64);
    }

    unsafe fn put_slice_at(&mut self, to_put: &[u8], offset: usize) {
        let dest = &mut self.get_mut()[offset..(offset + to_put.len())];
        dest.copy_from_slice(to_put);
    }
}

impl MutableBuffer for Cursor<&mut [u8]> {
    fn has_remaining(&self, num_bytes: usize) -> bool {
        (self.cursor() + num_bytes) <= self.capacity()
    }

    fn capacity(&self) -> usize {
        self.get_ref().len()
    }

    fn cursor(&self) -> usize {
        self.position() as usize
    }

    unsafe fn advance_cursor(&mut self, n: usize) {
        self.set_position(self.position() + n as u64);
    }

    unsafe fn put_slice_at(&mut self, to_put: &[u8], offset: usize) {
        let dest = &mut self.get_mut()[offset..(offset + to_put.len())];
        dest.copy_from_slice(to_put);
    }
}

impl<const N: usize> MutableBuffer for Cursor<[u8; N]> {
    fn has_remaining(&self, num_bytes: usize) -> bool {
        (self.cursor() + num_bytes) <= self.capacity()
    }
    fn capacity(&self) -> usize {
        self.get_ref().len()
    }

    fn cursor(&self) -> usize {
        self.position() as usize
    }

    unsafe fn advance_cursor(&mut self, n: usize) {
        self.set_position(self.position() + n as u64);
    }

    unsafe fn put_slice_at(&mut self, to_put: &[u8], offset: usize) {
        let dest = &mut self.get_mut()[offset..(offset + to_put.len())];
        dest.copy_from_slice(to_put);
    }
}

/// An error that occurred while encoding data to the stream format.
#[derive(Debug, Error)]
pub enum EncodingError {
    /// The provided buffer is too small.
    #[error("buffer is too small")]
    BufferTooSmall,

    /// We attempted to encode values which are not yet supported by this implementation of
    /// the Fuchsia Tracing format.
    #[error("unsupported value type")]
    Unsupported,

    /// We attempted to write to a buffer with no remaining capacity.
    #[error("the buffer has no remaining capacity")]
    NoCapacity,
}

impl From<TryFromSliceError> for EncodingError {
    fn from(_: TryFromSliceError) -> Self {
        EncodingError::BufferTooSmall
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::parse_record;
    use once_cell::sync::Lazy;
    use std::sync::Mutex;
    use tracing::info_span;
    use tracing_subscriber::{
        layer::{Layer, SubscriberExt},
        Registry,
    };

    #[fuchsia::test]
    fn build_basic_record() {
        let mut encoder = Encoder::new(Cursor::new([0u8; 1024]));
        encoder
            .write_event(WriteEventParams::<_, &str, _> {
                event: TestRecord {
                    severity: Severity::Info.into_primitive(),
                    timestamp: zx::Time::from_nanos(12345),
                    file: None,
                    line: None,
                    record_arguments: vec![],
                },
                tags: &[],
                metatags: std::iter::empty(),
                pid: zx::Koid::from_raw(0),
                tid: zx::Koid::from_raw(0),
                dropped: 0,
            })
            .expect("wrote event");
        let (record, _) = parse_record(encoder.inner().get_ref()).expect("wrote valid record");
        assert_eq!(
            record,
            fstream::Record {
                timestamp: 12345,
                severity: Severity::Info.into_primitive(),
                arguments: vec![
                    fstream::Argument {
                        name: "pid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    }
                ]
            }
        );
    }

    #[fuchsia::test]
    fn build_records_with_location() {
        let mut encoder = Encoder::new(Cursor::new([0u8; 1024]));
        encoder
            .write_event(WriteEventParams::<_, &str, _> {
                event: TestRecord {
                    severity: Severity::Error.into_primitive(),
                    timestamp: zx::Time::from_nanos(12345),
                    file: Some("foo.rs"),
                    line: Some(10),
                    record_arguments: vec![],
                },
                tags: &[],
                metatags: std::iter::empty(),
                pid: zx::Koid::from_raw(0),
                tid: zx::Koid::from_raw(0),
                dropped: 0,
            })
            .expect("wrote event");
        let (record, _) = parse_record(encoder.inner().get_ref()).expect("wrote valid record");
        assert_eq!(
            record,
            fstream::Record {
                timestamp: 12345,
                severity: Severity::Error.into_primitive(),
                arguments: vec![
                    fstream::Argument {
                        name: "pid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "file".to_string(),
                        value: fstream::Value::Text("foo.rs".into())
                    },
                    fstream::Argument {
                        name: "line".to_string(),
                        value: fstream::Value::UnsignedInt(10)
                    },
                ]
            }
        );
    }

    #[fuchsia::test]
    fn build_record_with_dropped_count() {
        let mut encoder = Encoder::new(Cursor::new([0u8; 1024]));
        encoder
            .write_event(WriteEventParams::<_, &str, _> {
                event: TestRecord {
                    severity: Severity::Warn.into_primitive(),
                    timestamp: zx::Time::from_nanos(12345),
                    file: None,
                    line: None,
                    record_arguments: vec![],
                },
                tags: &[],
                metatags: std::iter::empty(),
                pid: zx::Koid::from_raw(0),
                tid: zx::Koid::from_raw(0),
                dropped: 7,
            })
            .expect("wrote event");
        let (record, _) = parse_record(encoder.inner().get_ref()).expect("wrote valid record");
        assert_eq!(
            record,
            fstream::Record {
                timestamp: 12345,
                severity: Severity::Warn.into_primitive(),
                arguments: vec![
                    fstream::Argument {
                        name: "pid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "num_dropped".to_string(),
                        value: fstream::Value::UnsignedInt(7)
                    },
                ]
            }
        );
    }

    #[allow(dead_code)] // TODO(https://fxbug.dev/318827209)
    #[derive(Debug)]
    struct PrintMe(u32);

    #[allow(clippy::type_complexity)]
    static LAST_RECORD: Lazy<Mutex<Option<Encoder<Cursor<[u8; 1024]>>>>> =
        Lazy::new(|| Mutex::new(None));

    struct EncoderLayer;
    impl<S> Layer<S> for EncoderLayer
    where
        for<'lookup> S: Subscriber + LookupSpan<'lookup>,
    {
        fn on_event(&self, event: &Event<'_>, cx: Context<'_, S>) {
            let mut encoder = Encoder::new(Cursor::new([0u8; 1024]));
            encoder
                .write_event(WriteEventParams {
                    event: TracingEvent::new(event, cx),
                    tags: &["a-tag"],
                    metatags: [Metatag::Target].iter(),
                    pid: zx::Koid::from_raw(0),
                    tid: zx::Koid::from_raw(0),
                    dropped: 0,
                })
                .expect("wrote event");
            *LAST_RECORD.lock().unwrap() = Some(encoder);
        }

        fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
            let span = ctx.span(id).expect("Span not found, this is a bug");
            let mut extensions = span.extensions_mut();
            if extensions.get_mut::<EncodedSpanArguments>().is_none() {
                let encoded = EncodedSpanArguments::new(attrs).expect("encoded");
                extensions.insert(encoded);
            }
        }
    }

    #[test]
    fn build_record_from_tracing_event() {
        let before_timestamp = zx::Time::get_monotonic().into_nanos();
        let _s = tracing::subscriber::set_default(Registry::default().with(EncoderLayer));
        tracing::info!(
            is_a_str = "hahaha",
            is_debug = ?PrintMe(5),
            is_signed = -500,
            is_unsigned = 1000u64,
            is_bool = false,
            "blarg this is a message"
        );

        let guard = LAST_RECORD.lock().unwrap();
        let encoder = guard.as_ref().unwrap();
        let (record, _) = parse_record(encoder.inner().get_ref()).expect("wrote valid record");
        assert!(record.timestamp > before_timestamp);
        assert_eq!(
            record,
            fstream::Record {
                timestamp: record.timestamp,
                severity: Severity::Info.into_primitive(),
                arguments: vec![
                    fstream::Argument {
                        name: "pid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tag".to_string(),
                        value: fstream::Value::Text(
                            "diagnostics_log_encoding_lib_test::encode::tests".into()
                        ),
                    },
                    fstream::Argument {
                        name: "message".to_string(),
                        value: fstream::Value::Text("blarg this is a message".into())
                    },
                    fstream::Argument {
                        name: "is_a_str".to_string(),
                        value: fstream::Value::Text("hahaha".into())
                    },
                    fstream::Argument {
                        name: "is_debug".to_string(),
                        value: fstream::Value::Text("PrintMe(5)".into())
                    },
                    fstream::Argument {
                        name: "is_signed".to_string(),
                        value: fstream::Value::SignedInt(-500)
                    },
                    fstream::Argument {
                        name: "is_unsigned".to_string(),
                        value: fstream::Value::UnsignedInt(1000)
                    },
                    fstream::Argument {
                        name: "is_bool".to_string(),
                        value: fstream::Value::Boolean(false)
                    },
                    fstream::Argument {
                        name: "tag".to_string(),
                        value: fstream::Value::Text("a-tag".into(),)
                    },
                ]
            }
        );
    }

    #[test]
    fn spans_are_supported() {
        let before_timestamp = zx::Time::get_monotonic().into_nanos();
        let _s = tracing::subscriber::set_default(Registry::default().with(EncoderLayer));
        let span = info_span!("my span", tag = "span_tag", span_field = 42);
        span.in_scope(|| {
            let nested_span =
                info_span!("my other span", tag = "nested_span_tag", nested_span_field = "hello");
            nested_span.in_scope(|| {
                tracing::info!(is_bool = true, "a log in spans");
            });
        });

        let guard = LAST_RECORD.lock().unwrap();
        let encoder = guard.as_ref().unwrap();
        let (record, _) = parse_record(encoder.inner().get_ref()).expect("wrote valid record");
        assert!(record.timestamp > before_timestamp);
        assert_eq!(
            record,
            fstream::Record {
                timestamp: record.timestamp,
                severity: Severity::Info.into_primitive(),
                arguments: vec![
                    fstream::Argument {
                        name: "pid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tid".to_string(),
                        value: fstream::Value::UnsignedInt(0)
                    },
                    fstream::Argument {
                        name: "tag".to_string(),
                        value: fstream::Value::Text(
                            "diagnostics_log_encoding_lib_test::encode::tests".into()
                        ),
                    },
                    fstream::Argument {
                        name: "tag".to_string(),
                        value: fstream::Value::Text("span_tag".into(),),
                    },
                    fstream::Argument {
                        name: "span_field".to_string(),
                        value: fstream::Value::SignedInt(42),
                    },
                    fstream::Argument {
                        name: "tag".to_string(),
                        value: fstream::Value::Text("nested_span_tag".into(),),
                    },
                    fstream::Argument {
                        name: "nested_span_field".to_string(),
                        value: fstream::Value::Text("hello".into()),
                    },
                    fstream::Argument {
                        name: "message".to_string(),
                        value: fstream::Value::Text("a log in spans".into())
                    },
                    fstream::Argument {
                        name: "is_bool".to_string(),
                        value: fstream::Value::Boolean(true)
                    },
                    fstream::Argument {
                        name: "tag".to_string(),
                        value: fstream::Value::Text("a-tag".into(),)
                    },
                ]
            }
        );
    }

    #[test]
    fn resizable_vec_mutable_buffer() {
        // Putting a slice at offset=len is equivalent to concatenating.
        let mut vec = Cursor::new(ResizableBuffer(vec![1u8, 2, 3]));
        unsafe {
            vec.put_slice_at(&[4, 5, 6], 3);
        }
        assert_eq!(vec.get_ref().0, vec![1, 2, 3, 4, 5, 6]);

        // Putting a slice at an offset inside the buffer, is equivalent to replacing the items
        // there.
        let mut vec = Cursor::new(ResizableBuffer(vec![1, 3, 7, 9, 11, 13, 15]));
        unsafe {
            vec.put_slice_at(&[2, 4, 6], 2);
        }
        assert_eq!(vec.get_ref().0, vec![1, 3, 2, 4, 6, 13, 15]);

        // Putting a slice at an index in range replaces all the items and extends if needed.
        let mut vec = Cursor::new(ResizableBuffer(vec![1, 2, 3]));
        unsafe {
            vec.put_slice_at(&[4, 5, 6, 7], 0);
        }
        assert_eq!(vec.get_ref().0, vec![4, 5, 6, 7]);

        // Putting a slice at an offset beyond the buffer, fills with zeros the items in between.
        let mut vec = Cursor::new(ResizableBuffer(vec![1, 2, 3]));
        unsafe {
            vec.put_slice_at(&[4, 5, 6], 5);
        }
        assert_eq!(vec.get_ref().0, vec![1, 2, 3, 0, 0, 4, 5, 6]);
    }
}