ansi_to_tui/
lib.rs

1#![allow(unused_imports)]
2#![warn(missing_docs)]
3//! Parses a `Vec<u8>` as an byte sequence with ansi colors to
4//! [`tui::text::Text`][Text].  
5//!
6//! Invalid ansi colors / sequences will be ignored.  
7//!
8//!
9//! Supported features
10//! - UTF-8 using `String::from_utf8` or [`simdutf8`][simdutf8].
11//! - Most stuff like **Bold** / *Italic* / <u>Underline</u> / ~~Strikethrough~~.
12//! - Supports 4-bit color palletes.
13//! - Supports 8-bit color.
14//! - Supports True color ( RGB / 24-bit color ).
15//!
16//!
17//! ## Example
18//! The argument to the function `ansi_to_text` implements `IntoIterator` so it will be consumed on
19//! use.
20//! ```rust
21//! # fn doctest() -> eyre::Result<()> {
22//! use ansi_to_tui::IntoText as _;
23//! let bytes = b"\x1b[38;2;225;192;203mAAAAA\x1b[0m".to_owned().to_vec();
24//! let text = bytes.into_text()?;
25//! # Ok(()) }
26//! ```
27//! Example parsing from a file.
28//! ```rust
29//! # fn doctest() -> eyre::Result<()> {
30//! use ansi_to_tui::IntoText as _;
31//! let buffer = std::fs::read("ascii/text.ascii")?;
32//! let text = buffer.into_text()?;
33//! # Ok(()) }
34//! ```
35//!
36//! If you want to use [`simdutf8`][simdutf8] instead of `String::from_utf8()`  
37//! for parsing UTF-8 then enable optional feature `simd`  
38//!  
39//! [Text]: https://docs.rs/tui/0.15.0/tui/text/struct.Text.html
40//! [ansi-to-tui]: https://github.com/uttarayan21/ansi-to-tui
41//! [simdutf8]: https://github.com/rusticstuff/simdutf8
42
43// mod ansi;
44mod code;
45mod error;
46mod parser;
47pub use error::Error;
48use ratatui_core::text::Text;
49
50/// IntoText will convert any type that has a AsRef<[u8]> to a Text.
51pub trait IntoText {
52    /// Convert the type to a Text.
53    #[allow(clippy::wrong_self_convention)]
54    fn into_text(&self) -> Result<Text<'static>, Error>;
55    /// Convert the type to a Text while trying to copy as less as possible
56    #[cfg(feature = "zero-copy")]
57    fn to_text(&self) -> Result<Text<'_>, Error>;
58}
59impl<T> IntoText for T
60where
61    T: AsRef<[u8]>,
62{
63    fn into_text(&self) -> Result<Text<'static>, Error> {
64        Ok(crate::parser::text(self.as_ref())?.1)
65    }
66
67    #[cfg(feature = "zero-copy")]
68    fn to_text(&self) -> Result<Text<'_>, Error> {
69        Ok(crate::parser::text_fast(self.as_ref())?.1)
70    }
71}