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.
45use fuchsia_fuzzctl::OutputSink;
6use std::cell::RefCell;
7use std::env;
8use std::fmt::{Debug, Display};
9use std::io::{stdout, Write};
10use std::rc::Rc;
1112/// `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}
1819impl 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.
25pub fn new(data: Rc<RefCell<Vec<u8>>>) -> Self {
26let echo = env::var("FFX_FUZZ_TEST_ECHO_OUTPUT").is_ok();
27Self { data, echo }
28 }
29}
3031impl Clone for BufferSink {
32fn clone(&self) -> Self {
33Self { data: Rc::clone(&self.data), echo: self.echo }
34 }
35}
3637impl OutputSink for BufferSink {
38fn write_all(&self, buf: &[u8]) {
39if self.echo {
40let _ = stdout().write_all(buf);
41 }
42let mut data = self.data.borrow_mut();
43 data.extend_from_slice(buf);
44 }
4546fn print<D: Display>(&self, message: D) {
47self.write_all(message.to_string().as_bytes());
48 }
4950fn error<D: Display>(&self, message: D) {
51self.write_all(message.to_string().as_bytes());
52 }
53}