๐Ÿ“ฆ jgardona / ansistream

๐Ÿ“„ lib.rs ยท 779 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779//! # Ansi Stream
//! Write blazingly fast, free allocation ansi escape codes to a buffer, and flushes them all to any output
//! stream. Supports 8/16 colors, 256 colors, RGB color rendering output.
//!
//! ## ANSI Escape Codes for Terminal Graphics
//! The ANSI escape code standard, formally adopted as ISO/IEC 6429, defines a series of control sequences.
//! Each control sequence begins with a **Control Sequence Introducer** (CSI), defined as a scape character
//! followed immediately by a bracket: **ESC[**. In particular, a CSI followed by a certain number of "parameter bytes"
//! (ASCII 0-9:; <=>?) then the letter m forms a control sequence known as **Select Graphic Rendition** (SGR). If no
//! parameter bytes are explicitly given, then it is assumed to be 0. SGR parameters can be chained together with a semicolon **;**
//! as **delimiter**.
//!
//! Some common SGR parameters are shown below.
//!
//! |Parameter | Effect|
//! |- | -|
//! |0 | reset all SGR effects to their default|
//! |1 | bold or increased intensity|
//! |2 | faint or decreased insensity|
//! |4 | singly underlined|
//! |5 | slow blink|
//! |30-37 | foreground color (3/4 bit)|
//! |38;5;x | foreground color (256 colors, non-standard)|
//! |38;2;r;g;b | foreground color (RGB, non-standard)|
//! |40-47 | background color (8 colors)|
//! |48;5;x | background color (256 colors, non-standard)|
//! |48;2;r;g;b | background color (RGB, non-standard)|
//! |90-97 | bright foreground color (non-standard)|
//! |100-107 | bright background color (non-standard)|
//!
//! ## Examples
//!
//! * Write FC_RED attribute to stream
//!
//! ```
//! use ansistream::{FC_RED, AnsiEscapeStream};
//! use std::io::Cursor;
//! 
//! let buffer = Cursor::new(Vec::<u8>::new());
//! let mut astream = AnsiEscapeStream::new(buffer);
//! astream.write_attribute(FC_RED).unwrap();
//! // fcred escape code
//! assert_eq!(&[0x1b, 0x5b, 0x33, 0x31, 0x6d], astream.buffer());
//! ```
//!
//! * Reset an attribute in stream
//!
//! ```
//! use ansistream::{FC_RED, AnsiEscapeStream};
//! use std::io::Cursor;
//!
//! let buffer = Cursor::new(Vec::<u8>::new());
//! let mut astream = AnsiEscapeStream::new(buffer);
//! astream.reset_attribute(FC_RED).unwrap();
//! // fcred escape code
//! assert_eq!(&[0x1b, 0x5b, 0x33, 0x39, 0x6d], astream.buffer());
//! ```
//!
//! * Write formatted foreground green color text to stream.
//!
//! ```
//! use ansistream::{FC_GREEN, AnsiEscapeStream};
//! use std::io::Cursor;
//!
//! let buffer = Cursor::new(Vec::<u8>::new());
//! let mut astream = AnsiEscapeStream::new(buffer);
//! astream
//!     .write_text_fc_fmt(FC_GREEN, format_args!("123"))
//!     .unwrap();
//! // asserts that fcred was writed and also reseted with fcdefault
//! assert_eq!(
//!     &[0x1b, 0x5b, 0x33, 0x32, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x33, 0x39, 0x6d],
//!     astream.buffer()
//! );
//! ```

use std::{
    fmt::{self, Arguments},
    io::{self, BufWriter, Write},
    ops::{Deref, DerefMut},
};

/// ASCII Escape.
const ESC: u8 = 0x1b;

