Explicitly pass stdout as output (sink) to the play function

This commit is contained in:
Marcin Kulik
2024-01-02 21:52:08 +01:00
parent 80c24abf9c
commit b2b612cd92
2 changed files with 15 additions and 11 deletions

View File

@@ -1,7 +1,7 @@
use crate::player;
use anyhow::Result;
use clap::Args;
use std::fs;
use std::{fs, io};
#[derive(Debug, Args)]
pub struct Cli {
@@ -30,7 +30,7 @@ impl Cli {
loop {
let file = fs::File::open(&self.filename)?;
player::play(file, speed, self.idle_time_limit)?;
player::play(file, io::stdout(), speed, self.idle_time_limit)?;
if !self.loop_ {
break;

View File

@@ -1,13 +1,17 @@
use crate::format::asciicast;
use anyhow::Result;
use std::io::{self, Write};
use std::io;
use std::thread;
use std::time::{Duration, Instant};
pub fn play(input: impl io::Read, speed: f64, idle_time_limit: Option<f64>) -> Result<()> {
let reader = io::BufReader::new(input);
pub fn play(
recording: impl io::Read,
mut output: impl io::Write,
speed: f64,
idle_time_limit: Option<f64>,
) -> Result<()> {
let reader = io::BufReader::new(recording);
let (header, events) = asciicast::open(reader)?;
let mut stdout = io::stdout();
let idle_time_limit = idle_time_limit
.or(header.idle_time_limit)
@@ -15,19 +19,19 @@ pub fn play(input: impl io::Read, speed: f64, idle_time_limit: Option<f64>) -> R
let events = asciicast::limit_idle_time(events, idle_time_limit);
let events = asciicast::accelerate(events, speed);
let output = asciicast::output(events);
let events = asciicast::output(events);
let epoch = Instant::now();
for o in output {
let (time, data) = o?;
for event in events {
let (time, data) = event?;
let diff = time as i64 - epoch.elapsed().as_micros() as i64;
if diff > 0 {
stdout.flush().unwrap();
output.flush()?;
thread::sleep(Duration::from_micros(diff as u64));
}
stdout.write_all(data.as_bytes())?;
output.write_all(data.as_bytes())?;
}
Ok(())