Skip to content

Commit

Permalink
Apply clippy lints for more idiomatic code
Browse files Browse the repository at this point in the history
  • Loading branch information
chipnertkj authored and emilio committed Apr 6, 2024
1 parent c3314d1 commit e89af28
Show file tree
Hide file tree
Showing 11 changed files with 157 additions and 165 deletions.
47 changes: 24 additions & 23 deletions color/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,21 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use super::*;
use crate::{ColorParser, PredefinedColorSpace, Color, RgbaLegacy};
use cssparser::{Parser, ParserInput};
use serde_json::{self, json, Value};
use cssparser::ParserInput;
use serde_json::{json, Value};

fn almost_equals(a: &Value, b: &Value) -> bool {
match (a, b) {
(&Value::Number(ref a), &Value::Number(ref b)) => {
(Value::Number(a), Value::Number(b)) => {
let a = a.as_f64().unwrap();
let b = b.as_f64().unwrap();
(a - b).abs() <= a.abs() * 1e-6
}

(&Value::Bool(a), &Value::Bool(b)) => a == b,
(&Value::String(ref a), &Value::String(ref b)) => a == b,
(&Value::Array(ref a), &Value::Array(ref b)) => {
a.len() == b.len()
&& a.iter()
.zip(b.iter())
.all(|(ref a, ref b)| almost_equals(*a, *b))
(Value::String(a), Value::String(b)) => a == b,
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| almost_equals(a, b))
}
(&Value::Object(_), &Value::Object(_)) => panic!("Not implemented"),
(&Value::Null, &Value::Null) => true,
Expand All @@ -43,8 +39,7 @@ fn assert_json_eq(results: Value, expected: Value, message: &str) {
}
}


fn run_raw_json_tests<F: Fn(Value, Value) -> ()>(json_data: &str, run: F) {
fn run_raw_json_tests<F: Fn(Value, Value)>(json_data: &str, run: F) {
let items = match serde_json::from_str(json_data) {
Ok(Value::Array(items)) => items,
other => panic!("Invalid JSON: {:?}", other),
Expand Down Expand Up @@ -92,11 +87,14 @@ fn color3() {
#[cfg_attr(all(miri, feature = "skip_long_tests"), ignore)]
#[test]
fn color3_hsl() {
run_color_tests(include_str!("../src/css-parsing-tests/color3_hsl.json"), |c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
})
run_color_tests(
include_str!("../src/css-parsing-tests/color3_hsl.json"),
|c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
},
)
}

/// color3_keywords.json is different: R, G and B are in 0..255 rather than 0..1
Expand All @@ -115,11 +113,14 @@ fn color3_keywords() {
#[cfg_attr(all(miri, feature = "skip_long_tests"), ignore)]
#[test]
fn color4_hwb() {
run_color_tests(include_str!("../src/css-parsing-tests/color4_hwb.json"), |c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
})
run_color_tests(
include_str!("../src/css-parsing-tests/color4_hwb.json"),
|c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
},
)
}

#[cfg_attr(all(miri, feature = "skip_long_tests"), ignore)]
Expand Down Expand Up @@ -355,7 +356,7 @@ fn generic_parser() {
];

for (input, expected) in TESTS {
let mut input = ParserInput::new(*input);
let mut input = ParserInput::new(input);
let mut input = Parser::new(&mut input);

let actual: OutputType = parse_color_with(&TestColorParser, &mut input).unwrap();
Expand Down
20 changes: 10 additions & 10 deletions macros/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ fn get_byte_from_lit(lit: &syn::Lit) -> u8 {

fn get_byte_from_expr_lit(expr: &syn::Expr) -> u8 {
match *expr {
syn::Expr::Lit(syn::ExprLit { ref lit, .. }) => {
get_byte_from_lit(lit)
}
syn::Expr::Lit(syn::ExprLit { ref lit, .. }) => get_byte_from_lit(lit),
_ => unreachable!(),
}
}
Expand All @@ -63,15 +61,17 @@ fn parse_pat_to_table<'a>(
table: &mut [u8; 256],
) {
match pat {
&syn::Pat::Lit(syn::PatLit { ref lit, .. }) => {
syn::Pat::Lit(syn::PatLit { ref lit, .. }) => {
let value = get_byte_from_lit(lit);
if table[value as usize] == 0 {
table[value as usize] = case_id;
}
}
&syn::Pat::Range(syn::PatRange { ref start, ref end, .. }) => {
let lo = get_byte_from_expr_lit(&start.as_ref().unwrap());
let hi = get_byte_from_expr_lit(&end.as_ref().unwrap());
syn::Pat::Range(syn::PatRange {
ref start, ref end, ..
}) => {
let lo = get_byte_from_expr_lit(start.as_ref().unwrap());
let hi = get_byte_from_expr_lit(end.as_ref().unwrap());
for value in lo..hi {
if table[value as usize] == 0 {
table[value as usize] = case_id;
Expand All @@ -81,14 +81,14 @@ fn parse_pat_to_table<'a>(
table[hi as usize] = case_id;
}
}
&syn::Pat::Wild(_) => {
syn::Pat::Wild(_) => {
for byte in table.iter_mut() {
if *byte == 0 {
*byte = case_id;
}
}
}
&syn::Pat::Ident(syn::PatIdent { ref ident, .. }) => {
syn::Pat::Ident(syn::PatIdent { ref ident, .. }) => {
assert_eq!(*wildcard, None);
*wildcard = Some(ident);
for byte in table.iter_mut() {
Expand All @@ -97,7 +97,7 @@ fn parse_pat_to_table<'a>(
}
}
}
&syn::Pat::Or(syn::PatOr { ref cases, .. }) => {
syn::Pat::Or(syn::PatOr { ref cases, .. }) => {
for case in cases {
parse_pat_to_table(case, case_id, wildcard, table);
}
Expand Down
6 changes: 3 additions & 3 deletions src/cow_rc_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use std::borrow::{Borrow, Cow};
use std::rc::Rc;
use std::{cmp, fmt, hash, marker, mem, ops, slice, str, ptr};
use std::{cmp, fmt, hash, marker, mem, ops, ptr, slice, str};

/// A string that is either shared (heap-allocated and reference-counted) or borrowed.
///
Expand All @@ -23,9 +23,9 @@ pub struct CowRcStr<'a> {
phantom: marker::PhantomData<Result<&'a str, Rc<String>>>,
}

fn _static_assert_same_size<'a>() {
fn _static_assert_same_size() {
// "Instantiate" the generic function without calling it.
let _ = mem::transmute::<CowRcStr<'a>, Option<CowRcStr<'a>>>;
let _ = mem::transmute::<CowRcStr<'_>, Option<CowRcStr<'_>>>;
}

impl<'a> From<Cow<'a, str>> for CowRcStr<'a> {
Expand Down
4 changes: 2 additions & 2 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ pub fn _cssparser_internal_to_lowercase<'a>(
let input_bytes =
unsafe { &*(input.as_bytes() as *const [u8] as *const [MaybeUninit<u8>]) };

buffer.copy_from_slice(&*input_bytes);
buffer.copy_from_slice(input_bytes);

// Same as above re layout, plus these bytes have been initialized:
let buffer = unsafe { &mut *(buffer as *mut [MaybeUninit<u8>] as *mut [u8]) };
Expand All @@ -195,7 +195,7 @@ pub fn _cssparser_internal_to_lowercase<'a>(
}

Some(
match input.bytes().position(|byte| matches!(byte, b'A'..=b'Z')) {
match input.bytes().position(|byte| byte.is_ascii_uppercase()) {
Some(first_uppercase) => make_ascii_lowercase(buffer, input, first_uppercase),
// common case: input is already lower-case
None => input,
Expand Down
16 changes: 8 additions & 8 deletions src/nth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use super::{BasicParseError, Parser, ParserInput, Token};
/// The input is typically the arguments of a function,
/// in which case the caller needs to check if the arguments’ parser is exhausted.
/// Return `Ok((A, B))`, or `Err(())` for a syntax error.
pub fn parse_nth<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(i32, i32), BasicParseError<'i>> {
pub fn parse_nth<'i>(input: &mut Parser<'i, '_>) -> Result<(i32, i32), BasicParseError<'i>> {
match *input.next()? {
Token::Number {
int_value: Some(b), ..
Expand All @@ -22,7 +22,7 @@ pub fn parse_nth<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(i32, i32), Basic
unit,
"n" => Ok(parse_b(input, a)?),
"n-" => Ok(parse_signless_b(input, a, -1)?),
_ => match parse_n_dash_digits(&*unit) {
_ => match parse_n_dash_digits(unit) {
Ok(b) => Ok((a, b)),
Err(()) => {
let unit = unit.clone();
Expand All @@ -40,8 +40,8 @@ pub fn parse_nth<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(i32, i32), Basic
"n-" => Ok(parse_signless_b(input, 1, -1)?),
"-n-" => Ok(parse_signless_b(input, -1, -1)?),
_ => {
let (slice, a) = if value.starts_with("-") {
(&value[1..], -1)
let (slice, a) = if let Some(stripped) = value.strip_prefix('-') {
(stripped, -1)
} else {
(&**value, 1)
};
Expand Down Expand Up @@ -81,7 +81,7 @@ pub fn parse_nth<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(i32, i32), Basic
}
}

fn parse_b<'i, 't>(input: &mut Parser<'i, 't>, a: i32) -> Result<(i32, i32), BasicParseError<'i>> {
fn parse_b<'i>(input: &mut Parser<'i, '_>, a: i32) -> Result<(i32, i32), BasicParseError<'i>> {
let start = input.state();
match input.next() {
Ok(&Token::Delim('+')) => parse_signless_b(input, a, 1),
Expand All @@ -98,8 +98,8 @@ fn parse_b<'i, 't>(input: &mut Parser<'i, 't>, a: i32) -> Result<(i32, i32), Bas
}
}

fn parse_signless_b<'i, 't>(
input: &mut Parser<'i, 't>,
fn parse_signless_b<'i>(
input: &mut Parser<'i, '_>,
a: i32,
b_sign: i32,
) -> Result<(i32, i32), BasicParseError<'i>> {
Expand All @@ -118,7 +118,7 @@ fn parse_n_dash_digits(string: &str) -> Result<i32, ()> {
let bytes = string.as_bytes();
if bytes.len() >= 3
&& bytes[..2].eq_ignore_ascii_case(b"n-")
&& bytes[2..].iter().all(|&c| matches!(c, b'0'..=b'9'))
&& bytes[2..].iter().all(|&c| c.is_ascii_digit())
{
Ok(parse_number_saturate(&string[1..]).unwrap()) // Include the minus sign
} else {
Expand Down
19 changes: 9 additions & 10 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl<'i, T> From<BasicParseError<'i>> for ParseError<'i, T> {
impl SourceLocation {
/// Create a new BasicParseError at this location for an unexpected token
#[inline]
pub fn new_basic_unexpected_token_error<'i>(self, token: Token<'i>) -> BasicParseError<'i> {
pub fn new_basic_unexpected_token_error(self, token: Token<'_>) -> BasicParseError<'_> {
BasicParseError {
kind: BasicParseErrorKind::UnexpectedToken(token),
location: self,
Expand All @@ -125,7 +125,7 @@ impl SourceLocation {

/// Create a new ParseError at this location for an unexpected token
#[inline]
pub fn new_unexpected_token_error<'i, E>(self, token: Token<'i>) -> ParseError<'i, E> {
pub fn new_unexpected_token_error<E>(self, token: Token<'_>) -> ParseError<'_, E> {
ParseError {
kind: ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(token)),
location: self,
Expand Down Expand Up @@ -652,9 +652,8 @@ impl<'i: 't, 't> Parser<'i, 't> {
let token = if using_cached_token {
let cached_token = self.input.cached_token.as_ref().unwrap();
self.input.tokenizer.reset(&cached_token.end_state);
match cached_token.token {
Token::Function(ref name) => self.input.tokenizer.see_function(name),
_ => {}
if let Token::Function(ref name) = cached_token.token {
self.input.tokenizer.see_function(name)
}
&cached_token.token
} else {
Expand Down Expand Up @@ -748,7 +747,7 @@ impl<'i: 't, 't> Parser<'i, 't> {
match self.parse_until_before(Delimiter::Comma, &mut parse_one) {
Ok(v) => values.push(v),
Err(e) if !ignore_errors => return Err(e),
Err(_) => {},
Err(_) => {}
}
match self.next() {
Err(_) => return Ok(values),
Expand Down Expand Up @@ -835,7 +834,7 @@ impl<'i: 't, 't> Parser<'i, 't> {
/// expect_ident, but clone the CowRcStr
#[inline]
pub fn expect_ident_cloned(&mut self) -> Result<CowRcStr<'i>, BasicParseError<'i>> {
self.expect_ident().map(|s| s.clone())
self.expect_ident().cloned()
}

/// Parse a <ident-token> whose unescaped value is an ASCII-insensitive match for the given value.
Expand All @@ -860,7 +859,7 @@ impl<'i: 't, 't> Parser<'i, 't> {
/// expect_string, but clone the CowRcStr
#[inline]
pub fn expect_string_cloned(&mut self) -> Result<CowRcStr<'i>, BasicParseError<'i>> {
self.expect_string().map(|s| s.clone())
self.expect_string().cloned()
}

/// Parse either a <ident-token> or a <string-token>, and return the unescaped value.
Expand All @@ -879,7 +878,7 @@ impl<'i: 't, 't> Parser<'i, 't> {
Token::UnquotedUrl(ref value) => Ok(value.clone()),
Token::Function(ref name) if name.eq_ignore_ascii_case("url") => {
self.parse_nested_block(|input| {
input.expect_string().map_err(Into::into).map(|s| s.clone())
input.expect_string().map_err(Into::into).cloned()
})
.map_err(ParseError::<()>::basic)
}
Expand All @@ -894,7 +893,7 @@ impl<'i: 't, 't> Parser<'i, 't> {
Token::QuotedString(ref value) => Ok(value.clone()),
Token::Function(ref name) if name.eq_ignore_ascii_case("url") => {
self.parse_nested_block(|input| {
input.expect_string().map_err(Into::into).map(|s| s.clone())
input.expect_string().map_err(Into::into).cloned()
})
.map_err(ParseError::<()>::basic)
}
Expand Down
16 changes: 8 additions & 8 deletions src/rules_and_declarations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::parser::{parse_nested_block, parse_until_after, ParseUntilErrorBehavi
///
/// Typical usage is `input.try_parse(parse_important).is_ok()`
/// at the end of a `DeclarationParser::parse_value` implementation.
pub fn parse_important<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(), BasicParseError<'i>> {
pub fn parse_important<'i>(input: &mut Parser<'i, '_>) -> Result<(), BasicParseError<'i>> {
input.expect_delim('!')?;
input.expect_ident_matching("important")
}
Expand Down Expand Up @@ -253,10 +253,10 @@ where
self.input.skip_whitespace();
let start = self.input.state();
match self.input.next_including_whitespace_and_comments().ok()? {
Token::CloseCurlyBracket |
Token::WhiteSpace(..) |
Token::Semicolon |
Token::Comment(..) => continue,
Token::CloseCurlyBracket
| Token::WhiteSpace(..)
| Token::Semicolon
| Token::Comment(..) => continue,
Token::AtKeyword(ref name) => {
let name = name.clone();
return Some(parse_at_rule(&start, name, self.input, &mut *self.parser));
Expand Down Expand Up @@ -294,7 +294,7 @@ where
&mut *self.parser,
Delimiter::Semicolon | Delimiter::CurlyBracketBlock,
) {
return Some(Ok(qual))
return Some(Ok(qual));
}
}

Expand Down Expand Up @@ -367,7 +367,7 @@ where
let start = self.input.state();
let at_keyword = match self.input.next_byte()? {
b'@' => match self.input.next_including_whitespace_and_comments() {
Ok(&Token::AtKeyword(ref name)) => Some(name.clone()),
Ok(Token::AtKeyword(name)) => Some(name.clone()),
_ => {
self.input.reset(&start);
None
Expand Down Expand Up @@ -503,5 +503,5 @@ where
input.expect_curly_bracket_block()?;
// Do this here so that we consume the `{` even if the prelude is `Err`.
let prelude = prelude?;
parse_nested_block(input, |input| parser.parse_block(prelude, &start, input))
parse_nested_block(input, |input| parser.parse_block(prelude, start, input))
}
Loading

0 comments on commit e89af28

Please sign in to comment.