/// Text Styles
pub const TS_RESET_ALL: u16 = 0;
pub const TS_BOLD: u16 = 1;
pub const TS_DIM: u16 = 2;
pub const TS_ITALIC: u16 = 3;
pub const TS_UNDERLINE: u16 = 4;
pub const TS_BLINK: u16 = 5;
pub const TS_OVERLINE: u16 = 6;
pub const TS_INVERT: u16 = 7;
pub const TS_HIDDEN: u16 = 8;
pub const TS_STRIKE: u16 = 9;
pub const TS_DEFAULT: u16 = 20;
pub const TS_NO_BOLD: u16 = 21;
pub const TS_NO_DIM: u16 = 22;
pub const TS_NO_ITALIC: u16 = 0; // 23; not working
pub const TS_NO_UNDERLINE: u16 = 24;
pub const TS_NO_BLINK: u16 = 25;
pub const TS_NO_OVERLINE: u16 = 26;
pub const TS_NO_INVERT: u16 = 27;
pub const TS_NO_HIDDEN: u16 = 28;
pub const TS_NO_STRIKE: u16 = 29;
/// Foreground colors.
pub const FC_BLACK: u16 = 30;
pub const FC_RED: u16 = 31;
pub const FC_GREEN: u16 = 32;
pub const FC_BROWN: u16 = 33;
pub const FC_BLUE: u16 = 34;
pub const FC_MAGENTA: u16 = 35;
pub const FC_CYAN: u16 = 36;
pub const FC_LIGHT_GRAY: u16 = 37;
pub const FC_RICH_COLORS: u16 = 38; // requires additional parameters(s)
pub const FC_DEFAULT: u16 = 39;
pub const FC_DARK_GRAY: u16 = 90;
pub const FC_LIGHT_RED: u16 = 91;
pub const FC_LIGHT_GREEN: u16 = 92;
pub const FC_YELLOW: u16 = 93;
pub const FC_LIGHT_BLUE: u16 = 94;
pub const FC_LIGHT_MAGENTA: u16 = 95;
pub const FC_LIGHT_CYAN: u16 = 96;
pub const FC_WHITE: u16 = 97;

/// Background colors.
pub const BC_BLACK: u16 = 40;
pub const BC_RED: u16 = 41;
pub const BC_GREEN: u16 = 42;
pub const BC_BROWN: u16 = 43;
pub const BC_BLUE: u16 = 44;
pub const BC_MAGENTA: u16 = 45;
pub const BC_CYAN: u16 = 46;
pub const BC_LIGHT_GRAY: u16 = 47;
pub const BC_RICH_COLORS: u16 = 48; // requires additional parameter(s)
pub const BC_DEFAULT: u16 = 49;
pub const BC_DARK_GRAY: u16 = 100;
pub const BC_LIGHT_RED: u16 = 101;
pub const BC_LIGHT_GREEN: u16 = 102;
pub const BC_YELLOW: u16 = 103;
pub const BC_LIGHT_BLUE: u16 = 104;
pub const BC_LIGHT_MAGENTA: u16 = 105;
pub const BC_LIGHT_CYAN: u16 = 106;
pub const BC_WHITE: u16 = 107;

/// Data structure used to do fast ansi escape write operations.
/// It implements many methods and traits which makes easier to format text.
/// An internal buffer can be preallocated, which avoids allocation using write operations.
#[derive(Debug)]
pub struct AnsiEscapeStream<W: Write> {
    buffer: BufWriter<W>,
}

impl<W: Write> AnsiEscapeStream<W> {
    /// Initializes an AnsiEscapeStream.\
    /// writer is any struct which can implement Write trait.
    pub fn new(writer: W) -> Self {
        Self {
            buffer: BufWriter::new(writer),
        }
    }

    /// Clear the internal buffer.\
    /// The buffer position is updated to 0, and all data is cleared. The capacity remains the same.
    // pub fn clear(&mut self) {
    //     self.buffer.set_position(0);
    //     self.buffer.get_mut().clear();
    // }

