D6766: rustfilepatterns: refactor the pattern of removing a prefix from a &[u8]

valentin.gatienbaron (Valentin Gatien-Baron) phabricator at mercurial-scm.org
Mon Aug 26 08:29:15 EDT 2019


valentin.gatienbaron created this revision.
Herald added subscribers: mercurial-devel, kevincox, durin42.
Herald added a reviewer: hg-reviewers.

REPOSITORY
  rHG Mercurial

REVISION DETAIL
  https://phab.mercurial-scm.org/D6766

AFFECTED FILES
  rust/hg-core/src/filepatterns.rs
  rust/hg-core/src/utils.rs

CHANGE DETAILS

diff --git a/rust/hg-core/src/utils.rs b/rust/hg-core/src/utils.rs
--- a/rust/hg-core/src/utils.rs
+++ b/rust/hg-core/src/utils.rs
@@ -41,6 +41,7 @@
     fn trim_end(&self) -> &Self;
     fn trim_start(&self) -> &Self;
     fn trim(&self) -> &Self;
+    fn chop_prefix(&self, needle:&Self) -> Option<&Self>;
 }
 
 fn is_not_whitespace(c: &u8) -> bool {
@@ -81,4 +82,12 @@
     fn trim(&self) -> &[u8] {
         self.trim_start().trim_end()
     }
+
+    fn chop_prefix(&self, needle:&Self) -> Option<&Self> {
+        if self.starts_with(needle) {
+            Some(&self[needle.len()..])
+        } else {
+            None
+        }
+    }
 }
diff --git a/rust/hg-core/src/filepatterns.rs b/rust/hg-core/src/filepatterns.rs
--- a/rust/hg-core/src/filepatterns.rs
+++ b/rust/hg-core/src/filepatterns.rs
@@ -59,8 +59,8 @@
         match c {
             b'*' => {
                 for (source, repl) in GLOB_REPLACEMENTS {
-                    if input.starts_with(source) {
-                        input = &input[source.len()..];
+                    if let Some(rest) = input.chop_prefix(source) {
+                        input = rest;
                         res.extend(*repl);
                         break;
                     }
@@ -268,8 +268,8 @@
             continue;
         }
 
-        if line.starts_with(b"syntax:") {
-            let syntax = line[b"syntax:".len()..].trim();
+        if let Some(syntax) = line.chop_prefix(b"syntax:") {
+            let syntax = syntax.trim();
 
             if let Some(rel_syntax) = SYNTAXES.get(syntax) {
                 current_syntax = rel_syntax;
@@ -282,13 +282,14 @@
         let mut line_syntax: &[u8] = &current_syntax;
 
         for (s, rels) in SYNTAXES.iter() {
-            if line.starts_with(rels) {
+            if let Some(rest) = line.chop_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.chop_prefix(&[s, &b":"[..]].concat()) {
                 line_syntax = rels;
-                line = &line[s.len() + 1..];
+                line = rest;
                 break;
             }
         }



To: valentin.gatienbaron, #hg-reviewers
Cc: durin42, kevincox, mercurial-devel


More information about the Mercurial-devel mailing list