fxt/
fxt_builder.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4use thiserror::Error;
5
6#[derive(Clone)]
7pub struct FxtBuilder<H> {
8    header: H,
9    buf: Vec<u8>,
10}
11
12#[derive(Error, Debug)]
13pub enum SerializeError {
14    #[error("Encountered Empty StringRefs when serializing argument's name")]
15    MissingArgName,
16}
17
18impl<H: crate::header::TraceHeader> FxtBuilder<H> {
19    /// Start a new fxt record with a typed header. The header should be completely configured for
20    /// the corresponding record except for its size in words which will be updated by the builder.
21    pub fn new(mut header: H) -> Self {
22        // Make space for our header word before anything gets added.
23        let buf = vec![0; 8];
24
25        // Set an initial size, we'll update as we go.
26        header.set_size_words(1);
27
28        Self { header, buf }
29    }
30
31    pub fn atom(mut self, atom: impl AsRef<[u8]>) -> Self {
32        self.buf.extend(atom.as_ref());
33        for _ in 0..crate::word_padding(self.buf.len()) {
34            self.buf.push(0);
35        }
36        assert_eq!(self.buf.len() % 8, 0, "buffer should be word-aligned after adding padding");
37        assert!(self.buf.len() < 32_768, "maximum record size is 32kb");
38        let size_words: u16 =
39            (self.buf.len() / 8).try_into().expect("trace records size in words must fit in a u16");
40        self.header.set_size_words(size_words);
41        self
42    }
43
44    /// Return the bytes of a possibly-valid fxt record with the header in place.
45    pub fn build(mut self) -> Vec<u8> {
46        self.buf[..8].copy_from_slice(&self.header.to_le_bytes());
47        self.buf
48    }
49}
50
51impl<H: std::fmt::Debug> std::fmt::Debug for FxtBuilder<H> {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        // Print in word-aligned chunks, exclude the zeroes we keep for the header.
54        let chunks = self.buf.chunks_exact(8).skip(1).collect::<Vec<_>>();
55        f.debug_struct("FxtBuilder").field("header", &self.header).field("buf", &chunks).finish()
56    }
57}