    // /// Set the internal buffer position to 0.
    // pub fn reset(&mut self) {
    //     self.buffer.set_position(0);
    // }

    /// Reset all ansi escape code attributes before this buffer position using ESC[0m.
    pub fn reset_all_attributes(&mut self) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[0m")?;
        Ok(())
    }

    /// Reset an attribute of type(FC, BC, TS). If the attribute is a foreground color, then
    /// reset it to the default foreground color, and so on.
    pub fn reset_attribute(&mut self, attr: u16) -> io::Result<()> {
        match attr {
            TS_BOLD => self.write_attribute(TS_NO_BOLD)?,
            TS_DIM => self.write_attribute(TS_NO_DIM)?,
            TS_ITALIC => self.write_attribute(TS_NO_ITALIC)?,
            TS_UNDERLINE => self.write_attribute(TS_NO_UNDERLINE)?,
            TS_BLINK => self.write_attribute(TS_NO_BLINK)?,
            TS_OVERLINE => self.write_attribute(TS_NO_OVERLINE)?,
            TS_INVERT => self.write_attribute(TS_NO_INVERT)?,
            TS_HIDDEN => self.write_attribute(TS_NO_HIDDEN)?,
            TS_STRIKE => self.write_attribute(TS_NO_STRIKE)?,
            FC_RICH_COLORS => self.write_attribute(FC_DEFAULT)?,
            BC_RICH_COLORS => self.write_attribute(BC_DEFAULT)?,
            30..=37 | 90..=97 => self.write_attribute(FC_DEFAULT)?,
            40..=47 | 100..=107 => self.write_attribute(BC_DEFAULT)?,
            _ => self.write_attribute(TS_DEFAULT)?,
        };

        Ok(())
    }

