Skip to content

Commit

Permalink
Clean up code and make clippy changes
Browse files Browse the repository at this point in the history
Collapse if else statements in color_difference.rs
Use !is_empty instead of `... > 0` comparisons in gradient.rs
Use strip_prefix instead of manually stripping, avoids manual indexing
Remove extraneous clones, into_iters, and closures
Simplify matching on single condition to if let
Remove format! in favor of to_string
Fix deprecated image functions in examples
Change some as casts to use direct `from` casts when applicable
  • Loading branch information
okaneco committed Nov 19, 2020
1 parent 7b8272e commit b83f193
Show file tree
Hide file tree
Showing 13 changed files with 42 additions and 66 deletions.
2 changes: 1 addition & 1 deletion palette/examples/hue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use palette::{FromColor, Hsl, Hue, Lch, Pixel, Srgb};
fn main() {
let mut image = image::open("example-data/input/fruits.png")
.expect("could not open 'example-data/input/fruits.png'")
.to_rgb();
.to_rgb8();

//Shift hue by 180 degrees as HSL in bottom left part, and as LCh in top
//right part. Notice how LCh manages to preserve the apparent lightness of
Expand Down
4 changes: 2 additions & 2 deletions palette/examples/saturate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use image::{GenericImage, GenericImageView};
fn main() {
let mut image = image::open("example-data/input/cat.png")
.expect("could not open 'example-data/input/cat.png'")
.to_rgb();
.to_rgb8();

let width = image.width();
let height = image.height();
Expand Down Expand Up @@ -49,7 +49,7 @@ fn main() {
}
}
}

let _ = std::fs::create_dir("example-data/output");
match image.save("example-data/output/saturate.png") {
Ok(()) => println!("see 'example-data/output/saturate.png' for the result"),
Expand Down
8 changes: 2 additions & 6 deletions palette/src/blend/equations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,8 @@ where
Equation::Add => src_color.component_wise(&dst_color, |a, b| a + b),
Equation::Subtract => src_color.component_wise(&dst_color, |a, b| a - b),
Equation::ReverseSubtract => dst_color.component_wise(&src_color, |a, b| a - b),
Equation::Min => source
.color
.component_wise(&destination.color, |a, b| a.min(b)),
Equation::Max => source
.color
.component_wise(&destination.color, |a, b| a.max(b)),
Equation::Min => source.color.component_wise(&destination.color, Float::min),
Equation::Max => source.color.component_wise(&destination.color, Float::max),
};

