fix: make pedantic clippy happy

This commit is contained in:
Noa Aarts 2024-10-05 16:27:55 +02:00
parent f6f7623458
commit be383ec768
Signed by: noa
GPG key ID: 1850932741EFF672
4 changed files with 100 additions and 100 deletions

View file

@ -23,7 +23,7 @@ impl<R: AsyncBufRead + AsyncBufReadExt + std::marker::Unpin> Parser<R> for Binar
async fn parse(&self, reader: &mut R) -> io::Result<Command> {
let fst = reader.read_u8().await;
match fst {
Ok(i) => match i {
Ok(command) => match command {
HELP_BIN => Ok(Command::Help),
SIZE_BIN => {
let canvas = reader.read_u8().await?;
@ -31,43 +31,58 @@ impl<R: AsyncBufRead + AsyncBufReadExt + std::marker::Unpin> Parser<R> for Binar
}
GET_PX_BIN => {
let canvas = reader.read_u8().await?;
let x = reader.read_u16_le().await?;
let y = reader.read_u16_le().await?;
Ok(Command::GetPixel(canvas, x, y))
let horizontal = reader.read_u16_le().await?;
let vertical = reader.read_u16_le().await?;
Ok(Command::GetPixel(canvas, horizontal, vertical))
}
SET_PX_W_BIN => {
let canvas = reader.read_u8().await?;
let x = reader.read_u16_le().await?;
let y = reader.read_u16_le().await?;
let w = reader.read_u8().await?;
Ok(Command::SetPixel(canvas, x, y, Color::W8(w)))
let horizontal = reader.read_u16_le().await?;
let vertical = reader.read_u16_le().await?;
let white = reader.read_u8().await?;
Ok(Command::SetPixel(
canvas,
horizontal,
vertical,
Color::W8(white),
))
}
SET_PX_RGB_BIN => {
let canvas = reader.read_u8().await?;
let x = reader.read_u16_le().await?;
let y = reader.read_u16_le().await?;
let r = reader.read_u8().await?;
let g = reader.read_u8().await?;
let b = reader.read_u8().await?;
Ok(Command::SetPixel(canvas, x, y, Color::RGB24(r, g, b)))
let horizontal = reader.read_u16_le().await?;
let vertical = reader.read_u16_le().await?;
let red = reader.read_u8().await?;
let green = reader.read_u8().await?;
let blue = reader.read_u8().await?;
Ok(Command::SetPixel(
canvas,
horizontal,
vertical,
Color::RGB24(red, green, blue),
))
}
SET_PX_RGBA_BIN => {
let canvas = reader.read_u8().await?;
let x = reader.read_u16_le().await?;
let y = reader.read_u16_le().await?;
let r = reader.read_u8().await?;
let g = reader.read_u8().await?;
let b = reader.read_u8().await?;
let a = reader.read_u8().await?;
Ok(Command::SetPixel(canvas, x, y, Color::RGBA32(r, g, b, a)))
let horizontal = reader.read_u16_le().await?;
let vertical = reader.read_u16_le().await?;
let red = reader.read_u8().await?;
let green = reader.read_u8().await?;
let blue = reader.read_u8().await?;
let alpha = reader.read_u8().await?;
Ok(Command::SetPixel(
canvas,
horizontal,
vertical,
Color::RGBA32(red, green, blue, alpha),
))
}
_ => {
eprintln!("received illegal command: {}", i);
eprintln!("received illegal command: {command}");
Err(Error::from(ErrorKind::InvalidInput))
}
},
Err(err) => {
eprintln!("{}", err);
eprintln!("{err}");
Err(err)
}
}
@ -85,11 +100,10 @@ impl<W: AsyncWriteExt + std::marker::Unpin> Responder<W> for BinaryParser {
let help_text = format!(
"
You found the binary protocol help text
you can get this by sending ({:02X}) to the server
To get the size of a canvas, send ({:02X}) (u8 canvas) to the server
To set a pixel using RGB, use ({:02X}) (u8 canvas) (x as u16_le) (y as u16_le) (u8 r) (u8 g) (u8 b)
you can get this by sending ({HELP_BIN:02X}) to the server
To get the size of a canvas, send ({SIZE_BIN:02X}) (u8 canvas) to the server
To set a pixel using RGB, use ({SET_PX_RGB_BIN:02X}) (u8 canvas) (x as u16_le) (y as u16_le) (u8 r) (u8 g) (u8 b)
",
HELP_BIN, SIZE_BIN, SET_PX_RGB_BIN
);
match response {
Response::Help => writer.write_all(help_text.as_bytes()).await,
@ -103,6 +117,7 @@ To set a pixel using RGB, use ({:02X}) (u8 canvas) (x as u16_le) (y as u16_le) (
}
#[cfg(test)]
#[allow(clippy::needless_return)]
mod tests {
use super::*;
use tokio::io::BufReader;
@ -113,7 +128,7 @@ mod tests {
let reader = tokio_test::io::Builder::new().read(&[HELP_BIN]).build();
let mut bufreader = BufReader::new(reader);
let thingy = parser.parse(&mut bufreader).await;
assert_eq!(thingy.unwrap(), Command::Help)
assert_eq!(thingy.unwrap(), Command::Help);
}
#[tokio::test]
@ -122,7 +137,7 @@ mod tests {
let reader = tokio_test::io::Builder::new().read(&[SIZE_BIN, 3]).build();
let mut bufreader = BufReader::new(reader);
let thingy = parser.parse(&mut bufreader).await;
assert_eq!(thingy.unwrap(), Command::Size(3))
assert_eq!(thingy.unwrap(), Command::Size(3));
}
#[tokio::test]
@ -136,7 +151,7 @@ mod tests {
assert_eq!(
thingy.unwrap(),
Command::SetPixel(1, 0x4269, 0x6942, Color::W8(0x82))
)
);
}
#[tokio::test]
@ -160,7 +175,7 @@ mod tests {
assert_eq!(
thingy.unwrap(),
Command::SetPixel(1, 0x4269, 0x6942, Color::RGB24(0x82, 0x00, 0xff))
)
);
}
#[tokio::test]
@ -185,7 +200,7 @@ mod tests {
assert_eq!(
thingy.unwrap(),
Command::SetPixel(1, 0x4269, 0x6942, Color::RGBA32(0x82, 0x00, 0xff, 0xa0))
)
);
}
#[tokio::test]
@ -196,7 +211,7 @@ mod tests {
.build();
let mut bufreader = BufReader::new(reader);
let thingy = parser.parse(&mut bufreader).await;
assert_eq!(thingy.unwrap(), Command::GetPixel(3, 0x4269, 0x6942))
assert_eq!(thingy.unwrap(), Command::GetPixel(3, 0x4269, 0x6942));
}
#[tokio::test]

View file

@ -9,19 +9,19 @@ pub trait Grid<I, V> {
fn set(&self, x: I, y: I, value: V);
}
pub struct FlutGrid<T> {
pub struct Flut<T> {
size_x: usize,
size_y: usize,
cells: SyncUnsafeCell<Vec<T>>,
}
impl<T: Clone> FlutGrid<T> {
pub fn init(size_x: usize, size_y: usize, value: T) -> FlutGrid<T> {
impl<T: Clone> Flut<T> {
pub fn init(size_x: usize, size_y: usize, value: T) -> Flut<T> {
let mut vec = Vec::with_capacity(size_x * size_y);
for _ in 0..(size_x * size_y) {
vec.push(value.clone());
}
FlutGrid {
Flut {
size_x,
size_y,
cells: vec.into(),
@ -33,7 +33,7 @@ impl<T: Clone> FlutGrid<T> {
}
}
impl<T> FlutGrid<T> {
impl<T> Flut<T> {
fn index(&self, x: Coordinate, y: Coordinate) -> Option<usize> {
let x = x as usize;
let y = y as usize;
@ -44,7 +44,7 @@ impl<T> FlutGrid<T> {
}
}
impl<T> Grid<Coordinate, T> for FlutGrid<T> {
impl<T> Grid<Coordinate, T> for Flut<T> {
fn get(&self, x: Coordinate, y: Coordinate) -> Option<&T> {
self.index(x, y)
.map(|idx| unsafe { &(*self.cells.get())[idx] })
@ -64,21 +64,22 @@ impl<T> Grid<Coordinate, T> for FlutGrid<T> {
}
#[cfg(test)]
#[allow(clippy::needless_return)]
mod tests {
use super::*;
use crate::grid::FlutGrid;
use crate::grid::Flut;
use test::Bencher;
#[tokio::test]
async fn test_grid_init_values() {
let grid = FlutGrid::init(3, 3, 0);
let grid = Flut::init(3, 3, 0);
assert_eq!(grid.cells.into_inner(), vec![0, 0, 0, 0, 0, 0, 0, 0, 0])
assert_eq!(grid.cells.into_inner(), vec![0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
#[tokio::test]
async fn test_grid_init_size() {
let grid = FlutGrid::init(800, 600, 0);
let grid = Flut::init(800, 600, 0);
assert_eq!(grid.size_x, 800);
assert_eq!(grid.size_y, 600);
@ -86,30 +87,30 @@ mod tests {
#[tokio::test]
async fn test_grid_set() {
let grid = FlutGrid::init(3, 3, 0);
let grid = Flut::init(3, 3, 0);
grid.set(1, 1, 255);
grid.set(2, 1, 256);
assert_eq!(grid.cells.into_inner(), vec![0, 0, 0, 0, 255, 256, 0, 0, 0])
assert_eq!(grid.cells.into_inner(), vec![0, 0, 0, 0, 255, 256, 0, 0, 0]);
}
#[tokio::test]
async fn test_grid_set_out_of_range() {
let grid = FlutGrid::init(3, 3, 0);
let grid = Flut::init(3, 3, 0);
grid.set(1, 1, 255);
grid.set(3, 1, 256);
assert_eq!(grid.cells.into_inner(), vec![0, 0, 0, 0, 255, 0, 0, 0, 0])
assert_eq!(grid.cells.into_inner(), vec![0, 0, 0, 0, 255, 0, 0, 0, 0]);
}
#[tokio::test]
async fn test_grid_get() {
let grid = FlutGrid::init(3, 3, 0);
let grid = Flut::init(3, 3, 0);
grid.set(1, 2, 222);
assert_eq!(grid.get(1, 2), Some(&222));
}
#[tokio::test]
async fn test_grid_get_out_of_range() {
let grid = FlutGrid::init(3, 3, 0);
let grid = Flut::init(3, 3, 0);
grid.set(3, 1, 256);
assert_eq!(grid.get(3, 1), None);
assert_eq!(grid.get(1, 2), Some(&0));
@ -117,27 +118,27 @@ mod tests {
#[bench]
fn bench_init(b: &mut Bencher) {
b.iter(|| FlutGrid::init(800, 600, 0 as u32))
b.iter(|| Flut::init(800, 600, 0));
}
#[bench]
fn bench_set(b: &mut Bencher) {
let grid = FlutGrid::init(800, 600, 0 as u32);
let grid = Flut::init(800, 600, 0);
b.iter(|| {
let x = test::black_box(293);
let y = test::black_box(222);
let color = test::black_box(293_923);
let color = test::black_box(0x29_39_23);
grid.set(x, y, color);
})
});
}
#[bench]
fn bench_get(b: &mut Bencher) {
let grid = FlutGrid::init(800, 600, 0 as u32);
let grid = Flut::init(800, 600, 0);
b.iter(|| {
let x = test::black_box(293);
let y = test::black_box(222);
grid.get(x, y)
})
});
}
}

View file

@ -12,7 +12,7 @@ use std::{
};
use binary_protocol::BinaryParser;
use grid::{FlutGrid, Grid};
use grid::{Flut, Grid};
use text_protocol::TextParser;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt, BufReader, BufWriter},
@ -38,19 +38,19 @@ type Canvas = u8;
type Coordinate = u16;
fn set_pixel_rgba(
grids: &[grid::FlutGrid<u32>],
grids: &[grid::Flut<u32>],
canvas: Canvas,
x: Coordinate,
y: Coordinate,
rgb: u32,
) {
if let Some(grid) = grids.get(canvas as usize) {
grid.set(x, y, rgb)
grid.set(x, y, rgb);
}
}
fn get_pixel(
grids: &[grid::FlutGrid<u32>],
grids: &[grid::Flut<u32>],
canvas: Canvas,
x: Coordinate,
y: Coordinate,
@ -154,7 +154,7 @@ where
{
reader: BufReader<R>,
writer: BufWriter<W>,
grids: Arc<[FlutGrid<u32>]>,
grids: Arc<[Flut<u32>]>,
parser: ParserTypes,
}
@ -196,36 +196,30 @@ where
Ok(())
}
fn set_pixel_command(
&mut self,
canvas: Canvas,
x: Coordinate,
y: Coordinate,
color: Color,
) -> io::Result<()> {
fn set_pixel_command(&mut self, canvas: Canvas, x: Coordinate, y: Coordinate, color: &Color) {
let c: u32 = match color {
Color::RGB24(r, g, b) => u32::from_be_bytes([r, g, b, 0xff]),
Color::RGBA32(r, g, b, a) => u32::from_be_bytes([r, g, b, a]),
Color::W8(w) => u32::from_be_bytes([w, w, w, 0xff]),
Color::RGB24(red, green, blue) => u32::from_be_bytes([*red, *green, *blue, 0xff]),
Color::RGBA32(red, green, blue, alpha) => {
u32::from_be_bytes([*red, *green, *blue, *alpha])
}
Color::W8(white) => u32::from_be_bytes([*white, *white, *white, 0xff]),
};
set_pixel_rgba(self.grids.as_ref(), canvas, x, y, c);
increment_counter();
Ok(())
}
fn change_canvas_command(&mut self, canvas: Canvas) -> io::Result<()> {
match_parser!(parser: self.parser => parser.change_canvas(canvas))
}
fn change_protocol(&mut self, protocol: Protocol) -> io::Result<()> {
fn change_protocol(&mut self, protocol: &Protocol) {
match protocol {
Protocol::Text => self.parser = ParserTypes::TextParser(TextParser::new(0)),
Protocol::Binary => self.parser = ParserTypes::BinaryParser(BinaryParser::new()),
}
Ok(())
}
pub fn new(reader: R, writer: W, grids: Arc<[grid::FlutGrid<u32>]>) -> FlutClient<R, W> {
pub fn new(reader: R, writer: W, grids: Arc<[grid::Flut<u32>]>) -> FlutClient<R, W> {
FlutClient {
reader: BufReader::new(reader),
writer: BufWriter::new(writer),
@ -246,10 +240,10 @@ where
Ok(Command::Size(canvas)) => self.size_command(canvas).await?,
Ok(Command::GetPixel(canvas, x, y)) => self.get_pixel_command(canvas, x, y).await?,
Ok(Command::SetPixel(canvas, x, y, color)) => {
self.set_pixel_command(canvas, x, y, color)?;
self.set_pixel_command(canvas, x, y, &color);
}
Ok(Command::ChangeCanvas(canvas)) => self.change_canvas_command(canvas)?,
Ok(Command::ChangeProtocol(protocol)) => self.change_protocol(protocol)?,
Ok(Command::ChangeProtocol(protocol)) => self.change_protocol(&protocol),
Err(err) if err.kind() == ErrorKind::UnexpectedEof => {
return Ok(());
@ -262,10 +256,7 @@ where
}
}
async fn handle_flut(
flut_listener: TcpListener,
grids: Arc<[grid::FlutGrid<u32>]>,
) -> io::Result<()> {
async fn handle_flut(flut_listener: TcpListener, grids: Arc<[grid::Flut<u32>]>) -> io::Result<()> {
let mut handles = Vec::new();
loop {
let (mut socket, _) = flut_listener.accept().await?;
@ -286,15 +277,11 @@ async fn handle_flut(
#[allow(clippy::needless_return)]
async fn main() {
println!("created grids");
let grids: Arc<[FlutGrid<u32>; GRID_LENGTH]> =
[grid::FlutGrid::init(800, 600, 0xff00ffff)].into();
let grids: Arc<[Flut<u32>; GRID_LENGTH]> = [grid::Flut::init(800, 600, 0xff_00_ff_ff)].into();
let flut_listener = match TcpListener::bind(HOST).await {
Ok(listener) => listener,
Err(_) => {
eprintln!("Was unable to bind to {HOST}, please check if a different process is bound");
return;
}
let Ok(flut_listener) = TcpListener::bind(HOST).await else {
eprintln!("Was unable to bind to {HOST}, please check if a different process is bound");
return;
};
println!("bound flut listener");
@ -306,7 +293,7 @@ async fn main() {
];
for handle in handles {
println!("joined handle had result {:?}", handle.await)
println!("joined handle had result {:?}", handle.await);
}
}

View file

@ -55,7 +55,7 @@ impl TextParser {
Err(Error::from(ErrorKind::InvalidInput))
}
}
fn parse_canvas(&self, line: &str) -> io::Result<Command> {
fn parse_canvas(line: &str) -> io::Result<Command> {
let mut split = line.trim().split(' ');
let _command = split.next().ok_or(Error::from(ErrorKind::InvalidInput))?;
@ -66,7 +66,7 @@ impl TextParser {
Err(Error::from(ErrorKind::InvalidInput))
}
}
fn parse_protocol(&self, line: &str) -> io::Result<Command> {
fn parse_protocol(line: &str) -> io::Result<Command> {
let mut split = line.trim().split(' ');
let _command = split.next().ok_or(Error::from(ErrorKind::InvalidInput))?;
@ -81,7 +81,7 @@ impl TextParser {
impl<R: AsyncBufRead + AsyncBufReadExt + std::marker::Unpin> Parser<R> for TextParser {
async fn parse(&self, reader: &mut R) -> io::Result<Command> {
let mut line = "".to_string();
let mut line = String::new();
if reader.read_line(&mut line).await.is_ok() {
if line.starts_with("HELP") {
return Ok(Command::Help);
@ -90,9 +90,9 @@ impl<R: AsyncBufRead + AsyncBufReadExt + std::marker::Unpin> Parser<R> for TextP
} else if line.starts_with("PX ") {
return self.parse_pixel(&line);
} else if line.starts_with("CANVAS ") {
return self.parse_canvas(&line);
return TextParser::parse_canvas(&line);
} else if line.starts_with("PROTOCOL ") {
return self.parse_protocol(&line);
return TextParser::parse_protocol(&line);
}
}
Err(Error::from(ErrorKind::InvalidInput))
@ -114,14 +114,10 @@ impl<W: AsyncWriteExt + std::marker::Unpin> Responder<W> for TextParser {
async fn unparse(&self, response: Response, writer: &mut W) -> io::Result<()> {
match response {
Response::Help => writer.write_all(HELP_TEXT).await,
Response::Size(x, y) => {
writer
.write_all(format!("SIZE {} {}\n", x, y).as_bytes())
.await
}
Response::Size(x, y) => writer.write_all(format!("SIZE {x} {y}\n").as_bytes()).await,
Response::GetPixel(x, y, color) => {
writer
.write_all(format!("PX {} {} {}\n", x, y, hex::encode_upper(color)).as_bytes())
.write_all(format!("PX {x} {y} {}\n", hex::encode_upper(color)).as_bytes())
.await
}
}
@ -129,6 +125,7 @@ impl<W: AsyncWriteExt + std::marker::Unpin> Responder<W> for TextParser {
}
#[cfg(test)]
#[allow(clippy::needless_return)]
mod tests {
use super::*;
use tokio::io::BufReader;