瀏覽代碼

Fix clippy issues

Dirkjan Ochtman 6 年之前
父節點
當前提交
8e66bc59b2
共有 6 個文件被更改,包括 115 次插入132 次删除
  1. 2 2
      idna/src/punycode.rs
  2. 38 54
      idna/src/uts46.rs
  3. 2 2
      idna/tests/uts46.rs
  4. 55 54
      url/src/host.rs
  5. 13 11
      url/src/parser.rs
  6. 5 9
      url/src/quirks.rs

+ 2 - 2
idna/src/punycode.rs

@@ -215,8 +215,8 @@ pub fn encode(input: &[char]) -> Option<String> {
 #[inline]
 #[inline]
 fn value_to_digit(value: u32) -> char {
 fn value_to_digit(value: u32) -> char {
     match value {
     match value {
-        0..=25 => (value as u8 + 'a' as u8) as char, // a..z
-        26..=35 => (value as u8 - 26 + '0' as u8) as char, // 0..9
+        0..=25 => (value as u8 + b'a') as char, // a..z
+        26..=35 => (value as u8 - 26 + b'0') as char, // 0..9
         _ => panic!(),
         _ => panic!(),
     }
     }
 }
 }

+ 38 - 54
idna/src/uts46.rs

@@ -19,7 +19,7 @@ use unicode_normalization::UnicodeNormalization;
 
 
 include!("uts46_mapping_table.rs");
 include!("uts46_mapping_table.rs");
 
 
-const PUNYCODE_PREFIX: &'static str = "xn--";
+const PUNYCODE_PREFIX: &str = "xn--";
 
 
 #[derive(Debug)]
 #[derive(Debug)]
 struct StringTableSlice {
 struct StringTableSlice {
@@ -131,26 +131,19 @@ fn passes_bidi(label: &str, is_bidi_domain: bool) -> bool {
         // LTR label
         // LTR label
         BidiClass::L => {
         BidiClass::L => {
             // Rule 5
             // Rule 5
-            loop {
-                match chars.next() {
-                    Some(c) => {
-                        if !matches!(
-                            bidi_class(c),
-                            BidiClass::L
-                                | BidiClass::EN
-                                | BidiClass::ES
-                                | BidiClass::CS
-                                | BidiClass::ET
-                                | BidiClass::ON
-                                | BidiClass::BN
-                                | BidiClass::NSM
-                        ) {
-                            return false;
-                        }
-                    }
-                    None => {
-                        break;
-                    }
+            while let Some(c) = chars.next() {
+                if !matches!(
+                    bidi_class(c),
+                    BidiClass::L
+                        | BidiClass::EN
+                        | BidiClass::ES
+                        | BidiClass::CS
+                        | BidiClass::ET
+                        | BidiClass::ON
+                        | BidiClass::BN
+                        | BidiClass::NSM
+                ) {
+                    return false;
                 }
                 }
             }
             }
 
 
@@ -184,37 +177,28 @@ fn passes_bidi(label: &str, is_bidi_domain: bool) -> bool {
             let mut found_an = false;
             let mut found_an = false;
 
 
             // Rule 2
             // Rule 2
-            loop {
-                match chars.next() {
-                    Some(c) => {
-                        let char_class = bidi_class(c);
-
-                        if char_class == BidiClass::EN {
-                            found_en = true;
-                        }
-                        if char_class == BidiClass::AN {
-                            found_an = true;
-                        }
+            for c in chars {
+                let char_class = bidi_class(c);
+                if char_class == BidiClass::EN {
+                    found_en = true;
+                } else if char_class == BidiClass::AN {
+                    found_an = true;
+                }
 
 
-                        if !matches!(
-                            char_class,
-                            BidiClass::R
-                                | BidiClass::AL
-                                | BidiClass::AN
-                                | BidiClass::EN
-                                | BidiClass::ES
-                                | BidiClass::CS
-                                | BidiClass::ET
-                                | BidiClass::ON
-                                | BidiClass::BN
-                                | BidiClass::NSM
-                        ) {
-                            return false;
-                        }
-                    }
-                    None => {
-                        break;
-                    }
+                if !matches!(
+                    char_class,
+                    BidiClass::R
+                        | BidiClass::AL
+                        | BidiClass::AN
+                        | BidiClass::EN
+                        | BidiClass::ES
+                        | BidiClass::CS
+                        | BidiClass::ET
+                        | BidiClass::ON
+                        | BidiClass::BN
+                        | BidiClass::NSM
+                ) {
+                    return false;
                 }
                 }
             }
             }
             // Rule 3
             // Rule 3
@@ -280,7 +264,7 @@ fn validate(label: &str, is_bidi_domain: bool, config: Config, errors: &mut Vec<
     // https://github.com/whatwg/url/issues/53
     // https://github.com/whatwg/url/issues/53
 
 
     // V3: neither begin nor end with a U+002D HYPHEN-MINUS
     // V3: neither begin nor end with a U+002D HYPHEN-MINUS
-    else if config.check_hyphens && (label.starts_with("-") || label.ends_with("-")) {
+    else if config.check_hyphens && (label.starts_with('-') || label.ends_with('-')) {
         errors.push(Error::ValidityCriteria);
         errors.push(Error::ValidityCriteria);
     }
     }
     // V4: not contain a U+002E FULL STOP
     // V4: not contain a U+002E FULL STOP
@@ -445,12 +429,12 @@ impl Config {
         }
         }
 
 
         if self.verify_dns_length {
         if self.verify_dns_length {
-            let domain = if result.ends_with(".") {
+            let domain = if result.ends_with('.') {
                 &result[..result.len() - 1]
                 &result[..result.len() - 1]
             } else {
             } else {
                 &*result
                 &*result
             };
             };
-            if domain.len() < 1 || domain.split('.').any(|label| label.len() < 1) {
+            if domain.is_empty() || domain.split('.').any(|label| label.is_empty()) {
                 errors.push(Error::TooShortForDns)
                 errors.push(Error::TooShortForDns)
             }
             }
             if domain.len() > 253 || domain.split('.').any(|label| label.len() > 63) {
             if domain.len() > 253 || domain.split('.').any(|label| label.len() > 63) {

+ 2 - 2
idna/tests/uts46.rs

@@ -12,12 +12,12 @@ use test::TestFn;
 pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
 pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
     // https://www.unicode.org/Public/idna/13.0.0/IdnaTestV2.txt
     // https://www.unicode.org/Public/idna/13.0.0/IdnaTestV2.txt
     for (i, line) in include_str!("IdnaTestV2.txt").lines().enumerate() {
     for (i, line) in include_str!("IdnaTestV2.txt").lines().enumerate() {
-        if line == "" || line.starts_with("#") {
+        if line == "" || line.starts_with('#') {
             continue;
             continue;
         }
         }
 
 
         // Remove comments
         // Remove comments
-        let line = match line.find("#") {
+        let line = match line.find('#') {
             Some(index) => &line[0..index],
             Some(index) => &line[0..index],
             None => line,
             None => line,
         };
         };

+ 55 - 54
url/src/host.rs

@@ -85,36 +85,35 @@ impl Host<String> {
         if domain.is_empty() {
         if domain.is_empty() {
             return Err(ParseError::EmptyHost);
             return Err(ParseError::EmptyHost);
         }
         }
-        if domain
-            .find(|c| {
-                matches!(
-                    c,
-                    '\0' | '\t'
-                        | '\n'
-                        | '\r'
-                        | ' '
-                        | '#'
-                        | '%'
-                        | '/'
-                        | ':'
-                        | '<'
-                        | '>'
-                        | '?'
-                        | '@'
-                        | '['
-                        | '\\'
-                        | ']'
-                        | '^'
-                )
-            })
-            .is_some()
-        {
-            return Err(ParseError::InvalidDomainCharacter);
-        }
-        if let Some(address) = parse_ipv4addr(&domain)? {
+
+        let is_invalid_domain_char = |c| {
+            matches!(
+                c,
+                '\0' | '\t'
+                    | '\n'
+                    | '\r'
+                    | ' '
+                    | '#'
+                    | '%'
+                    | '/'
+                    | ':'
+                    | '<'
+                    | '>'
+                    | '?'
+                    | '@'
+                    | '['
+                    | '\\'
+                    | ']'
+                    | '^'
+            )
+        };
+
+        if domain.find(is_invalid_domain_char).is_some() {
+            Err(ParseError::InvalidDomainCharacter)
+        } else if let Some(address) = parse_ipv4addr(&domain)? {
             Ok(Host::Ipv4(address))
             Ok(Host::Ipv4(address))
         } else {
         } else {
-            Ok(Host::Domain(domain.into()))
+            Ok(Host::Domain(domain))
         }
         }
     }
     }
 
 
@@ -126,33 +125,35 @@ impl Host<String> {
             }
             }
             return parse_ipv6addr(&input[1..input.len() - 1]).map(Host::Ipv6);
             return parse_ipv6addr(&input[1..input.len() - 1]).map(Host::Ipv6);
         }
         }
-        if input
-            .find(|c| {
-                matches!(
-                    c,
-                    '\0' | '\t'
-                        | '\n'
-                        | '\r'
-                        | ' '
-                        | '#'
-                        | '/'
-                        | ':'
-                        | '<'
-                        | '>'
-                        | '?'
-                        | '@'
-                        | '['
-                        | '\\'
-                        | ']'
-                        | '^'
-                )
-            })
-            .is_some()
-        {
-            return Err(ParseError::InvalidDomainCharacter);
+
+        let is_invalid_host_char = |c| {
+            matches!(
+                c,
+                '\0' | '\t'
+                    | '\n'
+                    | '\r'
+                    | ' '
+                    | '#'
+                    | '/'
+                    | ':'
+                    | '<'
+                    | '>'
+                    | '?'
+                    | '@'
+                    | '['
+                    | '\\'
+                    | ']'
+                    | '^'
+            )
+        };
+
+        if input.find(is_invalid_host_char).is_some() {
+            Err(ParseError::InvalidDomainCharacter)
+        } else {
+            Ok(Host::Domain(
+                utf8_percent_encode(input, CONTROLS).to_string(),
+            ))
         }
         }
-        let s = utf8_percent_encode(input, CONTROLS).to_string();
-        Ok(Host::Domain(s))
     }
     }
 }
 }
 
 

+ 13 - 11
url/src/parser.rs

@@ -105,6 +105,7 @@ macro_rules! syntax_violation_enum {
         ///
         ///
         /// This may be extended in the future so exhaustive matching is
         /// This may be extended in the future so exhaustive matching is
         /// discouraged with an unused variant.
         /// discouraged with an unused variant.
+        #[allow(clippy::manual_non_exhaustive)] // introduced in 1.40, MSRV is 1.36
         #[derive(PartialEq, Eq, Clone, Copy, Debug)]
         #[derive(PartialEq, Eq, Clone, Copy, Debug)]
         pub enum SyntaxViolation {
         pub enum SyntaxViolation {
             $(
             $(
@@ -573,7 +574,7 @@ impl<'a> Parser<'a> {
                         } else if let Some(host_str) = base_url.host_str() {
                         } else if let Some(host_str) = base_url.host_str() {
                             self.serialization.push_str(host_str);
                             self.serialization.push_str(host_str);
                             host_end = self.serialization.len();
                             host_end = self.serialization.len();
-                            host = base_url.host.clone();
+                            host = base_url.host;
                         }
                         }
                     }
                     }
                 }
                 }
@@ -776,7 +777,7 @@ impl<'a> Parser<'a> {
                 }
                 }
                 let path_start = base_url.path_start;
                 let path_start = base_url.path_start;
                 self.serialization.push_str(base_url.slice(..path_start));
                 self.serialization.push_str(base_url.slice(..path_start));
-                self.serialization.push_str("/");
+                self.serialization.push('/');
                 let remaining = self.parse_path(
                 let remaining = self.parse_path(
                     scheme_type,
                     scheme_type,
                     &mut true,
                     &mut true,
@@ -1036,7 +1037,7 @@ impl<'a> Parser<'a> {
         Ok((host, input))
         Ok((host, input))
     }
     }
 
 
-    fn get_file_host<'i>(input: Input<'i>) -> ParseResult<(Host<String>, Input)> {
+    fn get_file_host(input: Input) -> ParseResult<(Host<String>, Input)> {
         let (_, host_str, remaining) = Parser::file_host(input)?;
         let (_, host_str, remaining) = Parser::file_host(input)?;
         let host = match Host::parse(&host_str)? {
         let host = match Host::parse(&host_str)? {
             Host::Domain(ref d) if d == "localhost" => Host::Domain("".to_string()),
             Host::Domain(ref d) if d == "localhost" => Host::Domain("".to_string()),
@@ -1150,7 +1151,7 @@ impl<'a> Parser<'a> {
                 self.log_violation(SyntaxViolation::Backslash);
                 self.log_violation(SyntaxViolation::Backslash);
             }
             }
             // A special URL always has a non-empty path.
             // A special URL always has a non-empty path.
-            if !self.serialization.ends_with("/") {
+            if !self.serialization.ends_with('/') {
                 self.serialization.push('/');
                 self.serialization.push('/');
                 // We have already made sure the forward slash is present.
                 // We have already made sure the forward slash is present.
                 if maybe_c == Some('/') || maybe_c == Some('\\') {
                 if maybe_c == Some('/') || maybe_c == Some('\\') {
@@ -1239,7 +1240,7 @@ impl<'a> Parser<'a> {
                 | ".%2E" => {
                 | ".%2E" => {
                     debug_assert!(self.serialization.as_bytes()[segment_start - 1] == b'/');
                     debug_assert!(self.serialization.as_bytes()[segment_start - 1] == b'/');
                     self.serialization.truncate(segment_start);
                     self.serialization.truncate(segment_start);
-                    if self.serialization.ends_with("/")
+                    if self.serialization.ends_with('/')
                         && Parser::last_slash_can_be_removed(&self.serialization, path_start)
                         && Parser::last_slash_can_be_removed(&self.serialization, path_start)
                     {
                     {
                         self.serialization.pop();
                         self.serialization.pop();
@@ -1247,7 +1248,7 @@ impl<'a> Parser<'a> {
                     self.shorten_path(scheme_type, path_start);
                     self.shorten_path(scheme_type, path_start);
 
 
                     // and then if neither c is U+002F (/), nor url is special and c is U+005C (\), append the empty string to url’s path.
                     // and then if neither c is U+002F (/), nor url is special and c is U+005C (\), append the empty string to url’s path.
-                    if ends_with_slash && !self.serialization.ends_with("/") {
+                    if ends_with_slash && !self.serialization.ends_with('/') {
                         self.serialization.push('/');
                         self.serialization.push('/');
                     }
                     }
                 }
                 }
@@ -1255,7 +1256,7 @@ impl<'a> Parser<'a> {
                 // nor url is special and c is U+005C (\), append the empty string to url’s path.
                 // nor url is special and c is U+005C (\), append the empty string to url’s path.
                 "." | "%2e" | "%2E" => {
                 "." | "%2e" | "%2E" => {
                     self.serialization.truncate(segment_start);
                     self.serialization.truncate(segment_start);
-                    if !self.serialization.ends_with("/") {
+                    if !self.serialization.ends_with('/') {
                         self.serialization.push('/');
                         self.serialization.push('/');
                     }
                     }
                 }
                 }
@@ -1263,7 +1264,7 @@ impl<'a> Parser<'a> {
                     // If url’s scheme is "file", url’s path is empty, and buffer is a Windows drive letter, then
                     // If url’s scheme is "file", url’s path is empty, and buffer is a Windows drive letter, then
                     if scheme_type.is_file() && is_windows_drive_letter(segment_before_slash) {
                     if scheme_type.is_file() && is_windows_drive_letter(segment_before_slash) {
                         // Replace the second code point in buffer with U+003A (:).
                         // Replace the second code point in buffer with U+003A (:).
-                        if let Some(c) = segment_before_slash.chars().nth(0) {
+                        if let Some(c) = segment_before_slash.chars().next() {
                             self.serialization.truncate(segment_start);
                             self.serialization.truncate(segment_start);
                             self.serialization.push(c);
                             self.serialization.push(c);
                             self.serialization.push(':');
                             self.serialization.push(':');
@@ -1291,15 +1292,15 @@ impl<'a> Parser<'a> {
             //FIXME: log violation
             //FIXME: log violation
             let path = self.serialization.split_off(path_start);
             let path = self.serialization.split_off(path_start);
             self.serialization.push('/');
             self.serialization.push('/');
-            self.serialization.push_str(&path.trim_start_matches("/"));
+            self.serialization.push_str(&path.trim_start_matches('/'));
         }
         }
 
 
         input
         input
     }
     }
 
 
-    fn last_slash_can_be_removed(serialization: &String, path_start: usize) -> bool {
+    fn last_slash_can_be_removed(serialization: &str, path_start: usize) -> bool {
         let url_before_segment = &serialization[..serialization.len() - 1];
         let url_before_segment = &serialization[..serialization.len() - 1];
-        if let Some(segment_before_start) = url_before_segment.rfind("/") {
+        if let Some(segment_before_start) = url_before_segment.rfind('/') {
             // Do not remove the root slash
             // Do not remove the root slash
             segment_before_start >= path_start
             segment_before_start >= path_start
                 // Or a windows drive letter slash
                 // Or a windows drive letter slash
@@ -1357,6 +1358,7 @@ impl<'a> Parser<'a> {
         }
         }
     }
     }
 
 
+    #[allow(clippy::too_many_arguments)]
     fn with_query_and_fragment(
     fn with_query_and_fragment(
         mut self,
         mut self,
         scheme_type: SchemeType,
         scheme_type: SchemeType,

+ 5 - 9
url/src/quirks.rs

@@ -137,13 +137,9 @@ pub fn set_host(url: &mut Url, new_host: &str) -> Result<(), ()> {
     if host == Host::Domain("".to_string()) {
     if host == Host::Domain("".to_string()) {
         if !username(&url).is_empty() {
         if !username(&url).is_empty() {
             return Err(());
             return Err(());
-        }
-        if let Some(p) = opt_port {
-            if let Some(_) = p {
-                return Err(());
-            }
-        }
-        if url.port().is_some() {
+        } else if let Some(Some(_)) = opt_port {
+            return Err(());
+        } else if url.port().is_some() {
             return Err(());
             return Err(());
         }
         }
     }
     }
@@ -232,10 +228,10 @@ pub fn set_pathname(url: &mut Url, new_pathname: &str) {
     if url.cannot_be_a_base() {
     if url.cannot_be_a_base() {
         return;
         return;
     }
     }
-    if Some('/') == new_pathname.chars().nth(0)
+    if new_pathname.starts_with('/')
         || (SchemeType::from(url.scheme()).is_special()
         || (SchemeType::from(url.scheme()).is_special()
             // \ is a segment delimiter for 'special' URLs"
             // \ is a segment delimiter for 'special' URLs"
-            && Some('\\') == new_pathname.chars().nth(0))
+            && new_pathname.starts_with('\\'))
     {
     {
         url.set_path(new_pathname)
         url.set_path(new_pathname)
     } else {
     } else {