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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! # getopt
//!
//! `getopt` provides a minimalistic, (essentially) POSIX-compliant option parser.

/// A single option.
///
/// For `Opt(x, y)`:
///   - `x` is `Some` character, or `None` if no option was found.
///   - `y` is `Some` string, or `None` if no argument was expected.
///
/// # Example
///
/// ```
/// use getopt::*;
///
/// // args = ["program", "-abc", "foo"];
/// # let args: Vec<String> = vec!["program", "-abc", "foo"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "ab:c";
/// let mut state = State::new();
///
/// assert_eq!(
///     Opt(Some('a'), None),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!(
///     Opt(Some('b'), Some(String::from("c"))),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!(
///     Opt(None, None),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// ```
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Opt(pub Option<char>, pub Option<String>);

/// The current state of the parser.
///
/// `args[index]` is the current element being parsed.
/// `args[index][point]` is the current character being parsed.
///
/// After parsing is complete (that is, [`Opt(None, None)`][`Opt`] is returned), any remaining arguments can
/// be found in `args` beginning at `index`.
///
/// # Example
///
/// ```
/// use getopt::*;
///
/// // args = ["program", "-abc", "foo"];
/// # let args: Vec<String> = vec!["program", "-abc", "foo"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "ab:c";
/// let mut state = State::new();
///
/// getopt(&args, optstring, &mut state).unwrap();
/// assert_eq!(State { index: 1, point: 2 }, state);
/// getopt(&args, optstring, &mut state).unwrap();
/// assert_eq!(State { index: 2, point: 0 }, state);
/// getopt(&args, optstring, &mut state).unwrap();
/// assert_eq!(State { index: 2, point: 0 }, state);
/// assert_eq!("foo", args[state.index]);
/// ```
///
/// [`Opt`]: struct.Opt.html
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct State {
    pub index: usize,
    pub point: usize,
}

impl State {
    /// Constructs a new `State`, with `index` and `point` initialized to 1 and 0, respectively.
    pub fn new() -> State {
        State::default()
    }
}

impl Default for State {
    fn default() -> State {
        State { index: 1, point: 0 }
    }
}

/// Returns the next option character, if any.
///
/// Returns an error if an unexpected option is encountered or if an expected argument is not
/// found.
///
/// Parsing stops at the first non-hyphenated argument; or at the first argument matching "-"; or
/// after the first argument matching "--".
///
/// When no more options are available, `getopt` returns [`Opt(None, None)`][`Opt`].
///
/// # Examples
///
/// ## "-"
/// ```
/// use getopt::*;
///
/// // args = ["program", "-", "-a"];
/// # let args: Vec<String> = vec!["program", "-", "-a"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "a";
/// let mut state = State::new();
///
/// assert_eq!(
///     Opt(None, None),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!("-", args[state.index]);
/// ```
///
/// ## "--"
/// ```
/// use getopt::*;
///
/// // args = ["program", "--", "-a"];
/// # let args: Vec<String> = vec!["program", "--", "-a"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "a";
/// let mut state = State::new();
///
/// assert_eq!(
///     Opt(None, None),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!("-a", args[state.index]);
/// ```
///
/// ## Unexpected option:
/// ```
/// use getopt::*;
///
/// // args = ["program", "-b"];
/// # let args: Vec<String> = vec!["program", "-b"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "a";
/// let mut state = State::new();
///
/// assert_eq!(
///     Err(String::from("unknown option -- b")),
///     getopt(&args, optstring, &mut state)
/// );
/// ```
///
/// ## Missing argument:
/// ```
/// use getopt::*;
///
/// // args = ["program", "-a"];
/// # let args: Vec<String> = vec!["program", "-a"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "a:";
/// let mut state = State::new();
///
/// assert_eq!(
///     Err(String::from("option requires an argument -- a")),
///     getopt(&args, optstring, &mut state)
/// );
/// ```
///
/// ## A simple example:
/// ```
/// use getopt::*;
///
/// // args = ["program", "-abc", "foo"];
/// # let args: Vec<String> = vec!["program", "-abc", "foo"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "ab:c";
/// let mut state = State::new();
///
/// assert_eq!(
///     Opt(Some('a'), None),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!(State { index: 1, point: 2 }, state);
/// assert_eq!(
///     Opt(Some('b'), Some(String::from("c"))),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!(State { index: 2, point: 0 }, state);
/// assert_eq!(
///     Opt(None, None),
///     getopt(&args, optstring, &mut state).unwrap()
/// );
/// assert_eq!(State { index: 2, point: 0 }, state);
/// assert_eq!("foo", args[state.index]);
/// ```
///
/// ## A more realistic example:
/// ```
/// use getopt::*;
///
/// // args = ["program", "-abc", "-d", "foo", "-e", "bar"];
/// # let mut args: Vec<String> = vec!["program", "-abc", "-d", "foo", "-e", "bar"]
/// #     .into_iter()
/// #     .map(String::from)
/// #     .collect();
/// let optstring = "ab:cd:e";
/// let mut state = State::new();
///
/// let mut a_flag = false;
/// let mut b_flag = String::new();
/// let mut c_flag = false;
/// let mut d_flag = String::new();
/// let mut e_flag = false;
///
/// loop {
///     match getopt(&args, optstring, &mut state) {
///         Err(error) => panic!("{}", error),
///         Ok(opt) => match opt {
///             Opt(None, _) => break,
///             Opt(Some('a'), None) => a_flag = true,
///             Opt(Some('b'), Some(arg)) => b_flag = arg.clone(),
///             Opt(Some('c'), None) => c_flag = true,
///             Opt(Some('d'), Some(arg)) => d_flag = arg.clone(),
///             Opt(Some('e'), None) => e_flag = true,
///             _ => panic!("unknown option: {:?}", opt),
///         },
///     }
/// }
///
/// let args = args.split_off(state.index);
///
/// assert_eq!(true, a_flag);
/// assert_eq!("c", b_flag);
/// assert_eq!(false, c_flag);
/// assert_eq!("foo", d_flag);
/// assert_eq!(true, e_flag);
///
/// assert_eq!(1, args.len());
/// assert_eq!("bar", args.first().unwrap());
/// ```
///
/// [`Opt`]: struct.Opt.html
pub fn getopt(args: &[String], optstring: &str, state: &mut State) -> Result<Opt, String> {
    let args: Vec<Vec<char>> = explode(args);
    let nothing: Result<Opt, String> = Ok(Opt(None, None));

    if state.point == 0 {
        /*
         * If, when getopt() is called:
         *      argv[optind] is a null pointer
         *      *argv[optind] is not the character '-'
         *      argv[optind] points to the string "-"
         * getopt() shall return -1 without changing optind.
         */
        if state.index >= args.len() || args[state.index][0] != '-' || args[state.index].len() == 1
        {
            return nothing;
        }

        /*
         * If:
         *      argv[optind] points to the string "--"
         * getopt() shall return -1 after incrementing optind.
         */
        if args[state.index][1] == '-' && args[state.index].len() == 2 {
            state.index += 1;
            return nothing;
        }

        state.point += 1;
    }

    let opt: char = args[state.index][state.point];
    state.point += 1;

    match get_spec(optstring, opt) {
        None => Err(format!("unknown option -- {}", opt)),
        Some(Spec(c, false)) => {
            if state.point >= args[state.index].len() {
                state.index += 1;
                state.point = 0;
            }
            Ok(Opt(Some(c), None))
        }
        Some(Spec(c, true)) => {
            let arg: String = if state.point >= args[state.index].len() {
                state.index += 1;
                if state.index >= args.len() {
                    return Err(format!("option requires an argument -- {}", opt));
                }
                args[state.index].iter().collect()
            } else {
                args[state.index]
                    .clone()
                    .split_off(state.point)
                    .iter()
                    .collect()
            };
            state.index += 1;
            state.point = 0;

            Ok(Opt(Some(c), Some(arg)))
        }
    }
}

fn explode(array: &[String]) -> Vec<Vec<char>> {
    array.into_iter().map(|e| e.chars().collect()).collect()
}

struct Spec(char, bool);

fn get_spec(optstring: &str, c: char) -> Option<Spec> {
    let optstring: Vec<char> = optstring.chars().collect();

    for i in 0..optstring.len() {
        if optstring[i] == c {
            return Some(Spec(c, i + 1 < optstring.len() && optstring[i + 1] == ':'));
        }
    }
    None
}

#[cfg(test)]
mod tests;