    /// Write a byte slice to stream.
    pub fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        self.buffer.write(buffer)
    }

    /// Write an attribute to stream.
    pub fn write_attribute(&mut self, attr: u16) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{attr}m")?;
        Ok(())
    }

    /// Write a string to stream.
    pub fn write_string(&mut self, text: &str) -> io::Result<usize> {
        self.buffer.write(text.as_bytes())
    }

    /// Write a 16 formatted foreground color text to stream. The attribute is reseted at the end of operation.
    ///
    /// # Examples
    ///
    /// ```
    /// use ansistream::{FC_GREEN, AnsiEscapeStream};
    /// use std::io::Cursor;
    ///         
    /// let buffer = Cursor::new(Vec::<u8>::new());
    /// let mut astream = AnsiEscapeStream::new(buffer);
    /// astream
    ///   .write_text_fc_fmt(FC_GREEN, format_args!("123"))
    ///   .unwrap();
    /// // asserts that fgreen was writed and also reseted with fcdefault
    /// assert_eq!(
    ///     &[0x1b, 0x5b, 0x33, 0x32, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x33, 0x39, 0x6d],
    ///     astream.buffer()
    /// );
    /// ```
    pub fn write_text_fc_fmt(&mut self, color: u16, fmt: fmt::Arguments<'_>) -> io::Result<()> {
        match color {
            40..=47 | 100..=107 => {
                self.write_attribute(color - 10)?;
                write!(self.buffer, "{fmt}")?;
                self.reset_attribute(color - 10)?;
            }
            _ => {
                self.write_attribute(color)?;
                write!(self.buffer, "{fmt}")?;
                self.reset_attribute(color)?;
            }
        };

        Ok(())
    }

    /// Write a 16 formatted background color text to stream. The attribute is reseted at the end of operation.
    ///
    /// # Examples
    ///
    /// ```
    /// use ansistream::{BC_GREEN, AnsiEscapeStream};
    /// use std::io::Cursor;
    ///
    /// let buffer = Cursor::new(Vec::<u8>::new());
    /// let mut astream = AnsiEscapeStream::new(buffer);
    /// astream
    ///     .write_text_bc_fmt(BC_GREEN, format_args!("123"))
    ///     .unwrap();
    /// // asserts that bcgreen was writed and also reseted with bcdefault
    /// assert_eq!(
    ///     &[0x1b, 0x5b, 0x34, 0x32, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x34, 0x39, 0x6d],
    ///     astream.buffer()
    /// );
    ///
    /// ```
    pub fn write_text_bc_fmt(&mut self, color: u16, fmt: Arguments<'_>) -> io::Result<()> {
        match color {
            30..=37 | 90..=97 => {
                self.write_attribute(color + 10)?;
                write!(self.buffer, "{fmt}")?;
                self.reset_attribute(color + 10)?;
            }
            _ => {
                self.write_attribute(color)?;
                write!(self.buffer, "{fmt}")?;
                self.reset_attribute(color)?;
            }
        };

        Ok(())
    }

    /// Write 16 foregournd and background color text to stream. If the text is
    /// empty, the reset operation will not be performed. Only the codes from foreground
    /// and backround color are reseted.
    pub fn write_text_color(
        &mut self,
        foreground: u16,
        background: u16,
        text: &str,
    ) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{foreground};{background}m{text}")?;
        if !text.is_empty() {
            self.reset_attribute(foreground)?;
            self.reset_attribute(background)?;
        }
        Ok(())
    }

    /// Write 16 foreground and background color formatted text to stream.
    /// Only the codes from foreground and background are reset.
    pub fn write_text_color_fmt(
        &mut self,
        foreground: u16,
        background: u16,
        fmt: fmt::Arguments<'_>,
    ) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{foreground};{background}m{fmt}")?;
        self.reset_attribute(foreground)?;
        self.reset_attribute(background)?;
        Ok(())
    }

    /// Write 256 foreground color text to the stream. If the text is empty, the
    /// reset operation will not be performed.
    pub fn write_text_fc256(&mut self, color: u16, text: &str) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{FC_RICH_COLORS};5;{color}m{text}")?;
        if !text.is_empty() {
            self.reset_attribute(FC_RICH_COLORS)?;
        }
        Ok(())
    }

    /// Write 256 foreground color formatted text to the stream. A partial reset operation of used codes
    /// will be performed.
    pub fn write_text_fc256_fmt(&mut self, color: u16, fmt: fmt::Arguments<'_>) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{FC_RICH_COLORS};5;{color}m{fmt}")?;
        self.reset_attribute(FC_RICH_COLORS)?;
        Ok(())
    }

    /// Write 256 background color text to the stream. If the text is empty, the
    /// reset operation will not be performed.
    pub fn write_text_bc256(&mut self, color: u16, text: &str) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{BC_RICH_COLORS};5;{color}m{text}")?;
        if !text.is_empty() {
            self.reset_attribute(BC_RICH_COLORS)?;
        }
        Ok(())
    }

    /// Write 256 background color formatted text to the stream. A partial reset operation of used codes
    /// will be performed.
    pub fn write_text_bc256_fmt(&mut self, color: u16, fmt: fmt::Arguments<'_>) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{BC_RICH_COLORS};5;{color}m{fmt}")?;
        self.reset_attribute(BC_RICH_COLORS)?;
        Ok(())
    }

    /// Write RGB foreground color text to the stream. If the text is empty, the
    /// reset operation will not be performed.
    pub fn write_text_fcrgb(&mut self, r: u16, g: u16, b: u16, text: &str) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{FC_RICH_COLORS};2;{r};{g};{b}m{text}")?;
        if !text.is_empty() {
            self.reset_attribute(FC_RICH_COLORS)?;
        }
        Ok(())
    }

    /// Write RGB formatted foreground color text to the stream. A partial reset operation
    /// is performed.
    pub fn write_text_fcrgb_fmt(
        &mut self,
        r: u16,
        g: u16,
        b: u16,
        fmt: fmt::Arguments<'_>,
    ) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{FC_RICH_COLORS};2;{r};{g};{b}m{fmt}")?;
        self.reset_attribute(FC_RICH_COLORS)?;
        Ok(())
    }

    /// Write RGB background color text to the stream. If the text is empty, the
    /// reset operation will not be performed.
    pub fn write_text_bcrgb(&mut self, r: u16, g: u16, b: u16, text: &str) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{BC_RICH_COLORS};2;{r};{g};{b}m{text}")?;
        if !text.is_empty() {
            self.reset_attribute(BC_RICH_COLORS)?;
        }
        Ok(())
    }

    /// Write formatted RGB background color text to the stream. A partial reset operation is performed.
    pub fn write_text_bcrgb_fmt(
        &mut self,
        r: u16,
        g: u16,
        b: u16,
        fmt: fmt::Arguments<'_>,
    ) -> io::Result<()> {
        self.buffer.write_all(&[ESC])?;
        write!(self.buffer, "[{BC_RICH_COLORS};2;{r};{g};{b}m{fmt}")?;
        self.reset_attribute(BC_RICH_COLORS)?;
        Ok(())
    }
}

