Skip to content

Commit

Permalink
Merge pull request #5 from jnises/strip-incoming-escapes
Browse files Browse the repository at this point in the history
Strip incoming escapes
  • Loading branch information
jnises authored Nov 11, 2023
2 parents 0cef13d + 4996009 commit 2ea8f9b
Show file tree
Hide file tree
Showing 5 changed files with 396 additions and 57 deletions.
246 changes: 245 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
[package]
name = "colight"
version = "0.1.0"
version = "0.2.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.72"
clap = { version = "4.4.8", features = ["derive"] }
colorous = "1.0.12"
scopeguard = "1.2.0"
strip-ansi-escapes = "0.2.0"
termcolor = "1.2.0"
73 changes: 73 additions & 0 deletions src/ansi_stripper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/// TODO: there is a better standard way of doing this right?
use std::{
cell::RefCell,
collections::VecDeque,
io::{Read, Write},
rc::Rc,
};

struct ReadHalf(Rc<RefCell<VecDeque<u8>>>);

impl Read for ReadHalf {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.borrow_mut().read(buf)
}
}

struct WriteHalf(Rc<RefCell<VecDeque<u8>>>);

impl Write for WriteHalf {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.borrow_mut().extend(buf);
Ok(buf.len())
}

fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

fn make_read_writer() -> (ReadHalf, WriteHalf) {
let buf = Rc::new(RefCell::new(VecDeque::new()));
(ReadHalf(buf.clone()), WriteHalf(buf))
}

pub(crate) struct AnsiStripReader<R> {
input: R,
buf: ReadHalf,
stripper: strip_ansi_escapes::Writer<WriteHalf>,
}

impl<R> AnsiStripReader<R> {
pub(crate) fn new(input: R) -> Self {
let (buf, writer) = make_read_writer();
let stripper = strip_ansi_escapes::Writer::new(writer);
Self {
input,
buf,
stripper,
}
}
}

impl<R> Read for AnsiStripReader<R>
where
R: Read,
{
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
match self.buf.read(buf)? {
0 => {
let mut input_buf = [0; 64];
match self.input.read(&mut input_buf)? {
0 => return Ok(0),
n => {
self.stripper.write_all(&input_buf[..n])?;
}
}
}
n => return Ok(n),
}
}
}
}
Loading

0 comments on commit 2ea8f9b

Please sign in to comment.