fuchsia_fuzzctl_test/
writer.rs

1// Copyright 2022 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
5use fuchsia_fuzzctl::OutputSink;
6use std::cell::RefCell;
7use std::env;
8use std::fmt::{Debug, Display};
9use std::io::{stdout, Write};
10use std::rc::Rc;
11
12/// `BufferSink` saves its output in a buffer and can verify it against expected output.
13#[derive(Debug)]
14pub struct BufferSink {
15    data: Rc<RefCell<Vec<u8>>>,
16    echo: bool,
17}
18
19impl BufferSink {
20    ///.Creates a `BufferSink`.
21    ///
22    /// This object will write into the shared `data` vector. When running tests, users may
23    /// optional set the FFX_FUZZ_TEST_ECHO_OUTPUT environment variable, which will cause this
24    /// object to copy anything written to it to standard output.
25    pub fn new(data: Rc<RefCell<Vec<u8>>>) -> Self {
26        let echo = env::var("FFX_FUZZ_TEST_ECHO_OUTPUT").is_ok();
27        Self { data, echo }
28    }
29}
30
31impl Clone for BufferSink {
32    fn clone(&self) -> Self {
33        Self { data: Rc::clone(&self.data), echo: self.echo }
34    }
35}
36
37impl OutputSink for BufferSink {
38    fn write_all(&self, buf: &[u8]) {
39        if self.echo {
40            let _ = stdout().write_all(buf);
41        }
42        let mut data = self.data.borrow_mut();
43        data.extend_from_slice(buf);
44    }
45
46    fn print<D: Display>(&self, message: D) {
47        self.write_all(message.to_string().as_bytes());
48    }
49
50    fn error<D: Display>(&self, message: D) {
51        self.write_all(message.to_string().as_bytes());
52    }
53}