1use crate::*;
2use std::{fs, io, path::Path, time::Duration};
3
4bach::scope::define!(scope, Box<dyn io::Write>);
5
6pub fn set_file(path: &Path) {
7 let file = fs::File::create(path).unwrap();
8 let file = io::BufWriter::new(file);
9 let output = Box::new(file);
10 scope::set(Some(output));
11}
12
13pub fn set_stdout() {
14 let io = io::stdout();
15 let output = Box::new(io);
16 scope::set(Some(output));
17}
18
19pub fn emit<M: Codec + fmt::Display>(message: M) {
20 scope::try_borrow_mut_with(|output| {
21 if let Some(output) = output.as_mut() {
22 message.encode(output).unwrap();
23 } else {
24 println!("{}", message);
25 }
26 });
27}
28
29pub fn create_group(id: u64, name: String) {
30 emit(CreateGroup { id, name });
31}
32
33pub fn advance_time(ticks: u64) {
34 emit(AdvanceTime { ticks })
35}
36
37pub fn set_tick_duration(duration: Duration) {
38 emit(SetNanosPerTick {
39 nanos: duration.as_nanos() as _,
40 })
41}
42
43pub fn flush() {
44 scope::try_borrow_mut_with(|output| {
45 if let Some(output) = output.as_mut() {
46 output.flush().unwrap();
47 }
48 });
49}
50
51pub fn finish() {
52 flush();
53 }
55
56pub fn init_buffer(source: String, meta: &Path) {
57 let meta = meta.to_string_lossy().to_string();
58 emit(InitBuffer { source, meta });
59}