rainbowcat 0.1.0

Cat, now with 100% more rainbows
extern crate ansi_term;
extern crate palette;
extern crate failure;

use ansi_term::Color;

use failure::Error;

use std::fs::File;
use std::io::{self, Read};

use std::env;

fn palette_to_ansi(color: &palette::Srgb) -> Color {
        Color::RGB(
        (255. * color.red) as u8,
        (255. * color.blue) as u8,
        (255. * color.green) as u8
    )
}

fn rgbify(string: &str, color: &palette::Srgb) -> String {
    palette_to_ansi(color).paint(string).to_string()
}


fn write_rainbow(stream: &mut impl Read) -> Result<(), Error> {
    let mut buff: [u8; 128] = [0; 128];

    const HUE_PER_STEP: f32 = 0.02;

    let mut line = 0;
    let mut step = 0;
    loop {
        let read_amount = stream.read(&mut buff)?;
        if read_amount == 0 {
            break;
        }
        let string = &String::from_utf8_lossy(&buff[..read_amount]);


        for c in string.chars() {
            let hue = (step as f32) * HUE_PER_STEP + (line as f32) * HUE_PER_STEP;
            //let color = palette::Srgb::new((step as f32) * HUE_PER_STEP, 1., 1.);
            let color = palette::Hsv::new(hue * 255., 0.9, 0.5);

            let mut s = String::new();
            s.push(c);
            print!("{}", rgbify(&s, &color.into()));

            step += 1;
            if c == '\n' {
                line += 1;
                step = 0;
            }
        }
    }
    
    Ok(())
}



fn main_with_err() -> Result<(), Error> {
    let args = env::args().collect::<Vec<_>>();

    if args.len() == 1 {
        write_rainbow(&mut io::stdin())
    }
    else {
        write_rainbow(&mut File::open(&args[1])?)
    }
}


fn main() {
    main_with_err().unwrap();

    // TODO: Reset term here
}