# HG changeset patch # User Valentin Gatien-Baron # Date 1566822301 14400 # Node ID 62eabdf91f854238701716b555bbbe2c7fc08370 # Parent 96ddf83fc2679a54ecc6f5f388f868d7639040da rustfilepatterns: refactor the pattern of removing a prefix from a &[u8] Differential Revision: https://phab.mercurial-scm.org/D6766 diff -r 96ddf83fc267 -r 62eabdf91f85 rust/hg-core/src/filepatterns.rs --- a/rust/hg-core/src/filepatterns.rs Sun Aug 25 22:52:36 2019 -0400 +++ b/rust/hg-core/src/filepatterns.rs Mon Aug 26 08:25:01 2019 -0400 @@ -60,8 +60,8 @@ match c { b'*' => { for (source, repl) in GLOB_REPLACEMENTS { - if input.starts_with(source) { - input = &input[source.len()..]; + if let Some(rest) = input.drop_prefix(source) { + input = rest; res.extend(*repl); break; } @@ -269,8 +269,8 @@ continue; } - if line.starts_with(b"syntax:") { - let syntax = line[b"syntax:".len()..].trim(); + if let Some(syntax) = line.drop_prefix(b"syntax:") { + let syntax = syntax.trim(); if let Some(rel_syntax) = SYNTAXES.get(syntax) { current_syntax = rel_syntax; @@ -283,13 +283,14 @@ let mut line_syntax: &[u8] = ¤t_syntax; for (s, rels) in SYNTAXES.iter() { - if line.starts_with(rels) { + if let Some(rest) = line.drop_prefix(rels) { line_syntax = rels; - line = &line[rels.len()..]; + line = rest; break; - } else if line.starts_with(&[s, b":".as_ref()].concat()) { + } + if let Some(rest) = line.drop_prefix(&[s, &b":"[..]].concat()) { line_syntax = rels; - line = &line[s.len() + 1..]; + line = rest; break; } } diff -r 96ddf83fc267 -r 62eabdf91f85 rust/hg-core/src/utils.rs --- a/rust/hg-core/src/utils.rs Sun Aug 25 22:52:36 2019 -0400 +++ b/rust/hg-core/src/utils.rs Mon Aug 26 08:25:01 2019 -0400 @@ -40,6 +40,7 @@ fn trim_end(&self) -> &Self; fn trim_start(&self) -> &Self; fn trim(&self) -> &Self; + fn drop_prefix(&self, needle: &Self) -> Option<&Self>; } fn is_not_whitespace(c: &u8) -> bool { @@ -80,4 +81,12 @@ fn trim(&self) -> &[u8] { self.trim_start().trim_end() } + + fn drop_prefix(&self, needle: &Self) -> Option<&Self> { + if self.starts_with(needle) { + Some(&self[needle.len()..]) + } else { + None + } + } }