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.
4
5#[derive(Clone)]
6pub(crate) struct FxtBuilder<H> {
7    header: H,
8    buf: Vec<u8>,
9}
10
11impl<H: crate::header::TraceHeader> FxtBuilder<H> {
12    /// Start a new fxt record with a typed header. The header should be completely configured for
13    /// the corresponding record except for its size in words which will be updated by the builder.
14    pub fn new(mut header: H) -> Self {
15        // Make space for our header word before anything gets added.
16        let buf = vec![0; 8];
17
18        // Set an initial size, we'll update as we go.
19        header.set_size_words(1);
20
21        Self { header, buf }
22    }
23
24    pub fn atom(mut self, atom: impl AsRef<[u8]>) -> Self {
25        self.buf.extend(atom.as_ref());
26        for _ in 0..crate::word_padding(self.buf.len()) {
27            self.buf.push(0);
28        }
29        assert_eq!(self.buf.len() % 8, 0, "buffer should be word-aligned after adding padding");
30        assert!(self.buf.len() < 32_768, "maximum record size is 32kb");
31        let size_words: u16 =
32            (self.buf.len() / 8).try_into().expect("trace records size in words must fit in a u16");
33        self.header.set_size_words(size_words);
34        self
35    }
36
37    /// Return the bytes of a possibly-valid fxt record with the header in place.
38    pub fn build(mut self) -> Vec<u8> {
39        self.buf[..8].copy_from_slice(&self.header.to_le_bytes());
40        self.buf
41    }
42}
43
44impl<H: std::fmt::Debug> std::fmt::Debug for FxtBuilder<H> {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        // Print in word-aligned chunks, exclude the zeroes we keep for the header.
47        let chunks = self.buf.chunks_exact(8).skip(1).collect::<Vec<_>>();
48        f.debug_struct("FxtBuilder").field("header", &self.header).field("buf", &chunks).finish()
49    }
50}