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.
45#[derive(Clone)]
6pub(crate) struct FxtBuilder<H> {
7 header: H,
8 buf: Vec<u8>,
9}
1011impl<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.
14pub fn new(mut header: H) -> Self {
15// Make space for our header word before anything gets added.
16let buf = vec![0; 8];
1718// Set an initial size, we'll update as we go.
19header.set_size_words(1);
2021Self { header, buf }
22 }
2324pub fn atom(mut self, atom: impl AsRef<[u8]>) -> Self {
25self.buf.extend(atom.as_ref());
26for _ in 0..crate::word_padding(self.buf.len()) {
27self.buf.push(0);
28 }
29assert_eq!(self.buf.len() % 8, 0, "buffer should be word-aligned after adding padding");
30assert!(self.buf.len() < 32_768, "maximum record size is 32kb");
31let size_words: u16 =
32 (self.buf.len() / 8).try_into().expect("trace records size in words must fit in a u16");
33self.header.set_size_words(size_words);
34self
35}
3637/// Return the bytes of a possibly-valid fxt record with the header in place.
38pub fn build(mut self) -> Vec<u8> {
39self.buf[..8].copy_from_slice(&self.header.to_le_bytes());
40self.buf
41 }
42}
4344impl<H: std::fmt::Debug> std::fmt::Debug for FxtBuilder<H> {
45fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46// Print in word-aligned chunks, exclude the zeroes we keep for the header.
47let 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}