fix a bunch of clippy warnings

but not all of them. just the easy ones for now!
This commit is contained in:
Gered 2023-03-28 16:29:44 -04:00
parent aa22786d43
commit 7f19f4e7d4
29 changed files with 122 additions and 173 deletions

View file

@ -190,11 +190,7 @@ fn main() -> Result<()> {
"channel {} - {} {}", "channel {} - {} {}",
index, index,
if status.playing { "playing" } else { "not playing" }, if status.playing { "playing" } else { "not playing" },
if status.playing { if status.playing { format!("{} / {}", status.position, status.size) } else { String::new() }
String::from(format!("{} / {}", status.position, status.size))
} else {
String::new()
}
), ),
16, 16,
y, y,

View file

@ -102,7 +102,7 @@ fn update_system_movement(context: &mut Context) {
let velocities = context.entities.components::<Velocity>(); let velocities = context.entities.components::<Velocity>();
for (entity, position) in positions.iter_mut() { for (entity, position) in positions.iter_mut() {
if let Some(velocity) = velocities.get(&entity) { if let Some(velocity) = velocities.get(entity) {
position.0 += velocity.0 * context.delta; position.0 += velocity.0 * context.delta;
} }
} }
@ -114,8 +114,8 @@ fn update_system_collision(context: &mut Context) {
let mut velocities = context.entities.components_mut::<Velocity>(); let mut velocities = context.entities.components_mut::<Velocity>();
for (entity, _) in bounceables.iter() { for (entity, _) in bounceables.iter() {
let mut position = positions.get_mut(&entity).unwrap(); let mut position = positions.get_mut(entity).unwrap();
let mut velocity = velocities.get_mut(&entity).unwrap(); let mut velocity = velocities.get_mut(entity).unwrap();
let mut bounced = false; let mut bounced = false;
if position.0.x as i32 <= 0 || position.0.x as i32 + BALL_SIZE >= context.system.res.video.right() as i32 { if position.0.x as i32 <= 0 || position.0.x as i32 + BALL_SIZE >= context.system.res.video.right() as i32 {
@ -153,7 +153,7 @@ fn update_system_leave_particle_trail(context: &mut Context) {
if leaves_trail.timer <= 0.0 { if leaves_trail.timer <= 0.0 {
leaves_trail.timer = BALL_TRAIL_PARTICLE_INTERVAL; leaves_trail.timer = BALL_TRAIL_PARTICLE_INTERVAL;
let position = positions.get(&entity).unwrap(); let position = positions.get(entity).unwrap();
let mut trail_position = position.0; let mut trail_position = position.0;
trail_position.x += (BALL_SIZE / 2) as f32; trail_position.x += (BALL_SIZE / 2) as f32;
trail_position.y += (BALL_SIZE / 2) as f32; trail_position.y += (BALL_SIZE / 2) as f32;
@ -167,7 +167,7 @@ fn render_system_sprites(context: &mut Context) {
let positions = context.entities.components::<Position>(); let positions = context.entities.components::<Position>();
for (entity, sprite_index) in sprite_indices.iter() { for (entity, sprite_index) in sprite_indices.iter() {
let position = positions.get(&entity).unwrap(); let position = positions.get(entity).unwrap();
context.system.res.video.blit( context.system.res.video.blit(
IndexedBlitMethod::Transparent(0), IndexedBlitMethod::Transparent(0),
&context.sprites[sprite_index.0], &context.sprites[sprite_index.0],
@ -185,13 +185,13 @@ fn render_system_particles(context: &mut Context) {
let lifetimes = context.entities.components::<LifeLeft>(); let lifetimes = context.entities.components::<LifeLeft>();
for (entity, _) in particles.iter() { for (entity, _) in particles.iter() {
let position = positions.get(&entity).unwrap(); let position = positions.get(entity).unwrap();
let pixel_color; let pixel_color;
if let Some(color) = colors.get(&entity) { if let Some(color) = colors.get(entity) {
pixel_color = Some(color.0); pixel_color = Some(color.0);
} else if let Some(color_by_lifetime) = colors_by_lifetime.get(&entity) { } else if let Some(color_by_lifetime) = colors_by_lifetime.get(entity) {
let lifetime = lifetimes.get(&entity).unwrap(); let lifetime = lifetimes.get(entity).unwrap();
let percent_life = lifetime.life / lifetime.initial; let percent_life = lifetime.life / lifetime.initial;
pixel_color = Some(if percent_life >= 0.8 { pixel_color = Some(if percent_life >= 0.8 {
color_by_lifetime.0 color_by_lifetime.0

View file

@ -34,7 +34,7 @@ impl Game {
sprite.blit_region( sprite.blit_region(
IndexedBlitMethod::Solid, IndexedBlitMethod::Solid,
&balls_bmp, &balls_bmp,
&Rect::new(i as i32 * BALL_SIZE as i32, 0, BALL_SIZE as u32, BALL_SIZE as u32), &Rect::new(i as i32 * BALL_SIZE, 0, BALL_SIZE as u32, BALL_SIZE as u32),
0, 0,
0, 0,
); );

View file

@ -41,7 +41,7 @@ fn event_handler(event: &Event, context: &mut Core) -> bool {
move_entity_forward(context, *entity); move_entity_forward(context, *entity);
} }
} }
Event::Spawn(entity) => { Event::Spawn(_entity) => {
// todo // todo
} }
Event::AnimationFinished(entity) => { Event::AnimationFinished(entity) => {

View file

@ -636,7 +636,7 @@ pub fn new_pixel_particle(context: &mut Core, x: i32, y: i32, velocity: Vector2,
pub fn spawn_pixel_cloud(context: &mut Core, x: i32, y: i32, count: usize, speed: f32, lifetime: f32, color: u8) { pub fn spawn_pixel_cloud(context: &mut Core, x: i32, y: i32, count: usize, speed: f32, lifetime: f32, color: u8) {
let mut angle = 0.0; let mut angle = 0.0;
for i in 0..count { for _ in 0..count {
angle += RADIANS_360 / count as f32; angle += RADIANS_360 / count as f32;
let velocity = Vector2::from_angle(angle) * speed; let velocity = Vector2::from_angle(angle) * speed;
new_pixel_particle(context, x, y, velocity, lifetime, color); new_pixel_particle(context, x, y, velocity, lifetime, color);

View file

@ -561,7 +561,7 @@ fn update_system_turn_attached_entities(context: &mut Core) {
for (parent_entity, attachment) in attachments.iter() { for (parent_entity, attachment) in attachments.iter() {
// the parent may not have a facing direction. and if so, we don't need to change the // the parent may not have a facing direction. and if so, we don't need to change the
// attachment (child) // attachment (child)
let parent_facing_direction = if let Some(facing_direction) = facing_directions.get(&parent_entity) { let parent_facing_direction = if let Some(facing_direction) = facing_directions.get(parent_entity) {
facing_direction.0 facing_direction.0
} else { } else {
continue; continue;
@ -586,7 +586,7 @@ fn update_system_position_attached_entities(context: &mut Core) {
// get the parent position used as the base for the attached (child) entity. if the // get the parent position used as the base for the attached (child) entity. if the
// parent doesn't have one (probably it is dead?), then skip this attachment // parent doesn't have one (probably it is dead?), then skip this attachment
let parent_position; let parent_position;
if let Some(position) = positions.get(&parent_entity) { if let Some(position) = positions.get(parent_entity) {
parent_position = position.0; parent_position = position.0;
} else { } else {
continue; continue;

View file

@ -56,7 +56,7 @@ impl AppState<Game> for MainMenuState {
const SPACER: i32 = 8; const SPACER: i32 = 8;
draw_window(&mut context.core.system.res.video, &context.core.ui, x, y, x + width, y + height); draw_window(&mut context.core.system.res.video, &context.core.ui, x, y, x + width, y + height);
let selection_y = y + SPACER + (self.selection as i32 * 16); let selection_y = y + SPACER + (self.selection * 16);
context.core.system.res.video.print_string( context.core.system.res.video.print_string(
">", ">",
x + SPACER, x + SPACER,
@ -186,7 +186,7 @@ impl AppState<Game> for GamePlayState {
const SPACER: i32 = 8; const SPACER: i32 = 8;
draw_window(&mut context.core.system.res.video, &context.core.ui, x, y, x + width, y + height); draw_window(&mut context.core.system.res.video, &context.core.ui, x, y, x + width, y + height);
let selection_y = y + SPACER + (self.selection as i32 * 16); let selection_y = y + SPACER + (self.selection * 16);
context.core.system.res.video.print_string( context.core.system.res.video.print_string(
">", ">",
x + SPACER, x + SPACER,

View file

@ -38,23 +38,23 @@ pub fn draw_window(
dest.filled_rect(left + 8, top + 8, right - 8, bottom - 8, 1); dest.filled_rect(left + 8, top + 8, right - 8, bottom - 8, 1);
// corners // corners
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[2], left, top); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[2], left, top);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[3], right - 8, top); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[3], right - 8, top);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[4], left, bottom - 8); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[4], left, bottom - 8);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[5], right - 8, bottom - 8); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[5], right - 8, bottom - 8);
// top and bottom edges // top and bottom edges
for i in 0..((right - left) / 8) - 2 { for i in 0..((right - left) / 8) - 2 {
let x = left + 8 + (i * 8); let x = left + 8 + (i * 8);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[9], x, top); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[9], x, top);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[8], x, bottom - 8); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[8], x, bottom - 8);
} }
// left and right edges // left and right edges
for i in 0..((bottom - top) / 8) - 2 { for i in 0..((bottom - top) / 8) - 2 {
let y = top + 8 + (i * 8); let y = top + 8 + (i * 8);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[6], left, y); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[6], left, y);
dest.blit_region(IndexedBlitMethod::Transparent(0), &ui.bitmap(), &ui[7], right - 8, y); dest.blit_region(IndexedBlitMethod::Transparent(0), ui.bitmap(), &ui[7], right - 8, y);
} }
} }

View file

@ -47,17 +47,17 @@ impl TileMap {
} }
#[inline] #[inline]
pub fn lower(&self) -> &Box<[i32]> { pub fn lower(&self) -> &[i32] {
&self.layers[0] &self.layers[0]
} }
#[inline] #[inline]
pub fn upper(&self) -> &Box<[i32]> { pub fn upper(&self) -> &[i32] {
&self.layers[1] &self.layers[1]
} }
#[inline] #[inline]
pub fn collision(&self) -> &Box<[i32]> { pub fn collision(&self) -> &[i32] {
&self.layers[2] &self.layers[2]
} }

View file

@ -107,7 +107,7 @@ impl FormatChunk {
if chunk_header.size > 16 { if chunk_header.size > 16 {
additional_data_length = reader.read_u16::<LittleEndian>()?; additional_data_length = reader.read_u16::<LittleEndian>()?;
let mut buffer = vec![0u8; additional_data_length as usize]; let mut buffer = vec![0u8; additional_data_length as usize];
reader.read(&mut buffer)?; reader.read_exact(&mut buffer)?;
additional_data = Some(buffer.into_boxed_slice()); additional_data = Some(buffer.into_boxed_slice());
} else { } else {
additional_data_length = 0; additional_data_length = 0;
@ -136,7 +136,7 @@ impl FormatChunk {
writer.write_u16::<LittleEndian>(self.bits_per_sample)?; writer.write_u16::<LittleEndian>(self.bits_per_sample)?;
if self.additional_data_length > 0 { if self.additional_data_length > 0 {
writer.write_u16::<LittleEndian>(self.additional_data_length)?; writer.write_u16::<LittleEndian>(self.additional_data_length)?;
writer.write_all(&self.additional_data.as_ref().unwrap())?; writer.write_all(self.additional_data.as_ref().unwrap())?;
} }
Ok(()) Ok(())
} }

View file

@ -104,8 +104,7 @@ impl AudioChannel {
if let Some(sample) = self.next_sample() { if let Some(sample) = self.next_sample() {
Some((sample as f32 * self.volume) as i16) Some((sample as f32 * self.volume) as i16)
} else { } else if self.loops {
if self.loops {
self.position = 0; self.position = 0;
None None
} else { } else {
@ -113,7 +112,6 @@ impl AudioChannel {
None None
} }
} }
}
/// Resets the audio channel to a "blank slate", clearing the audio buffer, setting no current /// Resets the audio channel to a "blank slate", clearing the audio buffer, setting no current
/// audio generator, and turning playback off. /// audio generator, and turning playback off.
@ -265,15 +263,13 @@ impl AudioDevice {
pub fn play_buffer(&mut self, buffer: &AudioBuffer, loops: bool) -> Result<Option<usize>, AudioDeviceError> { pub fn play_buffer(&mut self, buffer: &AudioBuffer, loops: bool) -> Result<Option<usize>, AudioDeviceError> {
if *buffer.spec() != self.spec { if *buffer.spec() != self.spec {
Err(AudioDeviceError::AudioSpecMismatch) Err(AudioDeviceError::AudioSpecMismatch)
} else { } else if let Some((index, channel)) = self.stopped_channels_iter_mut().enumerate().next() {
if let Some((index, channel)) = self.stopped_channels_iter_mut().enumerate().next() {
channel.play_buffer(buffer, loops); channel.play_buffer(buffer, loops);
Ok(Some(index)) Ok(Some(index))
} else { } else {
Ok(None) Ok(None)
} }
} }
}
/// Plays the given [`AudioBuffer`] on the specified channel. Whatever that channel was playing /// Plays the given [`AudioBuffer`] on the specified channel. Whatever that channel was playing
/// will be interrupted and replaced with a copy of the given buffer's data. /// will be interrupted and replaced with a copy of the given buffer's data.

View file

@ -200,11 +200,7 @@ impl Entities {
/// no component store for this type of component, `None` is returned. /// no component store for this type of component, `None` is returned.
#[inline] #[inline]
pub fn components<T: Component>(&self) -> Option<RefComponents<T>> { pub fn components<T: Component>(&self) -> Option<RefComponents<T>> {
if let Some(component_store) = self.get_component_store() { self.get_component_store().map(|component_store| component_store.borrow())
Some(component_store.borrow())
} else {
None
}
} }
/// Returns a reference to the mutable component store for the given component type. This allows /// Returns a reference to the mutable component store for the given component type. This allows
@ -216,11 +212,7 @@ impl Entities {
/// instead. /// instead.
#[inline] #[inline]
pub fn components_mut<T: Component>(&self) -> Option<RefMutComponents<T>> { pub fn components_mut<T: Component>(&self) -> Option<RefMutComponents<T>> {
if let Some(component_store) = self.get_component_store() { self.get_component_store().map(|component_store| component_store.borrow_mut())
Some(component_store.borrow_mut())
} else {
None
}
} }
/// Initializes a component store for the given component type if one does not exist already. /// Initializes a component store for the given component type if one does not exist already.
@ -725,8 +717,8 @@ mod tests {
let mut healths = em.components_mut::<Health>().unwrap(); let mut healths = em.components_mut::<Health>().unwrap();
let mut positions = em.components_mut::<Position>().unwrap(); let mut positions = em.components_mut::<Position>().unwrap();
let health = healths.get_mut(&entity); let health = healths.get_mut(entity);
let position = positions.get_mut(&entity); let position = positions.get_mut(entity);
println!("entity {}, health: {:?}, position: {:?}", name.0, health, position); println!("entity {}, health: {:?}, position: {:?}", name.0, health, position);
@ -768,7 +760,7 @@ mod tests {
let mut positions = context.entities.components_mut::<Position>().unwrap(); let mut positions = context.entities.components_mut::<Position>().unwrap();
let velocities = context.entities.components::<Velocity>().unwrap(); let velocities = context.entities.components::<Velocity>().unwrap();
for (entity, position) in positions.iter_mut() { for (entity, position) in positions.iter_mut() {
if let Some(velocity) = velocities.get(&entity) { if let Some(velocity) = velocities.get(entity) {
position.0 += velocity.0; position.0 += velocity.0;
position.1 += velocity.1; position.1 += velocity.1;
} }

View file

@ -31,6 +31,11 @@ impl<EventType> EventPublisher<EventType> {
self.queue.len() self.queue.len()
} }
#[inline]
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
/// Clears the current event queue. The events will not be processed/handled. /// Clears the current event queue. The events will not be processed/handled.
#[inline] #[inline]
pub fn clear(&mut self) { pub fn clear(&mut self) {
@ -87,6 +92,11 @@ impl<EventType, ContextType> EventListeners<EventType, ContextType> {
self.listeners.len() self.listeners.len()
} }
#[inline]
pub fn is_empty(&self) -> bool {
self.listeners.is_empty()
}
/// Unregisters all event listeners/managers previously registered with this manager. /// Unregisters all event listeners/managers previously registered with this manager.
#[inline] #[inline]
pub fn clear(&mut self) { pub fn clear(&mut self) {
@ -113,7 +123,7 @@ impl<EventType, ContextType> EventListeners<EventType, ContextType> {
// HACK?: comparing function pointers -- see above "HACK?" comment. same concern here. // HACK?: comparing function pointers -- see above "HACK?" comment. same concern here.
self.listeners.retain(|&l| l as usize != listener as usize); self.listeners.retain(|&l| l as usize != listener as usize);
// return true if the listener was removed // return true if the listener was removed
return before_size != self.listeners.len(); before_size != self.listeners.len()
} }
/// Moves the queue from the given [`EventPublisher`] to this manager in preparation for /// Moves the queue from the given [`EventPublisher`] to this manager in preparation for
@ -184,13 +194,7 @@ mod tests {
fn message_filter(event: &TestEvent, _context: &mut TestContext) -> bool { fn message_filter(event: &TestEvent, _context: &mut TestContext) -> bool {
match event { match event {
TestEvent::Message(s) => { TestEvent::Message(s) => *s == "filter",
if *s == "filter" {
true // means event was handled, and no subsequent listeners should be called
} else {
false
}
}
_ => false, _ => false,
} }
} }

View file

@ -354,13 +354,12 @@ fn load_image_section<T: ReadBytesExt>(
) -> Result<(IndexedBitmap, Option<Palette>), GifError> { ) -> Result<(IndexedBitmap, Option<Palette>), GifError> {
let descriptor = LocalImageDescriptor::read(reader)?; let descriptor = LocalImageDescriptor::read(reader)?;
let palette: Option<Palette>; let palette = if descriptor.has_local_color_table() {
if descriptor.has_local_color_table() {
let num_colors = bits_to_num_colors(descriptor.local_color_table_bits() as u32) as usize; let num_colors = bits_to_num_colors(descriptor.local_color_table_bits() as u32) as usize;
palette = Some(Palette::load_num_colors_from_bytes(reader, PaletteFormat::Normal, num_colors)?); Some(Palette::load_num_colors_from_bytes(reader, PaletteFormat::Normal, num_colors)?)
} else { } else {
palette = None; // we expect that there was a global color table previously None // we expect that there was a global color table previously
} };
let mut bitmap = IndexedBitmap::new(gif_header.screen_width as u32, gif_header.screen_height as u32).unwrap(); let mut bitmap = IndexedBitmap::new(gif_header.screen_width as u32, gif_header.screen_height as u32).unwrap();
let mut writer = bitmap.pixels_mut(); let mut writer = bitmap.pixels_mut();
@ -501,15 +500,10 @@ impl IndexedBitmap {
// local color tables. // local color tables.
palette.to_bytes(writer, PaletteFormat::Normal)?; palette.to_bytes(writer, PaletteFormat::Normal)?;
let transparent_color: u8; let transparent_color = match settings {
match settings { GifSettings::Default => 0,
GifSettings::Default => { GifSettings::TransparentColor(color) => color,
transparent_color = 0; };
}
GifSettings::TransparentColor(color) => {
transparent_color = color;
}
}
writer.write_u8(EXTENSION_INTRODUCER)?; writer.write_u8(EXTENSION_INTRODUCER)?;
writer.write_u8(GifExtensionLabel::GraphicControl as u8)?; writer.write_u8(GifExtensionLabel::GraphicControl as u8)?;
@ -522,7 +516,7 @@ impl IndexedBitmap {
}; };
graphic_control.write(writer)?; graphic_control.write(writer)?;
save_image_section(writer, &self)?; save_image_section(writer, self)?;
writer.write_u8(GIF_TRAILER)?; writer.write_u8(GIF_TRAILER)?;
Ok(()) Ok(())

View file

@ -623,7 +623,7 @@ impl IndexedBitmap {
y: i32, y: i32,
) { ) {
if let Some(src_region) = src.get(index) { if let Some(src_region) = src.get(index) {
self.blit_region_unchecked(method, src.bitmap(), &src_region, x, y); self.blit_region_unchecked(method, src.bitmap(), src_region, x, y);
} }
} }
} }

View file

@ -227,8 +227,7 @@ impl IndexedBitmap {
if run_count == 0 { if run_count == 0 {
run_count = 1; run_count = 1;
run_pixel = pixel; run_pixel = pixel;
} else { } else if (pixel != run_pixel) || (run_count >= 63) {
if (pixel != run_pixel) || (run_count >= 63) {
write_pcx_data(writer, run_count, run_pixel)?; write_pcx_data(writer, run_count, run_pixel)?;
run_count = 1; run_count = 1;
run_pixel = pixel; run_pixel = pixel;
@ -236,7 +235,6 @@ impl IndexedBitmap {
run_count += 1; run_count += 1;
} }
} }
}
// end the scanline, writing out whatever run we might have had going // end the scanline, writing out whatever run we might have had going
write_pcx_data(writer, run_count, run_pixel)?; write_pcx_data(writer, run_count, run_pixel)?;

View file

@ -83,7 +83,7 @@ impl ChunkHeader {
pub fn write<T: WriteBytesExt>(&self, writer: &mut T) -> Result<(), PngError> { pub fn write<T: WriteBytesExt>(&self, writer: &mut T) -> Result<(), PngError> {
writer.write_u32::<BigEndian>(self.size)?; writer.write_u32::<BigEndian>(self.size)?;
writer.write(&self.name)?; writer.write_all(&self.name)?;
Ok(()) Ok(())
} }
} }
@ -142,11 +142,11 @@ fn read_chunk_data<T: ReadBytesExt>(reader: &mut T, chunk_header: &ChunkHeader)
fn write_chunk<T: WriteBytesExt>(writer: &mut T, chunk_header: &ChunkHeader, data: &[u8]) -> Result<(), PngError> { fn write_chunk<T: WriteBytesExt>(writer: &mut T, chunk_header: &ChunkHeader, data: &[u8]) -> Result<(), PngError> {
let mut hasher = crc32fast::Hasher::new(); let mut hasher = crc32fast::Hasher::new();
hasher.write(&chunk_header.name); hasher.write(&chunk_header.name);
hasher.write(&data); hasher.write(data);
let checksum = hasher.finalize(); let checksum = hasher.finalize();
chunk_header.write(writer)?; chunk_header.write(writer)?;
writer.write(data)?; writer.write_all(data)?;
writer.write_u32::<BigEndian>(checksum)?; writer.write_u32::<BigEndian>(checksum)?;
Ok(()) Ok(())
@ -308,12 +308,7 @@ impl ScanlinePixelConverter<u8> for ScanlineBuffer {
let offset = x * self.bpp; let offset = x * self.bpp;
match self.format { match self.format {
ColorFormat::IndexedColor => Ok(self.current[offset]), ColorFormat::IndexedColor => Ok(self.current[offset]),
_ => { _ => Err(PngError::BadFile(format!("Unsupported color format for this PixelReader: {:?}", self.format))),
return Err(PngError::BadFile(format!(
"Unsupported color format for this PixelReader: {:?}",
self.format
)))
}
} }
} }
@ -324,12 +319,7 @@ impl ScanlinePixelConverter<u8> for ScanlineBuffer {
self.current[offset] = pixel; self.current[offset] = pixel;
Ok(()) Ok(())
} }
_ => { _ => Err(PngError::BadFile(format!("Unsupported color format for this PixelReader: {:?}", self.format))),
return Err(PngError::BadFile(format!(
"Unsupported color format for this PixelReader: {:?}",
self.format
)))
}
} }
} }
} }
@ -343,9 +333,9 @@ impl ScanlinePixelConverter<u32> for ScanlineBuffer {
if let Some(palette) = palette { if let Some(palette) = palette {
Ok(palette[color]) Ok(palette[color])
} else { } else {
return Err(PngError::BadFile(String::from( Err(PngError::BadFile(String::from(
"No palette to map indexed-color format pixels to RGBA format destination", "No palette to map indexed-color format pixels to RGBA format destination",
))); )))
} }
} }
ColorFormat::RGB => { ColorFormat::RGB => {
@ -361,12 +351,7 @@ impl ScanlinePixelConverter<u32> for ScanlineBuffer {
let a = self.current[offset + 3]; let a = self.current[offset + 3];
Ok(to_argb32(a, r, g, b)) Ok(to_argb32(a, r, g, b))
} }
_ => { _ => Err(PngError::BadFile(format!("Unsupported color format for this PixelReader: {:?}", self.format))),
return Err(PngError::BadFile(format!(
"Unsupported color format for this PixelReader: {:?}",
self.format
)))
}
} }
} }
@ -388,12 +373,7 @@ impl ScanlinePixelConverter<u32> for ScanlineBuffer {
self.current[offset + 3] = a; self.current[offset + 3] = a;
Ok(()) Ok(())
} }
_ => { _ => Err(PngError::BadFile(format!("Unsupported color format for this PixelReader: {:?}", self.format))),
return Err(PngError::BadFile(format!(
"Unsupported color format for this PixelReader: {:?}",
self.format
)))
}
} }
} }
} }
@ -563,11 +543,11 @@ where
let mut hasher = crc32fast::Hasher::new(); let mut hasher = crc32fast::Hasher::new();
hasher.write(&chunk_header.name); hasher.write(&chunk_header.name);
hasher.write(&sub_chunk_bytes); hasher.write(sub_chunk_bytes);
let checksum = hasher.finalize(); let checksum = hasher.finalize();
chunk_header.write(writer)?; chunk_header.write(writer)?;
writer.write(sub_chunk_bytes)?; writer.write_all(sub_chunk_bytes)?;
writer.write_u32::<BigEndian>(checksum)?; writer.write_u32::<BigEndian>(checksum)?;
} }
@ -594,7 +574,7 @@ impl IndexedBitmap {
} }
pub fn to_png_bytes<T: WriteBytesExt>(&self, writer: &mut T, palette: &Palette) -> Result<(), PngError> { pub fn to_png_bytes<T: WriteBytesExt>(&self, writer: &mut T, palette: &Palette) -> Result<(), PngError> {
write_png_bytes(writer, &self, ColorFormat::IndexedColor, Some(palette)) write_png_bytes(writer, self, ColorFormat::IndexedColor, Some(palette))
} }
pub fn to_png_file(&self, path: &Path, palette: &Palette) -> Result<(), PngError> { pub fn to_png_file(&self, path: &Path, palette: &Palette) -> Result<(), PngError> {
@ -618,7 +598,7 @@ impl RgbaBitmap {
pub fn to_png_bytes<T: WriteBytesExt>(&self, writer: &mut T, format: PngFormat) -> Result<(), PngError> { pub fn to_png_bytes<T: WriteBytesExt>(&self, writer: &mut T, format: PngFormat) -> Result<(), PngError> {
write_png_bytes( write_png_bytes(
writer, writer,
&self, self,
match format { match format {
PngFormat::RGB => ColorFormat::RGB, PngFormat::RGB => ColorFormat::RGB,
PngFormat::RGBA => ColorFormat::RGBA, PngFormat::RGBA => ColorFormat::RGBA,

View file

@ -56,11 +56,7 @@ impl<PixelType: Pixel> Bitmap<PixelType> {
/// clipping region, None is returned. /// clipping region, None is returned.
#[inline] #[inline]
pub fn get_pixel(&self, x: i32, y: i32) -> Option<PixelType> { pub fn get_pixel(&self, x: i32, y: i32) -> Option<PixelType> {
if let Some(pixels) = self.pixels_at(x, y) { self.pixels_at(x, y).map(|pixels| pixels[0])
Some(pixels[0])
} else {
None
}
} }
/// Gets the pixel at the given coordinates. The coordinates are not checked for validity, so /// Gets the pixel at the given coordinates. The coordinates are not checked for validity, so

View file

@ -577,7 +577,7 @@ impl RgbaBitmap {
y: i32, y: i32,
) { ) {
if let Some(src_region) = src.get(index) { if let Some(src_region) = src.get(index) {
self.blit_region_unchecked(method, src.bitmap(), &src_region, x, y); self.blit_region_unchecked(method, src.bitmap(), src_region, x, y);
} }
} }
} }

View file

@ -104,6 +104,11 @@ where
self.tiles.len() self.tiles.len()
} }
#[inline]
pub fn is_empty(&self) -> bool {
self.tiles.is_empty()
}
#[inline] #[inline]
pub fn get(&self, index: usize) -> Option<&Rect> { pub fn get(&self, index: usize) -> Option<&Rect> {
self.tiles.get(index) self.tiles.get(index)
@ -141,12 +146,12 @@ pub mod tests {
let mut atlas = BitmapAtlas::new(bmp); let mut atlas = BitmapAtlas::new(bmp);
let rect = Rect::new(0, 0, 16, 16); let rect = Rect::new(0, 0, 16, 16);
assert_eq!(0, atlas.add(rect.clone()).unwrap()); assert_eq!(0, atlas.add(rect).unwrap());
assert_eq!(rect, atlas[0]); assert_eq!(rect, atlas[0]);
assert_eq!(1, atlas.len()); assert_eq!(1, atlas.len());
let rect = Rect::new(16, 0, 16, 16); let rect = Rect::new(16, 0, 16, 16);
assert_eq!(1, atlas.add(rect.clone()).unwrap()); assert_eq!(1, atlas.add(rect).unwrap());
assert_eq!(rect, atlas[1]); assert_eq!(rect, atlas[1]);
assert_eq!(2, atlas.len()); assert_eq!(2, atlas.len());

View file

@ -82,7 +82,7 @@ impl BlendMap {
blend_map blend_map
.set_mapping( .set_mapping(
source_color, source_color,
idx as u8, idx,
(gradient_size - 1) - (lit / (256 / gradient_size as u32) as u8) + source_color, (gradient_size - 1) - (lit / (256 / gradient_size as u32) as u8) + source_color,
) )
.unwrap(); .unwrap();
@ -240,11 +240,7 @@ impl BlendMap {
/// is not in this blend map, `None` is returned. /// is not in this blend map, `None` is returned.
#[inline] #[inline]
pub fn blend(&self, source_color: u8, dest_color: u8) -> Option<u8> { pub fn blend(&self, source_color: u8, dest_color: u8) -> Option<u8> {
if let Some(mapping) = self.get_mapping(source_color) { self.get_mapping(source_color).map(|mapping| mapping[dest_color as usize])
Some(mapping[dest_color as usize])
} else {
None
}
} }
pub fn load_from_file(path: &Path) -> Result<Self, BlendMapError> { pub fn load_from_file(path: &Path) -> Result<Self, BlendMapError> {

View file

@ -21,12 +21,12 @@ pub static VGA_PALETTE_BYTES: &[u8] = include_bytes!("../../assets/vga.pal");
#[inline] #[inline]
fn from_6bit(value: u8) -> u8 { fn from_6bit(value: u8) -> u8 {
(value.wrapping_shl(2) | value.wrapping_shr(4)) as u8 value.wrapping_shl(2) | value.wrapping_shr(4)
} }
#[inline] #[inline]
fn to_6bit(value: u8) -> u8 { fn to_6bit(value: u8) -> u8 {
(value.wrapping_shr(2)) as u8 value.wrapping_shr(2)
} }
// vga bios (0-63) format // vga bios (0-63) format
@ -40,7 +40,7 @@ fn read_palette_6bit<T: ReadBytesExt>(reader: &mut T, num_colors: usize) -> Resu
let g = reader.read_u8()?; let g = reader.read_u8()?;
let b = reader.read_u8()?; let b = reader.read_u8()?;
let color = to_rgb32(from_6bit(r), from_6bit(g), from_6bit(b)); let color = to_rgb32(from_6bit(r), from_6bit(g), from_6bit(b));
colors[i as usize] = color; colors[i] = color;
} }
Ok(colors) Ok(colors)
} }
@ -54,7 +54,7 @@ fn write_palette_6bit<T: WriteBytesExt>(
return Err(PaletteError::OutOfRange(num_colors)); return Err(PaletteError::OutOfRange(num_colors));
} }
for i in 0..num_colors { for i in 0..num_colors {
let (r, g, b) = from_rgb32(colors[i as usize]); let (r, g, b) = from_rgb32(colors[i]);
writer.write_u8(to_6bit(r))?; writer.write_u8(to_6bit(r))?;
writer.write_u8(to_6bit(g))?; writer.write_u8(to_6bit(g))?;
writer.write_u8(to_6bit(b))?; writer.write_u8(to_6bit(b))?;
@ -73,7 +73,7 @@ fn read_palette_8bit<T: ReadBytesExt>(reader: &mut T, num_colors: usize) -> Resu
let g = reader.read_u8()?; let g = reader.read_u8()?;
let b = reader.read_u8()?; let b = reader.read_u8()?;
let color = to_rgb32(r, g, b); let color = to_rgb32(r, g, b);
colors[i as usize] = color; colors[i] = color;
} }
Ok(colors) Ok(colors)
} }
@ -87,7 +87,7 @@ fn write_palette_8bit<T: WriteBytesExt>(
return Err(PaletteError::OutOfRange(num_colors)); return Err(PaletteError::OutOfRange(num_colors));
} }
for i in 0..num_colors { for i in 0..num_colors {
let (r, g, b) = from_rgb32(colors[i as usize]); let (r, g, b) = from_rgb32(colors[i]);
writer.write_u8(r)?; writer.write_u8(r)?;
writer.write_u8(g)?; writer.write_u8(g)?;
writer.write_u8(b)?; writer.write_u8(b)?;
@ -425,8 +425,8 @@ impl Palette {
} as usize; } as usize;
let subset = &mut self.colors[start..=end]; let subset = &mut self.colors[start..=end];
match step.signum() { match step.signum() {
-1 => subset.rotate_left(step.abs() as usize), -1 => subset.rotate_left(step.unsigned_abs() as usize),
1 => subset.rotate_right(step.abs() as usize), 1 => subset.rotate_right(step.unsigned_abs() as usize),
_ => {} _ => {}
} }
} }

View file

@ -264,11 +264,7 @@ impl<ContextType> States<ContextType> {
} }
fn state_of_front_state(&self) -> Option<State> { fn state_of_front_state(&self) -> Option<State> {
if let Some(state) = self.states.front() { self.states.front().map(|state| state.current_state())
Some(state.current_state())
} else {
None
}
} }
fn process_state_changes(&mut self, context: &mut ContextType) -> Result<(), StateError> { fn process_state_changes(&mut self, context: &mut ContextType) -> Result<(), StateError> {
@ -522,11 +518,7 @@ mod tests {
if self.counter > 0 { if self.counter > 0 {
self.counter -= 1; self.counter -= 1;
} }
if self.counter == 0 { self.counter == 0
true
} else {
false
}
} }
fn state_change(&mut self, new_state: State, old_state: State, context: &mut TestContext) { fn state_change(&mut self, new_state: State, old_state: State, context: &mut TestContext) {

View file

@ -164,7 +164,7 @@ where
// preserve existing background first // preserve existing background first
self.cursor_background.blit_region( self.cursor_background.blit_region(
GeneralBlitMethod::Solid, GeneralBlitMethod::Solid,
&dest, dest,
&Rect::new(x, y, self.cursor.width(), self.cursor.height()), &Rect::new(x, y, self.cursor.width(), self.cursor.height()),
0, 0,
0, 0,

View file

@ -170,7 +170,7 @@ impl SystemResourcesConfig for DosLikeConfig {
channels: Some(TARGET_AUDIO_CHANNELS), channels: Some(TARGET_AUDIO_CHANNELS),
samples: None, samples: None,
}; };
let mut audio = Audio::new(audio_spec, &audio_subsystem)?; let mut audio = Audio::new(audio_spec, audio_subsystem)?;
audio.resume(); audio.resume();
let audio_queue = AudioQueue::new(&audio); let audio_queue = AudioQueue::new(&audio);

View file

@ -125,7 +125,7 @@ impl SystemResourcesConfig for StandardConfig {
channels: Some(TARGET_AUDIO_CHANNELS), channels: Some(TARGET_AUDIO_CHANNELS),
samples: None, samples: None,
}; };
let mut audio = Audio::new(audio_spec, &audio_subsystem)?; let mut audio = Audio::new(audio_spec, audio_subsystem)?;
audio.resume(); audio.resume();
let audio_queue = AudioQueue::new(&audio); let audio_queue = AudioQueue::new(&audio);

View file

@ -57,11 +57,11 @@ const MAX_BITS: usize = 12;
const MAX_CODE_VALUE: LzwCode = (1 as LzwCode).wrapping_shl(MAX_BITS as u32) - 1; const MAX_CODE_VALUE: LzwCode = (1 as LzwCode).wrapping_shl(MAX_BITS as u32) - 1;
fn is_valid_code_size_bits(code_size_bits: usize) -> bool { fn is_valid_code_size_bits(code_size_bits: usize) -> bool {
code_size_bits >= MIN_BITS && code_size_bits <= MAX_BITS (MIN_BITS..=MAX_BITS).contains(&code_size_bits)
} }
fn is_valid_gif_min_code_size_bits(min_code_size_bits: usize) -> bool { fn is_valid_gif_min_code_size_bits(min_code_size_bits: usize) -> bool {
min_code_size_bits >= MIN_BITS && min_code_size_bits <= GIF_MAX_CODE_SIZE_BITS (MIN_BITS..=GIF_MAX_CODE_SIZE_BITS).contains(&min_code_size_bits)
} }
fn get_bitmask_for_bits(bits: usize) -> u32 { fn get_bitmask_for_bits(bits: usize) -> u32 {
@ -111,7 +111,7 @@ impl LzwBytePacker {
pub fn increase_bit_size(&mut self) -> Result<usize, LzwBytePackingError> { pub fn increase_bit_size(&mut self) -> Result<usize, LzwBytePackingError> {
if self.current_bit_size >= MAX_BITS { if self.current_bit_size >= MAX_BITS {
return Err(LzwBytePackingError::UnsupportedCodeSizeBits(self.current_bit_size + 1)); Err(LzwBytePackingError::UnsupportedCodeSizeBits(self.current_bit_size + 1))
} else { } else {
self.current_bit_size += 1; self.current_bit_size += 1;
self.bitmask = get_bitmask_for_bits(self.current_bit_size); self.bitmask = get_bitmask_for_bits(self.current_bit_size);
@ -257,7 +257,7 @@ impl LzwByteUnpacker {
pub fn increase_bit_size(&mut self) -> Result<usize, LzwBytePackingError> { pub fn increase_bit_size(&mut self) -> Result<usize, LzwBytePackingError> {
if self.current_bit_size >= MAX_BITS { if self.current_bit_size >= MAX_BITS {
return Err(LzwBytePackingError::UnsupportedCodeSizeBits(self.current_bit_size + 1)); Err(LzwBytePackingError::UnsupportedCodeSizeBits(self.current_bit_size + 1))
} else { } else {
self.current_bit_size += 1; self.current_bit_size += 1;
self.bitmask = get_bitmask_for_bits(self.current_bit_size); self.bitmask = get_bitmask_for_bits(self.current_bit_size);

View file

@ -141,16 +141,16 @@ fn blended_pixel_drawing() {
let (mut screen, palette, blend_map) = setup_for_blending(); let (mut screen, palette, blend_map) = setup_for_blending();
for i in 0..10 { for i in 0..10 {
screen.set_blended_pixel(0 + i, 0 + i, 1, &blend_map); screen.set_blended_pixel(i, i, 1, &blend_map);
screen.set_blended_pixel(319 - i, 0 + i, 2, &blend_map); screen.set_blended_pixel(319 - i, i, 2, &blend_map);
screen.set_blended_pixel(0 + i, 239 - i, 3, &blend_map); screen.set_blended_pixel(i, 239 - i, 3, &blend_map);
screen.set_blended_pixel(319 - i, 239 - i, 4, &blend_map); screen.set_blended_pixel(319 - i, 239 - i, 4, &blend_map);
} }
unsafe { unsafe {
for i in 0..10 { for i in 0..10 {
screen.set_blended_pixel_unchecked(5 + i, 0 + i, 1, &blend_map); screen.set_blended_pixel_unchecked(5 + i, i, 1, &blend_map);
screen.set_blended_pixel_unchecked(314 - i, 0 + i, 2, &blend_map); screen.set_blended_pixel_unchecked(314 - i, i, 2, &blend_map);
screen.set_blended_pixel_unchecked(5 + i, 239 - i, 3, &blend_map); screen.set_blended_pixel_unchecked(5 + i, 239 - i, 3, &blend_map);
screen.set_blended_pixel_unchecked(314 - i, 239 - i, 4, &blend_map); screen.set_blended_pixel_unchecked(314 - i, 239 - i, 4, &blend_map);
} }

View file

@ -179,16 +179,16 @@ fn blended_pixel_drawing() {
let blend = BlendFunction::Blend; let blend = BlendFunction::Blend;
for i in 0..10 { for i in 0..10 {
screen.set_blended_pixel(0 + i, 0 + i, COLOR_BLUE_HALF_ALPHA, blend); screen.set_blended_pixel(i, i, COLOR_BLUE_HALF_ALPHA, blend);
screen.set_blended_pixel(319 - i, 0 + i, COLOR_GREEN_HALF_ALPHA, blend); screen.set_blended_pixel(319 - i, i, COLOR_GREEN_HALF_ALPHA, blend);
screen.set_blended_pixel(0 + i, 239 - i, COLOR_CYAN_HALF_ALPHA, blend); screen.set_blended_pixel(i, 239 - i, COLOR_CYAN_HALF_ALPHA, blend);
screen.set_blended_pixel(319 - i, 239 - i, COLOR_RED_HALF_ALPHA, blend); screen.set_blended_pixel(319 - i, 239 - i, COLOR_RED_HALF_ALPHA, blend);
} }
unsafe { unsafe {
for i in 0..10 { for i in 0..10 {
screen.set_blended_pixel_unchecked(5 + i, 0 + i, COLOR_BLUE_HALF_ALPHA, blend); screen.set_blended_pixel_unchecked(5 + i, i, COLOR_BLUE_HALF_ALPHA, blend);
screen.set_blended_pixel_unchecked(314 - i, 0 + i, COLOR_GREEN_HALF_ALPHA, blend); screen.set_blended_pixel_unchecked(314 - i, i, COLOR_GREEN_HALF_ALPHA, blend);
screen.set_blended_pixel_unchecked(5 + i, 239 - i, COLOR_CYAN_HALF_ALPHA, blend); screen.set_blended_pixel_unchecked(5 + i, 239 - i, COLOR_CYAN_HALF_ALPHA, blend);
screen.set_blended_pixel_unchecked(314 - i, 239 - i, COLOR_RED_HALF_ALPHA, blend); screen.set_blended_pixel_unchecked(314 - i, 239 - i, COLOR_RED_HALF_ALPHA, blend);
} }