let alpha = match self.alpha_equation {
Expand Down
30 changes: 9 additions & 21 deletions palette/src/color_difference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,29 +60,23 @@ pub fn get_ciede_difference<T: FloatComponent>(this: &LabColorDiff<T>, other: &L

let delta_h_prime: T = if c_one_prime == T::zero() || c_two_prime == T::zero() {
from_f64(0.0)
} else if h_prime_difference <= from_f64(180.0) {
h_two_prime - h_one_prime
} else if h_two_prime <= h_one_prime {
h_two_prime - h_one_prime + from_f64(360.0)
} else {
if h_prime_difference <= from_f64(180.0) {
h_two_prime - h_one_prime
} else {
if h_two_prime <= h_one_prime {
h_two_prime - h_one_prime + from_f64(360.0)
} else {
h_two_prime - h_one_prime - from_f64(360.0)
}
}
h_two_prime - h_one_prime - from_f64(360.0)
};

let delta_big_h_prime = from_f64::<T>(2.0)
* (c_one_prime * c_two_prime).sqrt()
* (delta_h_prime / from_f64(2.0) * pi_over_180).sin();
let h_bar_prime = if c_one_prime == T::zero() || c_two_prime == T::zero() {
h_one_prime + h_two_prime
} else if h_prime_difference > from_f64(180.0) {
(h_one_prime + h_two_prime + from_f64(360.0)) / from_f64(2.0)
} else {
if h_prime_difference > from_f64(180.0) {
(h_one_prime + h_two_prime + from_f64(360.0)) / from_f64(2.0)
} else {
(h_one_prime + h_two_prime) / from_f64(2.0)
}
(h_one_prime + h_two_prime) / from_f64(2.0)
};

let l_bar = (this.l + other.l) / from_f64(2.0);
Expand All @@ -103,13 +97,7 @@ pub fn get_ciede_difference<T: FloatComponent>(this: &LabColorDiff<T>, other: &L
* (-(((h_bar_prime - from_f64(275.0)) / from_f64(25.0))
* ((h_bar_prime - from_f64(275.0)) / from_f64(25.0))))
.exp();
let c_bar_prime_pow_seven = c_bar_prime
* c_bar_prime
* c_bar_prime
* c_bar_prime
* c_bar_prime
* c_bar_prime
* c_bar_prime;
let c_bar_prime_pow_seven = c_bar_prime.powi(7);
let r_c: T = from_f64::<T>(2.0)
* (c_bar_prime_pow_seven / (c_bar_prime_pow_seven + twenty_five_pow_seven)).sqrt();
let r_t = -r_c * (from_f64::<T>(2.0) * delta_theta * pi_over_180).sin();
Expand Down
10 changes: 5 additions & 5 deletions palette/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,9 @@ macro_rules! convert_double_to_uint {
impl IntoComponent<f32> for u8 {
#[inline]
fn into_component(self) -> f32 {
let comp_u = self as u32 + C23;
let comp_u = u32::from(self) + C23;
let comp_f = f32::from_bits(comp_u) - f32::from_bits(C23);
let max_u = core::u8::MAX as u32 + C23;
let max_u = u32::from(core::u8::MAX) + C23;
let max_f = (f32::from_bits(max_u) - f32::from_bits(C23)).recip();
comp_f * max_f
}
Expand All @@ -172,9 +172,9 @@ impl IntoComponent<f32> for u8 {
impl IntoComponent<f64> for u8 {
#[inline]
fn into_component(self) -> f64 {
let comp_u = self as u64 + C52;
let comp_u = u64::from(self) + C52;
let comp_f = f64::from_bits(comp_u) - f64::from_bits(C52);
let max_u = core::u8::MAX as u64 + C52;
let max_u = u64::from(core::u8::MAX) + C52;
let max_f = (f64::from_bits(max_u) - f64::from_bits(C52)).recip();
comp_f * max_f
}
Expand Down Expand Up @@ -218,7 +218,7 @@ macro_rules! convert_uint_to_uint {
impl IntoComponent<f64> for f32 {
#[inline]
fn into_component(self) -> f64 {
self as f64
f64::from(self)
}
}
convert_float_to_uint!(f32; direct (u8, u16); via f64 (u32, u64, u128););
Expand Down
4 changes: 2 additions & 2 deletions palette/src/gradient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl<C: Mix + Clone> Gradient<C> {
C::Scalar: FromF64,
{
let mut points: Vec<_> = colors.into_iter().map(|c| (C::Scalar::zero(), c)).collect();
assert!(points.len() > 0);
assert!(!points.is_empty());
let step_size = C::Scalar::one() / from_f64(max(points.len() - 1, 1) as f64);

for (i, &mut (ref mut p, _)) in points.iter_mut().enumerate() {
Expand All @@ -45,7 +45,7 @@ impl<C: Mix + Clone> Gradient<C> {
/// be at least one color and they are expected to be ordered by their
/// position value.
pub fn with_domain(colors: Vec<(C::Scalar, C)>) -> Gradient<C> {
assert!(colors.len() > 0);
assert!(!colors.is_empty());

//Maybe sort the colors?
Gradient(colors)
Expand Down
9 changes: 3 additions & 6 deletions palette/src/relative_contrast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub trait RelativeContrast {
/// The type of the contrast ratio.
type Scalar: FromF64 + PartialOrd;

/// Calculate contrast ratio between two colors.
/// Calculate the contrast ratio between two colors.
fn get_contrast_ratio(&self, other: &Self) -> Self::Scalar;
/// Verify the contrast between two colors satisfies SC 1.4.3. Contrast
/// is at least 4.5:1 (Level AA).
Expand Down Expand Up @@ -81,13 +81,10 @@ pub trait RelativeContrast {
}
}

/// Calculate a ratio between two `luma` values.
/// Calculate the ratio between two `luma` values.
pub fn contrast_ratio<T>(luma1: T, luma2: T) -> T
where
T: Add<Output = T>,
T: Div<Output = T>,
T: FromF64,
T: Component,
T: Component + FromF64 + Add<Output = T> + Div<Output = T>,
{
if luma1 > luma2 {
(luma1 + from_f64(0.05)) / (luma2 + from_f64(0.05))
Expand Down
2 changes: 1 addition & 1 deletion palette/src/rgb/rgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1060,7 +1060,7 @@ impl<S: RgbStandard> FromStr for Rgb<S, u8> {
// Parses a color hex code of format '#ff00bb' or '#abc' into a
// Rgb<S, u8> instance.
fn from_str(hex: &str) -> Result<Self, Self::Err> {
let hex_code = if hex.starts_with('#') { &hex[1..] } else { hex };
let hex_code = hex.strip_prefix('#').map_or(hex, |stripped| stripped);
match hex_code.len() {
3 => {
let red = u8::from_str_radix(&hex_code[..1], 16)?;
Expand Down
2 changes: 1 addition & 1 deletion palette_derive/src/alpha/with_alpha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn derive(item: TokenStream) -> ::std::result::Result<TokenStream, Vec<::syn
attrs,
..
} = syn::parse(item).map_err(|error| vec![error])?;
let generics = original_generics.clone();
let generics = original_generics;

let item_meta: TypeItemAttributes = parse_namespaced_attributes(attrs)?;

Expand Down
4 changes: 1 addition & 3 deletions palette_derive/src/convert/from_color_unclamped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,7 @@ fn prepare_from_impl(
generics: &Generics,
generic_component: bool,
) -> Result<Vec<FromImplParameters>> {
let included_colors = COLOR_TYPES
.into_iter()
.filter(|&&color| !skip.contains(color));
let included_colors = COLOR_TYPES.iter().filter(|&&color| !skip.contains(color));
let linear_path = util::path(&["encoding", "Linear"], meta.internal);

let mut parameters = Vec::new();
Expand Down
27 changes: 12 additions & 15 deletions palette_derive/src/encoding/pixel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub fn derive(tokens: TokenStream) -> std::result::Result<TokenStream, Vec<syn::
} else {
errors.push(syn::Error::new(
Span::call_site(),
format!("`Pixel` can only be derived for structs with one or more fields"),
"`Pixel` can only be derived for structs with one or more fields".to_string(),
));

return Err(errors);
Expand All @@ -127,23 +127,20 @@ fn is_repr_c(attributes: &[Attribute]) -> std::result::Result<bool, Vec<syn::Err
for attribute in attributes {
let attribute_name = attribute.path.get_ident().map(ToString::to_string);

match attribute_name.as_deref() {
Some("repr") => {
let items = match meta::parse_tuple_attribute(attribute.tokens.clone()) {
Ok(items) => items,
Err(error) => {
errors.push(error);
continue;
}
};
if let Some("repr") = attribute_name.as_deref() {
let items = match meta::parse_tuple_attribute(attribute.tokens.clone()) {
Ok(items) => items,
Err(error) => {
errors.push(error);
continue;
}
};

let contains_c = items.into_iter().find(|item: &Ident| item == "C").is_some();
let contains_c = items.iter().any(|item: &Ident| item == "C");

if contains_c {
return Ok(true);
}
if contains_c {
return Ok(true);
}
_ => {}
}
}

Expand Down
2 changes: 1 addition & 1 deletion palette_derive/src/meta/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ pub fn parse_tuple_attribute<T: Parse>(tts: TokenStream) -> Result<Vec<T>> {
Ok(tuple)
}

parse_generic_tuple.parse2(tts.clone())
parse_generic_tuple.parse2(tts)
}

fn parse_meta_list(buffer: &ParseBuffer) -> syn::Result<Punctuated<NestedMeta, Token![,]>> {
Expand Down
4 changes: 2 additions & 2 deletions palette_derive/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use syn::{parse_quote, Ident, Type};
pub fn path<'a, P: AsRef<[&'a str]>>(path: P, internal: bool) -> TokenStream {
let path = path
.as_ref()
.into_iter()
.iter()
.map(|&ident| Ident::new(ident, Span::call_site()));

if internal {
Expand All @@ -18,7 +18,7 @@ pub fn path<'a, P: AsRef<[&'a str]>>(path: P, internal: bool) -> TokenStream {

pub fn path_type(path: &[&str], internal: bool) -> Type {
let path = path
.into_iter()
.iter()
.map(|&ident| Ident::new(ident, Span::call_site()));

if internal {
Expand Down

0 comments on commit b83f193

Please sign in to comment.