Sfoglia il codice sorgente

Avoid an allocation when printing help text

Benjamin Sago 8 anni fa
parent
commit
4018165e26
3 ha cambiato i file con 33 aggiunte e 19 eliminazioni
  1. 22 16
      src/options/help.rs
  2. 3 1
      src/options/misfire.rs
  3. 8 2
      src/options/mod.rs

+ 22 - 16
src/options/help.rs

@@ -1,4 +1,4 @@
-use getopts::Matches;
+use std::fmt;
 
 
 static OPTIONS: &str = r##"
@@ -45,25 +45,31 @@ LONG VIEW OPTIONS
 static GIT_HELP:      &str = r##"  --git              list each file's Git status, if tracked"##;
 static EXTENDED_HELP: &str = r##"  -@, --extended     list each file's extended attributes and sizes"##;
 
+#[derive(PartialEq, Debug)]
+pub struct HelpString {
+    pub only_long: bool,
+    pub git: bool,
+    pub xattrs: bool,
+}
 
-pub fn help_string(matches: &Matches, git: bool, xattr: bool) -> String {
-    let mut help = String::from("Usage:\n  exa [options] [files...]\n");
+impl fmt::Display for HelpString {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        try!(write!(f, "Usage:\n  exa [options] [files...]\n"));
 
-    if !matches.opt_present("long") {
-        help.push_str(OPTIONS);
-    }
+        if !self.only_long {
+            try!(write!(f, "{}", OPTIONS));
+        }
 
-    help.push_str(LONG_OPTIONS);
+        try!(write!(f, "{}", LONG_OPTIONS));
 
-    if git {
-        help.push('\n');
-        help.push_str(GIT_HELP);
-    }
+        if self.git {
+            try!(write!(f, "\n{}", GIT_HELP));
+        }
 
-    if xattr {
-        help.push('\n');
-        help.push_str(EXTENDED_HELP);
-    }
+        if self.xattrs {
+            try!(write!(f, "\n{}", EXTENDED_HELP));
+        }
 
-    help
+        Ok(())
+    }
 }

+ 3 - 1
src/options/misfire.rs

@@ -4,6 +4,8 @@ use std::num::ParseIntError;
 use getopts;
 use glob;
 
+use options::help::HelpString;
+
 
 /// A list of legal choices for an argument-taking option
 #[derive(PartialEq, Debug)]
@@ -28,7 +30,7 @@ pub enum Misfire {
 
     /// The user asked for help. This isn’t strictly an error, which is why
     /// this enum isn’t named Error!
-    Help(String),
+    Help(HelpString),
 
     /// The user wanted the version number.
     Version,

+ 8 - 2
src/options/mod.rs

@@ -12,7 +12,7 @@ mod filter;
 pub use self::filter::{FileFilter, SortField, SortCase};
 
 mod help;
-use self::help::help_string;
+use self::help::HelpString;
 
 mod misfire;
 pub use self::misfire::Misfire;
@@ -103,7 +103,13 @@ impl Options {
         };
 
         if matches.opt_present("help") {
-            return Err(Misfire::Help(help_string(&matches, cfg!(feature="git"), xattr::ENABLED)));
+            let help = HelpString {
+                only_long: matches.opt_present("long"),
+                git: cfg!(feature="git"),
+                xattrs: xattr::ENABLED,
+            };
+
+            return Err(Misfire::Help(help));
         }
         else if matches.opt_present("version") {
             return Err(Misfire::Version);