1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Low-level argument parsing.

use std::ffi::{OsStr, OsString};

/// Trait for string types that can be parsed as command-line arguments.
pub trait ArgString: Sized {
    /// Parse the string as a command-line argument.
    ///
    /// On failure, return the input.
    fn parse_arg(self) -> Result<ParsedArg<Self>, Self>;

    /// Convert the argument into a str if it is a valid Unicode string.
    fn to_str(&self) -> Option<&str>;

    /// Convert the argument into an OsStr.
    fn to_osstr(&self) -> &OsStr;
}

fn is_arg_name(c: char) -> bool {
    match c {
        'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => true,
        _ => false,
    }
}

impl ArgString for String {
    fn parse_arg(self) -> Result<ParsedArg<String>, String> {
        let mut chars = self.chars();
        match chars.next() {
            Some('-') => (),
            _ => return Ok(ParsedArg::Positional(self)),
        }
        let cur = chars.clone();
        match chars.next() {
            Some('-') => {
                if chars.as_str().is_empty() {
                    return Ok(ParsedArg::EndOfFlags);
                }
            }
            Some(_) => chars = cur,
            None => return Ok(ParsedArg::Positional(self)),
        }
        let body = chars.as_str();
        let (name, value) = match body.find('=') {
            Some(idx) => (&body[..idx], Some(&body[idx + 1..])),
            None => (body, None),
        };
        if name.is_empty() || !name.chars().all(is_arg_name) {
            return Err(self);
        }
        Ok(ParsedArg::Named(name.to_owned(), value.map(str::to_owned)))
    }

    fn to_str(&self) -> Option<&str> {
        Some(self)
    }

    fn to_osstr(&self) -> &OsStr {
        self.as_ref()
    }
}

impl ArgString for OsString {
    fn parse_arg(self) -> Result<ParsedArg<OsString>, OsString> {
        use std::os::unix::ffi::{OsStrExt, OsStringExt};
        let bytes = self.as_bytes();
        if bytes.len() < 2 || bytes[0] != b'-' {
            return Ok(ParsedArg::Positional(self));
        }
        let body = if bytes[1] != b'-' {
            &bytes[1..]
        } else if bytes.len() == 2 {
            return Ok(ParsedArg::EndOfFlags);
        } else {
            &bytes[2..]
        };
        let (name, value) = match body.iter().position(|&c| c == b'=') {
            None => (body, None),
            Some(idx) => (&body[..idx], Some(&body[idx + 1..])),
        };
        if name.len() == 0
            || name[0] == b'-'
            || name[name.len() - 1] == b'-'
            || !name.iter().all(|&c| is_arg_name(c as char))
        {
            return Err(self);
        }
        let name = Vec::from(name);
        let name = unsafe { String::from_utf8_unchecked(name) };
        let value = value.map(|v| OsString::from_vec(Vec::from(v)));
        Ok(ParsedArg::Named(name, value))
    }

    fn to_str(&self) -> Option<&str> {
        OsStr::to_str(self)
    }

    fn to_osstr(&self) -> &OsStr {
        self
    }
}

/// A single command-line argument which has been parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedArg<T> {
    /// A positional argument.
    Positional(T),
    /// The "--" argument.
    EndOfFlags,
    /// A named option, such as "-opt" or "-opt=value".
    ///
    /// The leading dashes are removed from the name.
    Named(String, Option<T>),
}

