Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. pub fn escape_shell_arg(arg: &str) -> String {
  2. let mut output = String::new();
  3.  
  4. for ch in arg.chars() {
  5. match ch {
  6. // Output a closing single quote, an escaped single quote, and then
  7. // resume the string by outputting a single quote.
  8. '\'' => output.extend(r"'\''".chars()),
  9.  
  10. // Output a closing single quote, an escaped backslash, and then
  11. // resume the string literal by outputting a single quote.
  12. '\\' => output.extend(r"'\\'".chars()),
  13.  
  14. // Other characters should be safe
  15. ch => output.push(ch),
  16. }
  17. }
  18.  
  19. <[&str]>::join(&["'", &output, "'"], "")
  20. }
  21.  
  22. #[cfg(test)]
  23. mod test {
  24. use super::escape_shell_arg;
  25.  
  26. // static INPUTS: &[&str] = [
  27. // "hello, world",
  28. // "i'm tricky",
  29. // r#"this "one" is \"weird\""#,
  30. // ];
  31.  
  32. #[test]
  33. fn hello_world() {
  34. assert_eq!("'hello, world'", escape_shell_arg("hello, world"));
  35. }
  36.  
  37. #[test]
  38. fn escape_single_quote() {
  39. assert_eq!(r"'i'\''m tricky'", escape_shell_arg("i'm tricky"));
  40. }
  41.  
  42. #[test]
  43. fn escape_backslash() {
  44. assert_eq!(r"'C:'\\'Windows'\\'System32'", escape_shell_arg(r"C:\Windows\System32"));
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement