~saiko/cmdparser

1c1e5a9d4aef395ffed336d0b723af2613fb4d59 — 2xsaiko 6 months ago 4bd3cab master
Add escape()
2 files changed, 28 insertions(+), 0 deletions(-)

M src/base.rs
M src/lib.rs
M src/base.rs => src/base.rs +27 -0
@@ 237,3 237,30 @@ fn tokenize(s: &str) -> Vec<Vec<String>> {

    commands
}

pub fn escape(s: &str) -> Cow<str> {
    if s.is_empty() { return "".into(); }

    let escaped = if s.contains('\\') || s.contains('"') {
        s
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .into()
    } else {
        s.into()
    };

    if s.contains(' ') || s.contains(';') {
        format!("\"{}\"", escaped).into()
    } else {
        escaped
    }
}

#[test]
fn test_escape() {
    assert_eq!("\"Test String\"", escape("Test String"));
    assert_eq!("\\\",./\\\\", escape("\",./\\"));
    assert_eq!("\" \\\",./\\\\ \"", escape(" \",./\\ "));
    assert_eq!("blah_blah-blah", escape("blah_blah-blah"));
}
\ No newline at end of file

M src/lib.rs => src/lib.rs +1 -0
@@ 1,6 1,7 @@
#![feature(box_syntax)]

pub use base::*;

#[cfg(feature = "engine")]
pub use engine::*;