impl<T> ParsedArg<T> {
    /// Map a `ParsedArg<T>` to a `ParsedArg<U>` by applying a function to the inner value.
    pub fn map<U, F>(self, f: F) -> ParsedArg<U>
    where
        F: FnOnce(T) -> U,
    {
        match self {
            ParsedArg::Positional(x) => ParsedArg::Positional(f(x)),
            ParsedArg::EndOfFlags => ParsedArg::EndOfFlags,
            ParsedArg::Named(x, y) => ParsedArg::Named(x, y.map(f)),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::ffi::OsStr;
    use std::fmt::Debug;
    use std::os::unix::ffi::OsStrExt;

    fn osstr(s: &[u8]) -> OsString {
        OsString::from(OsStr::from_bytes(s))
    }

    struct Case<T>(T, ParsedArg<T>);

    impl<T> Case<T> {
        fn map<F, U>(self, f: F) -> Case<U>
        where
            F: Fn(T) -> U,
        {
            let Case(input, output) = self;
            Case(f(input), output.map(f))
        }
    }

    impl<T: Debug + Clone + ArgString + PartialEq<T>> Case<T> {
        fn test(&self) -> bool {
            let Case(input, expected) = self;
            match input.clone().parse_arg() {
                Ok(arg) => {
                    if &arg != expected {
                        eprintln!(
                            "{:?}.parse_arg(): got {:?}, expect {:?}",
                            input, expected, arg
                        );
                        false
                    } else {
                        true
                    }
                }
                Err(_) => {
                    eprintln!("{:?}.parse_arg(): got error, expect {:?}", input, expected);
                    false
                }
            }
        }
    }

    fn success_cases() -> Vec<Case<String>> {
        let mut cases = vec![
            Case("abc", ParsedArg::Positional("abc")),
            Case("", ParsedArg::Positional("")),
            Case("-", ParsedArg::Positional("-")),
            Case("--", ParsedArg::EndOfFlags),
            Case("-a", ParsedArg::Named("a".to_owned(), None)),
            Case("--a", ParsedArg::Named("a".to_owned(), None)),
            Case("-a=", ParsedArg::Named("a".to_owned(), Some(""))),
            Case("--a=", ParsedArg::Named("a".to_owned(), Some(""))),
            Case("--arg-name", ParsedArg::Named("arg-name".to_owned(), None)),
            Case("--ARG_NAME", ParsedArg::Named("ARG_NAME".to_owned(), None)),
            Case(
                "--opt=value",
                ParsedArg::Named("opt".to_owned(), Some("value")),
            ),
        ];
        cases.drain(..).map(|c| c.map(str::to_owned)).collect()
    }

    struct Fail<T>(T);

    impl<T: Debug + Clone + ArgString + PartialEq<T>> Fail<T> {
        fn test(&self) -> bool {
            let Fail(input) = self;
            match input.clone().parse_arg() {
                Ok(arg) => {
                    eprintln!("{:?}.parse_arg(): got {:?}, expect error", input, arg);
                    false
                }
                Err(e) => {
                    if &e != input {
                        eprintln!(
                            "{:?}.parse_arg(): got error {:?}, expect error {:?}",
                            input, e, input
                        );
                        false
                    } else {
                        true
                    }
                }
            }
        }
    }

    const FAIL_CASES: &'static [&'static str] =
        &["-\0", "--\n", "--\0=", "-=", "--=", "-=value", "--=xyz"];

    #[test]
    fn parse_string_success() {
        let mut success = true;
        for case in success_cases().drain(..) {
            if !case.test() {
                success = false;
            }
        }
        if !success {
            panic!("failed");
        }
    }

    #[test]
    fn parse_osstring_success() {
        let mut success = true;
        let mut cases: Vec<Case<OsString>> = success_cases()
            .drain(..)
            .map(|c| c.map(OsString::from))
            .collect();
        cases.push(Case(
            osstr(b"\x80\xff"),
            ParsedArg::Positional(osstr(b"\x80\xff")),
        ));
        cases.push(Case(
            osstr(b"--opt=\xff"),
            ParsedArg::Named("opt".to_owned(), Some(osstr(b"\xff"))),
        ));
        for case in cases.drain(..) {
            if !case.test() {
                success = false;
            }
        }
        if !success {
            panic!("failed");
        }
    }

    #[test]
    fn parse_string_failure() {
        let mut success = true;
        for &input in FAIL_CASES.iter() {
            if !Fail(input.to_owned()).test() {
                success = false;
            }
        }
        if !success {
            panic!("failed");
        }
    }

    #[test]
    fn parse_osstring_failure() {
        let mut success = true;
        let mut cases: Vec<OsString> = FAIL_CASES
            .iter()
            .map(|&s| OsString::from(s.to_owned()))
            .collect();
        for input in cases.drain(..) {
            if !Fail(input).test() {
                success = false;
            }
        }
        if !success {
            panic!("failed");
        }
    }
}