Skip to content

Commit

Permalink
clippy and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Toyz committed Mar 21, 2024
1 parent 3ac3fc0 commit 42bf54b
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 23 deletions.
21 changes: 18 additions & 3 deletions src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,23 @@ impl SumSave {
}
}

pub fn eval(x: u32, y: u32, width: u32, height: u32, r: u8, g: u8, b: u8, a: u8, sr: u8, sg: u8, sb: u8, input: &DynamicImage, rng: &mut ThreadRng, tokens: Vec<Token>) -> Result<Rgba<u8>, String> {
#[derive(Debug, Clone)]
pub struct EvalContext {
pub tokens: Vec<Token>,
pub size: (u32, u32),
pub rgba: [u8; 4],
pub saved_rgb: [u8; 3],
pub position: (u32, u32),
}

pub fn eval(ctx: EvalContext, input: &DynamicImage,
mut rng: ThreadRng) -> Result<Rgba<u8>, String> {
let EvalContext { tokens, size, rgba, saved_rgb, position } = ctx;
let (width, height) = size;
let (x, y) = position;
let [r, g, b, a] = rgba;
let [sr, sg, sb] = saved_rgb;

if a == 0 {
return Ok(Rgba([0, 0, 0, 0]));
}
Expand Down Expand Up @@ -79,7 +95,6 @@ pub fn eval(x: u32, y: u32, width: u32, height: u32, r: u8, g: u8, b: u8, a: u8,
};

let mut saved = SumSave::new();
// let mut boxed: [RgbSum; 9] = [RgbSum { r: 0, g: 0, b: 0 }; 9];

for tok in tokens {
match tok {
Expand Down Expand Up @@ -181,7 +196,7 @@ pub fn eval(x: u32, y: u32, width: u32, height: u32, r: u8, g: u8, b: u8, a: u8,
stack.push(RgbSum { r: if a.r > b.r { 255 } else { 0 }, g: if a.g > b.g { 255 } else { 0 }, b: if a.b > b.b { 255 } else { 0 } });
}

Token::CharToken(c) => {
Token::Char(c) => {
match c {
'c' => stack.push(RgbSum { r, g, b }),
'R' => stack.push(RgbSum { r: 255, g: 0, b: 0 }),
Expand Down
32 changes: 17 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::io::{BufReader, BufWriter};
use std::path::PathBuf;
use std::path::{Path, PathBuf};

use clap::Parser;
use gif::{Encoder, Repeat};
use image::{AnimationDecoder, ColorType, DynamicImage, GenericImage, GenericImageView, ImageDecoder, Pixel};
use image::codecs::gif::GifDecoder;
use image::io::Reader as ImageReader;
use crate::eval::EvalContext;
use crate::parser::Token;

mod parser;
Expand All @@ -31,9 +32,7 @@ fn main() -> anyhow::Result<()> {
let args = Args::parse();
println!("Input File: {}", args.input);

// create path buffer
let path = std::path::PathBuf::from(&args.input);
// check if file exists
let path = Path::new(&args.input);
if !path.exists() {
return Err(anyhow::anyhow!("File does not exist"));
}
Expand All @@ -52,16 +51,16 @@ fn main() -> anyhow::Result<()> {
parsed.push((e.to_string(), tokens));
}

let format = get_format(&path);
let output_extension = get_output_extension(&path);
let format = get_format(path);
let output_extension = get_output_extension(path);
println!("Saving image");

let output_file = match args.output {
Some(file) => PathBuf::from(file),
None => PathBuf::from(format!("output.{}", output_extension)),
};

let img = ImageReader::open(&path)?.decode()?;
let img = ImageReader::open(path)?.decode()?;
match format {
image::ImageFormat::Png => {
let out = process(img, parsed)?;
Expand All @@ -72,7 +71,7 @@ fn main() -> anyhow::Result<()> {
out.save_with_format(output_file, format)?;
},
image::ImageFormat::Gif => {
let f = std::fs::File::open(&path)?;
let f = std::fs::File::open(path)?;
let decoder = GifDecoder::new(BufReader::new(f))?;
let [w, h] = [decoder.dimensions().0, decoder.dimensions().1];
let frames = decoder.into_frames().collect_frames()?;
Expand Down Expand Up @@ -125,16 +124,19 @@ fn process(mut img: DynamicImage, expressions: Vec<(String, Vec<Token>)>) -> any

let min_y = bounds.min_y();
let max_y = bounds.max_y();
let mut rng = rand::thread_rng();
let rng = rand::thread_rng();

for x in min_x..max_x {
for y in min_y..max_y {
let colors = img.get_pixel(x, y).to_rgba();
let [r, g, b, a] = colors.0;

// The eval function is assumed to be synchronous and CPU-bound
let result = eval::eval(x, y, width, height, r, g, b, if a <= 0 { 255 } else { a }, sr, sg, sb, &img, &mut rng, tokens.clone())
.expect("Failed to evaluate");
let result = eval::eval(EvalContext {
tokens: tokens.clone(),
size: (width, height),
rgba: colors.0,
saved_rgb: [sr, sg, sb],
position: (x, y),
}, &img, rng.clone()).expect("Failed to evaluate");

sr = result[0];
sg = result[1];
Expand All @@ -149,7 +151,7 @@ fn process(mut img: DynamicImage, expressions: Vec<(String, Vec<Token>)>) -> any
Ok(output_image)
}

fn get_format(file: &PathBuf) -> image::ImageFormat {
fn get_format(file: &Path) -> image::ImageFormat {
match file.extension().expect("file extension").to_str().expect("to string") {
"png" => image::ImageFormat::Png,
"jpg" | "jpeg" => image::ImageFormat::Jpeg,
Expand All @@ -163,6 +165,6 @@ fn get_format(file: &PathBuf) -> image::ImageFormat {
}
}

fn get_output_extension(file: &PathBuf) -> &str {
fn get_output_extension(file: &Path) -> &str {
file.extension().expect("file extension").to_str().expect("to string")
}
10 changes: 5 additions & 5 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub enum Token {
Weight,
LeftParen,
RightParen,
CharToken(char),
Char(char),
}

pub(crate) fn shunting_yard(input: &str) -> Result<Vec<Token>, String> {
Expand All @@ -45,7 +45,7 @@ pub(crate) fn shunting_yard(input: &str) -> Result<Vec<Token>, String> {
let digit = c.to_digit(10).unwrap() as i64;
number_buffer = match number_buffer {
Some(number) => {
let new_number = number as i64 * 10i64 + digit as i64;
let new_number = number as i64 * 10i64 + digit;
if new_number > 255 {
return Err(format!("Number exceeds 255 at position {}", current_position));
} else {
Expand Down Expand Up @@ -90,7 +90,7 @@ pub(crate) fn shunting_yard(input: &str) -> Result<Vec<Token>, String> {
push_number_buffer(&mut number_buffer, &mut output_queue, current_position)?;
},
_ if valid_tok(c) => {
output_queue.push_back(Token::CharToken(c));
output_queue.push_back(Token::Char(c));
},
_ => return Err(format!("Invalid character '{}' at position {}", c, current_position)),
}
Expand Down Expand Up @@ -202,8 +202,8 @@ mod tests {
fn test_valid_characters() {
let input = "c+Y";
let expected = Ok(vec![
Token::CharToken('c'),
Token::CharToken('Y'),
Token::Char('c'),
Token::Char('Y'),
Token::Add,
]);
assert_eq!(shunting_yard(input), expected);
Expand Down

0 comments on commit 42bf54b

Please sign in to comment.