impl<W: Write> Deref for AnsiEscapeStream<W> {
    type Target = BufWriter<W>;

    fn deref(&self) -> &Self::Target {
        &self.buffer
    }
}

impl<W: Write> DerefMut for AnsiEscapeStream<W> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.buffer
    }
}

impl<T, W: Write> AsMut<T> for AnsiEscapeStream<W>
where
    <AnsiEscapeStream<W> as Deref>::Target: AsMut<T>,
{
    fn as_mut(&mut self) -> &mut T {
        self.deref_mut().as_mut()
    }
}

impl<T, W: Write> AsRef<T> for AnsiEscapeStream<W>
where
    T: ?Sized,
    <AnsiEscapeStream<W> as Deref>::Target: AsRef<T>,
{
    fn as_ref(&self) -> &T {
        self.deref().as_ref()
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Cursor, Write};

    use super::*;

    #[test]
    fn test_write_bytes() {
        // write bytes to stream using byte string literal aka. b.
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.write(b"abcde").unwrap();

        let result = String::from_utf8_lossy(astream.buffer());
        assert_eq!("abcde", result);

        // write byes to stream using an array
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        let arr = [1, 2, 3, 4, 5];
        astream.write(&arr).unwrap();
        let vec = astream.buffer();
        assert_eq!(&arr, vec);

        // // write a vector to stream
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        let vec = vec![1, 2, 3, 4, 5];
        astream.write(&vec).unwrap();
        assert_eq!(&vec, astream.buffer());
    }

    #[test]
    fn test_write_attribute_function() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.write_attribute(FC_RED).unwrap();
        // fcred escape code
        let vec = astream.buffer();
        assert_eq!(&[0x1b, 0x5b, 0x33, 0x31, 0x6d], vec);
    }

    #[test]
    fn test_reset_attibute_function() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.reset_attribute(FC_RED).unwrap();
        // fcred escape code
        let vec = astream.buffer();
        assert_eq!(&[0x1b, 0x5b, 0x33, 0x39, 0x6d], vec);
    }

    #[test]
    fn test_drefmut_implementation() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        write!(&mut *astream, " ").unwrap();
        assert_eq!(&[0x20], astream.buffer());
    }

    #[test]
    fn test_write_text_fc_fmt_function() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream
            .write_text_fc_fmt(FC_GREEN, format_args!("123"))
            .unwrap();
        // asserts that fcred was writed and also reseted with fcdefault
        assert_eq!(
            &[0x1b, 0x5b, 0x33, 0x32, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x33, 0x39, 0x6d],
            astream.buffer()
        );

        astream.flush().unwrap();

        // asserts that if we use a background color, write_text_color will convert it to foreground color
        astream
            .write_text_fc_fmt(BC_YELLOW, format_args!("123"))
            .unwrap();
        assert_eq!(
            &[0x1b, 0x5b, 0x39, 0x33, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x33, 0x39, 0x6d],
            astream.buffer()
        )
    }

    #[test]
    fn test_write_text_bc_fmt_function() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream
            .write_text_bc_fmt(BC_GREEN, format_args!("123"))
            .unwrap();
        // asserts that bcgreen was writed and also reseted with bcdefault
        assert_eq!(
            &[0x1b, 0x5b, 0x34, 0x32, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x34, 0x39, 0x6d],
            astream.buffer()
        );

        astream.flush().unwrap();

        // asserts that if we use a foreground color, write_text_bc will convert it to background color
        astream
            .write_text_bc_fmt(FC_YELLOW, format_args!("123"))
            .unwrap();
        assert_eq!(
            &[0x1b, 0x5b, 0x31, 0x30, 0x33, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x34, 0x39, 0x6d],
            astream.buffer()
        )
    }

    #[test]
    fn test_write_text_color_function() {
        // test not reset scenario
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream
            .write_text_color(FC_MAGENTA, BC_DARK_GRAY, "")
            .unwrap();
        assert_eq!(
            &[0x1b, 0x5b, 0x33, 0x35, 0x3b, 0x31, 0x30, 0x30, 0x6d],
            astream.buffer()
        );

        astream.flush().unwrap();
        // test reset all scenario
        astream
            .write_text_color(FC_MAGENTA, BC_DARK_GRAY, "012")
            .unwrap();
        assert_eq!(
            &[
                0x1b, 0x5b, 0x33, 0x35, 0x3b, 0x31, 0x30, 0x30, 0x6d, 0x30, 0x31, 0x32, 0x1b, 0x5b,
                0x33, 0x39, 0x6d, 0x1b, 0x5b, 0x34, 0x39, 0x6d
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_fc256_function() {
        // test not reseting scenario
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.write_text_fc256(FC_BLUE, "").unwrap();
        assert_eq!(
            &[0x1b, 0x5b, 0x33, 0x38, 0x3b, 0x35, 0x3b, 0x33, 0x34, 0x6d],
            astream.buffer()
        );
        astream.flush().unwrap();

        // test reseting scenario
        astream.write_text_fc256(FC_BLUE, "012").unwrap();
        assert_eq!(
            &[
                0x1b, 0x5b, 0x33, 0x38, 0x3b, 0x35, 0x3b, 0x33, 0x34, 0x6d, 0x30, 0x31, 0x32, 0x1b,
                0x5b, 0x33, 0x39, 0x6d
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_bc256_function() {
        // test not reseting scenario
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.write_text_bc256(BC_BLUE, "").unwrap();
        assert_eq!(
            &[0x1b, 0x5b, 0x34, 0x38, 0x3b, 0x35, 0x3b, 0x34, 0x34, 0x6d],
            astream.buffer()
        );
        astream.flush().unwrap();

        // test reseting scenario
        astream.write_text_bc256(BC_BLUE, "012").unwrap();
        assert_eq!(
            &[
                0x1b, 0x5b, 0x34, 0x38, 0x3b, 0x35, 0x3b, 0x34, 0x34, 0x6d, 0x30, 0x31, 0x32, 0x1b,
                0x5b, 0x34, 0x39, 0x6d
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_fcrgb() {
        // test not reseting scenario
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.write_text_fcrgb(255, 255, 255, "").unwrap();
        assert_eq!(
            &[
                27, 91, 0x33, 0x38, 59, 0x32, 59, 0x32, 0x35, 0x35, 59, 0x32, 0x35, 0x35, 59, 0x32,
                0x35, 0x35, 109
            ],
            astream.buffer()
        );
        astream.flush().unwrap();

        // test reseting scenario
        astream.write_text_fcrgb(255, 255, 255, "012").unwrap();
        assert_eq!(
            &[
                27, 91, 0x33, 0x38, 59, 0x32, 59, 0x32, 0x35, 0x35, 59, 0x32, 0x35, 0x35, 59, 0x32,
                0x35, 0x35, 109, 0x30, 0x31, 0x32, 27, 91, 0x33, 0x39, 109
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_bcrgb() {
        // test not reseting scenario
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);
        astream.write_text_bcrgb(255, 255, 255, "").unwrap();
        assert_eq!(
            &[
                27, 91, 0x34, 0x38, 59, 0x32, 59, 0x32, 0x35, 0x35, 59, 0x32, 0x35, 0x35, 59, 0x32,
                0x35, 0x35, 109
            ],
            astream.buffer()
        );
        astream.flush().unwrap();

        // test reseting scenario
        astream.write_text_bcrgb(255, 255, 255, "012").unwrap();
        assert_eq!(
            &[
                27, 91, 0x34, 0x38, 59, 0x32, 59, 0x32, 0x35, 0x35, 59, 0x32, 0x35, 0x35, 59, 0x32,
                0x35, 0x35, 109, 0x30, 0x31, 0x32, 27, 91, 0x34, 0x39, 109
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_color_fmt() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);

        // test reset all scenario
        astream
            .write_text_color_fmt(FC_MAGENTA, BC_DARK_GRAY, format_args!("012"))
            .unwrap();
        assert_eq!(
            &[
                0x1b, 0x5b, 0x33, 0x35, 0x3b, 0x31, 0x30, 0x30, 0x6d, 0x30, 0x31, 0x32, 0x1b, 0x5b,
                0x33, 0x39, 0x6d, 0x1b, 0x5b, 0x34, 0x39, 0x6d
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_fc256_fmt() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);

        // test reseting scenario
        astream
            .write_text_fc256_fmt(FC_BLUE, format_args!("012"))
            .unwrap();
        assert_eq!(
            &[
                0x1b, 0x5b, 0x33, 0x38, 0x3b, 0x35, 0x3b, 0x33, 0x34, 0x6d, 0x30, 0x31, 0x32, 0x1b,
                0x5b, 0x33, 0x39, 0x6d
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_bc256_fmt() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);

        // test reseting scenario
        astream
            .write_text_bc256_fmt(BC_BLUE, format_args!("012"))
            .unwrap();
        assert_eq!(
            &[
                0x1b, 0x5b, 0x34, 0x38, 0x3b, 0x35, 0x3b, 0x34, 0x34, 0x6d, 0x30, 0x31, 0x32, 0x1b,
                0x5b, 0x34, 0x39, 0x6d
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_fcrgb_fmt() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);

        // test reseting scenario
        astream
            .write_text_fcrgb_fmt(255, 255, 255, format_args!("012"))
            .unwrap();
        assert_eq!(
            &[
                27, 91, 0x33, 0x38, 59, 0x32, 59, 0x32, 0x35, 0x35, 59, 0x32, 0x35, 0x35, 59, 0x32,
                0x35, 0x35, 109, 0x30, 0x31, 0x32, 27, 91, 0x33, 0x39, 109
            ],
            astream.buffer()
        );
    }

    #[test]
    fn test_write_text_bcrgb_fmt() {
        let c = Cursor::new(Vec::<u8>::new());
        let mut astream = AnsiEscapeStream::new(c);

        // test reseting scenario
        astream
            .write_text_bcrgb_fmt(255, 255, 255, format_args!("012"))
            .unwrap();
        assert_eq!(
            &[
                27, 91, 0x34, 0x38, 59, 0x32, 59, 0x32, 0x35, 0x35, 59, 0x32, 0x35, 0x35, 59, 0x32,
                0x35, 0x35, 109, 0x30, 0x31, 0x32, 27, 91, 0x34, 0x39, 109
            ],
            astream.buffer()
        );
    }
}