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
//! This is documentation for the `buffer` module.
//!
//! buffer has access to the objects that can store and use the strings provided by the end user.
//!
//! # Examples
//! ```
//! use console_tester::buffer::TermWriter;
//! use std::io::Write;
//! let mut term_writer: TermWriter = TermWriter::new();
//! term_writer.write(b"Hello");
//! term_writer.flush();
//! ```

use crate::reg::{
    compare,
    ErrorList::{EmptyVec, UncappedEscape},
};
use crate::term::TermStrings;
use std::fmt::Debug;
use std::io::Write;

/// TermWriter Object that holds character array buffer
#[derive(Debug, Clone)]
pub struct TermWriter {
    writer: Vec<u8>,
}

/// 'Write' trait implementation for TermWriter to add to the ' Vec<u8>'
impl Write for TermWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.writer.write(buf)
    }

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

/// TermWriter implementation
impl TermWriter {
    // create new TermWriter object
    pub fn new() -> TermWriter {
        TermWriter { writer: Vec::new() }
    }

    // Should be used with an assert to check if the unwrap is equal to true
    // Wrapper for reg.rs that will format errors
    pub fn compare(self, _t: TermStrings) -> Result<bool, &'static str> {
        let compare_result = compare(self.writer, _t.get_term_list());

        match compare_result {
            Ok(true) => return Ok(true),
            Err(EmptyVec) => return Err(&"Provided terminal escape sequences were empty."),
            Err(UncappedEscape(x)) => {
                let invalid_str: String = x;
                error_print(invalid_str);
                return Err(&"Potential unrecognized escape sequences were found");
            }
            _ => return Err(&"Unknown error occurred"),
        };
    }

    // TODO: take in a file name and buffered input as arguments
    // Open a given file in write-only mode and attempt to write to it
    // If write to file is successful, write into TermWriter
    /*pub fn write_to_file(&mut self, file_name: &str, buf: &[u8]) -> Result<bool, &'static str> {
        let mut success = false;

        let mut file = match File::create(&file_name) {
            Ok(file) => file,
            Err(_file) => return Err("Failed writing to the supplied file"),
        };

        file.write(buf);

        let mut buffer = TermWriter::new();
        let _bytes_written = match buffer.write(buf) {
            Ok(_) => success = true,
            Err(_) => println!("Failed writing to TermWriter"),
        };
        return Ok(success);
    }*/
}

// Pretty print function for unrecognized escape sequences
// found within an input
pub fn error_print(invalid_str: String) {
    let result = invalid_str;

    println!("\x1b[0;31m------------------ Console Failure ------------------\n\n");

    println!(
        " Possible unrecognized escape sequence(s) in the input.\n Shown in brackets:\n{:?}\n\n",
        result
    );
    println!("-----------------------------------------------------\x1b[0m");
}

// 'cargo test'
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn vec_string_bytes() {
        let vec1 = vec!["Some".to_string(), "junk".to_string(), "text".to_string()];
        let joined_vec1 = vec1.join(" ");
        let vec1_bytes = joined_vec1.as_bytes();

        let bytes_literal = b"Some junk text";

        assert_eq!(vec1_bytes, bytes_literal);
    }

    #[test]
    fn termwriter_write() {
        let bytes_literal = b"Some junk text";

        let mut buffer = TermWriter::new();
        let bytes_written = match buffer.write(bytes_literal) {
            Ok(bytes_written) => assert_eq!(bytes_written, 14),
            Err(e) => println!("Failed writing to TermWriter object"),
        };
    }

    #[test]
    fn termwriter_write_all() {
        let bytes_literal = b"Some junk text";

        let mut buffer = TermWriter::new();

        assert_eq!((), buffer.write_all(bytes_literal).unwrap());
    }

    #[test]
    fn termwriter_flush() {
        let bytes_literal = b"Some junk text";

        let mut buffer = TermWriter::new();
        let _ = buffer.write(bytes_literal);

        assert_eq!((), buffer.flush().unwrap())
    }

    #[test]
    fn termwriter_compare() {
        let mut buffer = TermWriter::new();
        let _ = buffer.write(b"Text with\nTwo lines");
        let mut result = buffer.compare(TermStrings::new_from_env());

        if result.is_err() {
            assert_eq!(
                Err("Provided terminal escape sequences were empty."),
                result,
            );
        } else {
            assert_eq!(Ok(true), result);
        }
    }
}