stdshout/
lib.rs

1//! Shout it out!
2//!
3//! ## Example
4//!
5//! ```
6//! assert_eq!("I AM NOT SHOUTING!!!1!", stdshout::shout("i am not shouting"));
7//! ```
8
9use std::io;
10use std::io::Write;
11
12const APPEND : &'static str = "!!!1!";
13
14pub struct Stdshout<W: Write>(W);
15
16impl<W: Write> Stdshout<W> {
17    pub fn new(w: W) -> Stdshout<W> {
18        Stdshout(w)
19    }
20}
21
22impl<W: Write> Write for Stdshout<W> {
23    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
24        let lossy = String::from_utf8_lossy(buf.as_ref()).to_uppercase();
25        for line in lossy.split('\n') {
26            if line.len() > 0 {
27                self.0.write(line.as_bytes())?;
28                self.0.write(APPEND.as_bytes())?;
29                self.0.write(b"\n")?;
30            }
31        }
32
33        Ok(buf.len())
34    }
35
36    fn flush(&mut self) -> io::Result<()> {
37        self.0.flush()
38    }
39}
40
41/// Interpret data as UTF-8 and shout it out.
42pub fn shout<D: AsRef<[u8]>>(data: D) -> String {
43    let mut lossy = String::from_utf8_lossy(data.as_ref()).to_uppercase();
44    lossy.push_str(APPEND);
45    lossy
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn it_works() {
54        assert_eq!("HELLO!!!1!", shout("hello"));
55    }
56
57    #[test]
58    fn binary_data() {
59        assert_eq!("�!!!1!", shout(b"\xF0\x90\x80"));
60    }
61}