From 684089bdf00f2695d05ee93957bc26f66678d0ba Mon Sep 17 00:00:00 2001 From: Andreas Molzer Date: Tue, 1 Oct 2019 09:33:50 +0200 Subject: [PATCH] Fix strict const_err An array is indexed with constants that exceed its size. This is inopportune even in a branch that never gets executed. This changes it so that the indexing happens on a slice. Also removes a bunch of annotations by avoiding primitive casts with explicit type annotations in constants. --- src/color.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/color.rs b/src/color.rs index e6afd436ed..4cc77fcb14 100644 --- a/src/color.rs +++ b/src/color.rs @@ -100,15 +100,16 @@ impl Pixel for $ident { &mut self.0 } - #[allow(trivial_casts)] fn channels4(&self) -> (T, T, T, T) { + const CHANNELS: usize = $channels; let mut channels = [T::max_value(); 4]; - channels[0..$channels].copy_from_slice(&self.0); + channels[0..CHANNELS].copy_from_slice(&self.0); (channels[0], channels[1], channels[2], channels[3]) } fn from_channels(a: T, b: T, c: T, d: T,) -> $ident { - *<$ident as Pixel>::from_slice(&[a, b, c, d][..$channels]) + const CHANNELS: usize = $channels; + *<$ident as Pixel>::from_slice(&[a, b, c, d][..CHANNELS]) } fn from_slice(slice: &[T]) -> &$ident { @@ -174,13 +175,14 @@ impl Pixel for $ident { this } - #[allow(trivial_casts)] fn apply_with_alpha(&mut self, mut f: F, mut g: G) where F: FnMut(T) -> T, G: FnMut(T) -> T { - for v in self.0[..$channels as usize-$alphas as usize].iter_mut() { + const ALPHA: usize = $channels - $alphas; + for v in self.0[..ALPHA].iter_mut() { *v = f(*v) } - if $alphas as usize != 0 { - let v = &mut self.0[$channels as usize-$alphas as usize]; + // The branch of this match is `const`. This way ensures that no subexpression fails the + // `const_err` lint (the expression `self.0[ALPHA]` would). + if let Some(v) = self.0.get_mut(ALPHA) { *v = g(*v) } }