interviewer 0.1.1

Simple CLI prompting crate
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#![allow(dead_code)]
#![forbid(unsafe_code)]
// #![allow(incomplete_features)]
// #![feature(specialization)]

use std::cmp::Ordering;
use std::fmt::Debug;
use std::io::Write;
use std::sync::{Arc, Mutex};

use custom_error::custom_error;
use lazy_static::lazy_static;
#[cfg(feature = "num-bigfloat")]
use num_bigfloat::BigFloat;
#[cfg(feature = "num-bigint")]
use num_bigint::{BigInt, BigUint};
#[cfg(feature = "num-complex")]
use num_complex::{Complex32, Complex64};
#[cfg(feature = "num-rational")]
use num_rational::{BigRational, Rational32, Rational64};

lazy_static! {
    static ref PARSE_QUOTES: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));

    /// Allows direct modifications of `rustyline::Editor`. Stored as `Arc<Mutex<Option<rustyline::Editor<()>>>>`.
    ///
    /// `Some(rustyline::Editor<()>)` if creation was successful, `None` otherwise.
    pub static ref EDITOR: Arc<Mutex<Option<rustyline::Editor<()>>>> = {
        let e = rustyline::Editor::new();
        Arc::new(Mutex::new(match e {
            Ok(s) => Some(s),
            Err(e) => {
                eprintln!("Could not create rustyline::Editor. Reverting to legacy mode. Error: {}", e);
                None
            }
        }))};
}

const WHITESPACE_REPR: &str = "THIS___IS__A_REPR";

/// Modifies the behaviour of quotes ("") inside ask_many.
///
/// # Arguments
///
/// * `b`: new state
///
/// returns: ()
///
/// # Examples
///
/// ```ignore
/// use interviewer::{ask_until, set_consumable_quotes};
/// set_consumable_quotes(ask_until("enter a bool: "));
/// ```
///
/// ### false
///
/// ```ignore
/// use interviewer::{ask_many, ask_until, set_consumable_quotes, Separator};
/// set_consumable_quotes(false);
/// let s: Vec<String> = ask_many("enter a value: ", Separator::Sequence(",")).unwrap();
/// // assume input was: test, "test test"
/// assert_eq!(s, vec!["test", "\"test", "test\""]);
/// ```
///
/// ### true
///
/// ```ignore
/// use interviewer::{ask_many, ask_until, set_consumable_quotes, Separator};
/// set_consumable_quotes(true);
/// let s: Vec<String> = ask_many("enter a value: ", Separator::Sequence(",")).unwrap();
/// // assume input was: test, "test test"
/// assert_eq!(s, vec!["test", "test test"]);
/// ```
pub fn set_consumable_quotes(b: bool) { *Arc::clone(&PARSE_QUOTES).lock().unwrap() = b; }

/// Result wrapper containing `InterviewError`.
pub type Result<T> = std::result::Result<T, InterviewError>;
custom_error! {pub InterviewError
    ParseError{origin: String, target: String} = "Could not parse \"{origin}\" as {target}"
}

/// Enum for specifying separators for `ask_many` and its variations.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Separator<'a> {
    Whitespace,
    Sequence(&'a str),
    SequenceTrim(&'a str),
    SequenceTrimStart(&'a str),
    SequenceTrimEnd(&'a str)
}

#[inline(always)]
fn get_str<S: AsRef<str>>(prompt_str: S) -> String {
    let editor = Arc::clone(&EDITOR);
    let mut editor = editor.lock().unwrap();
    let editor = editor.as_mut();
    match editor {
        Some(editor) => {
            let readline = editor.readline(prompt_str.as_ref());
            match readline {
                Ok(line) => {
                    let line = line.as_str().trim();
                    editor.add_history_entry(line);
                    line.to_owned()
                }
                Err(rustyline::error::ReadlineError::Interrupted) => {
                    std::process::exit(0);
                }
                Err(err) => {
                    println!("Error: {:?}", err);
                    std::process::exit(1);
                }
            }
        }
        None => {
            // Trivial implementation
            print!("{}", prompt_str.as_ref());
            std::io::stdout().flush().expect("could not flush stdout");
            let mut buffer = String::new();
            let stdin = std::io::stdin();
            stdin.read_line(&mut buffer).expect("could not read stdin");
            buffer.trim().to_owned()
        }
    }
}

/// Ask the user for a value of type T.
///
/// Input is read only once.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
///
/// returns: Result<T, InterviewError>
///
/// # Examples
///
/// ```ignore
/// use interviewer::ask;
/// let s: i32 = ask("enter an i32: ").unwrap();
/// println!("{}", s);
/// ```
pub fn ask<T: Askable, S: AsRef<str>>(prompt_str: S) -> Result<T> {
    let input = get_str(prompt_str);
    T::convert(&input)
}

/// Ask the user for a value of type T. The user is prompted repeatedly until a
/// valid value is provided. Shortcircuits if the user enters an empty string.
///
/// Input is read multiple times.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
///
/// returns: Option<T>
///
/// # Examples
///
/// ```ignore
/// use interviewer::ask_opt;
/// let s: Option<i32> = ask_opt("enter an i32: ");
/// match s {
///     Some(s) => println!("{}", s),
///     None => println!("no value provided")
/// }
/// ```
pub fn ask_opt<T: Askable, S: AsRef<str>>(prompt_str: S) -> Option<T> {
    loop {
        let input = get_str(&prompt_str);
        if input.is_empty() {
            return None;
        }
        if let Ok(s) = T::convert(&input) {
            return Some(s);
        }
    }
}

/// Ask the user for a value of type T. The user is prompted repeatedly until a
/// valid value is provided.
///
/// Input is read multiple times.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
///
/// returns: T
///
/// # Examples
///
/// ```ignore
/// use interviewer::ask_until;
/// let s: i32 = ask_until("enter an i32: ");
/// println!("{}", s);
/// ```
pub fn ask_until<T: Askable, S: AsRef<str>>(prompt_str: S) -> T {
    loop {
        let input = get_str(&prompt_str);
        return match T::convert(&input) {
            Ok(s) => s,
            Err(_) => {
                continue;
            }
        };
    }
}

#[inline(always)]
fn iterator_skip<T: Iterator>(it: &mut T, len: usize) {
    match len.cmp(&2) {
        Ordering::Less => {}
        Ordering::Equal => {
            it.next();
        }
        Ordering::Greater => {
            it.nth(len - 2);
        }
    }
}

macro_rules! many_main {
    { $v:ident => $prompt_str:expr , $sep:expr } => {

        let parse_quotes = *Arc::clone(&PARSE_QUOTES).lock().unwrap();
        let s = if parse_quotes {
        // replace whitespace inside of quotes such as "hello world" with
        // "helloREPRworld" to allow better parsing
        let buffer = get_str($prompt_str);
        let mut tmp_buffer = String::new();
        let mut in_quote = false;
        for (_, c) in buffer.char_indices() {
            if c == '"' {
                in_quote = !in_quote;
            }
            if in_quote && c.is_whitespace() {
                tmp_buffer.push_str(WHITESPACE_REPR);
            } else if c != '"' {
                tmp_buffer.push(c);
            }
        }
        tmp_buffer.trim().to_owned()
    } else {
        get_str($prompt_str)
    };

    let mut s: Vec<&str> = match $sep {
        Separator::Whitespace => s.split_whitespace().collect(),
        Separator::Sequence(seq) => s.split(seq).collect(),
        Separator::SequenceTrim(seq) => {
            let mut strings = Vec::new();
            let mut it = s.char_indices();
            let mut start_index = 0;
            while let Some((i, _)) = it.next() {
                if s[i..].starts_with(seq) {
                    strings.push(s[start_index..i].trim());
                    iterator_skip(&mut it, seq.len());
                    start_index = i + seq.len();
                    continue;
                }
            }
            strings.push(s[start_index..].trim());
            strings
        }
        Separator::SequenceTrimStart(seq) => {
            let mut strings = Vec::new();
            let mut it = s.char_indices();
            let mut start_index = 0;
            while let Some((i, _)) = it.next() {
                if s[i..].starts_with(seq) {
                    strings.push(s[start_index..i].trim_start());
                    iterator_skip(&mut it, seq.len());
                    start_index = i + seq.len();
                    continue;
                }
            }
            strings.push(s[start_index..].trim_start());
            strings
        }
        Separator::SequenceTrimEnd(seq) => {
            let mut strings = Vec::new();
            let mut it = s.char_indices();
            let mut start_index = 0;
            while let Some((i, _)) = it.next() {
                if s[i..].starts_with(seq) {
                    strings.push(s[start_index..i].trim_end());
                    iterator_skip(&mut it, seq.len());
                    start_index = i + seq.len();
                    continue;
                }
            }
            strings.push(s[start_index..].trim_end());
            strings
        }
    };
    if s.last() == Some(&"") {
        s.pop();
    }

    let $v = s.iter().map(|item| item.replace(WHITESPACE_REPR, " "));

    };
}

/// Ask the user for multiple values of type T separated by delimiter.
///
/// Input is read only once.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
/// * `sep`: delimiter between values
///
/// returns: Result<Vec<T>, InterviewError>
///
/// # Examples
///
/// ```ignore
/// use interviewer::ask_many;
/// use interviewer::Separator::Whitespace;
/// let s: Vec<i32> = ask_many("enter multiple i32s: ", Whitespace).unwrap();
/// println!("{:?}", s);
/// ```
pub fn ask_many<T: Askable, S: AsRef<str>>(prompt_str: S, sep: Separator) -> Result<Vec<T>> {
    many_main! {s => prompt_str, sep}
    let mut v = Vec::with_capacity(s.len());
    for x in s {
        v.push(Askable::convert(x)?);
    }
    Ok(v)
}

/// Ask the user for multiple values of type T. The user is prompted repeatedly
/// until all values are parseable.
///
/// Input is read multiple times.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
/// * `sep`: delimiter between values
///
/// returns: Vec<T>
///
/// # Examples
///
/// ```ignore
/// use interviewer::{ask_many_until, Separator};
/// let s: Vec<i32> = ask_many_until("enter some i32s: ", Separator::SequenceTrim(","));
/// println!("{:?}", s);
/// ```
pub fn ask_many_until<T: Askable, S: AsRef<str>>(prompt_str: S, sep: Separator) -> Vec<T> {
    'outer: loop {
        many_main! {s => &prompt_str, sep}
        // Empty string could also potentially be a valid input.
        // if s.len() == 0 {
        //     continue 'outer;
        // }
        let mut v = Vec::with_capacity(s.len());
        for x in s {
            let val = match Askable::convert(x) {
                Ok(val) => val,
                Err(_) => {
                    continue 'outer;
                }
            };
            v.push(val);
        }
        return v;
    }
}

/// Ask the user for multiple values of type T. The user is prompted repeatedly
/// until all values can be parsed. Shortcircuits if the user enters an
/// empty string
///
/// Input is read multiple times.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
/// * `sep`: delimiter between values
///
/// returns: Option<Vec<T>>
///
/// # Examples
///
/// ```ignore
/// use interviewer::ask_many_opt;
/// use interviewer::Separator::Whitespace;
/// let s: Vec<i32> = ask_many_opt("enter multiple i32s: ", Whitespace).unwrap();
/// println!("{:?}", s);
/// ```
pub fn ask_many_opt<T: Askable, S: AsRef<str>>(prompt_str: S, sep: Separator) -> Option<Vec<T>> {
    'outer: loop {
        many_main! {s => &prompt_str, sep}
        if s.len() == 0 {
            return None;
        }
        let mut v = Vec::with_capacity(s.len());
        for x in s {
            v.push(match Askable::convert(x) {
                Ok(val) => val,
                Err(_) => continue 'outer
            });
        }
        return Some(v);
    }
}

/// Ask the user for multiple values of type T. Unparseable values are
/// represented as `None`.
///
/// Input is read only once.
///
/// # Arguments
///
/// * `prompt_str`: prompt displayed to the user
/// * `sep`: delimiter between values
///
/// returns: Vec<Option<T>>
///
/// # Examples
///
/// ```ignore
/// use interviewer::ask_many_opt;
/// use interviewer::Separator::Whitespace;
/// let s: Vec<i32> = ask_many_opt("enter multiple i32s: ", Whitespace).unwrap();
/// println!("{:?}", s);
/// ```
pub fn ask_many_opt_lazy<T: Askable, S: AsRef<str>>(prompt_str: S, sep: Separator) -> Vec<Option<T>> {
    many_main! {s => prompt_str, sep}
    let mut v = Vec::with_capacity(s.len());
    for x in s {
        match Askable::convert(x) {
            Ok(x) => {
                v.push(Some(x));
            }
            Err(_) => {
                v.push(None);
            }
        }
    }
    v
}

/// Base trait for all types that can be asked for input.
pub trait Askable {
    /// Convert a string to a value of type T.
    ///
    /// # Arguments
    ///
    /// * `prompt_str`: string to convert
    ///
    /// Returns `InterviewError` if the conversion fails.
    ///
    /// returns: Result<Self, InterviewError>
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use interviewer::{Askable, Result};
    /// struct X {
    ///     x: i32
    /// }
    ///
    /// impl Askable for X {
    ///     fn convert<S: AsRef<str>>(s: S) -> Result<Self> {
    ///         Ok(X {
    ///             x: s.as_ref().trim().parse::<i32>()?
    ///         })
    ///     }
    /// }
    /// ```
    fn convert<S: AsRef<str>>(s: S) -> Result<Self>
    where Self: Sized;
}

impl Askable for String {
    fn convert<S: AsRef<str>>(s: S) -> Result<Self> { Ok(s.as_ref().to_owned()) }
}

impl Askable for bool {
    fn convert<S: AsRef<str>>(s: S) -> Result<Self> {
        let lower = s.as_ref().to_lowercase();
        let lower = lower.trim();
        match lower {
            "y" | "yes" | "t" | "true" | "1" => Ok(true),
            "n" | "no" | "f" | "false" | "0" => Ok(false),
            _ => Err(InterviewError::ParseError {
                origin: s.as_ref().to_string(),
                target: "bool".to_string()
            })
        }
    }
}

// dirty fix until trait specialization is stable
macro_rules! impl_askable {
    ($t:ty) => {
        impl Askable for $t {
            fn convert<S: AsRef<str>>(s: S) -> Result<Self> {
                match s.as_ref().parse::<$t>() {
                    Ok(s) => Ok(s),
                    _ => Err(InterviewError::ParseError {
                        origin: s.as_ref().to_string(),
                        target: std::any::type_name::<$t>().to_string()
                    })
                }
            }
        }
    };
}

impl_askable!(char);
impl_askable!(i8);
impl_askable!(i16);
impl_askable!(i32);
impl_askable!(i64);
impl_askable!(i128);
impl_askable!(isize);
impl_askable!(u8);
impl_askable!(u16);
impl_askable!(u32);
impl_askable!(u64);
impl_askable!(u128);
impl_askable!(usize);
impl_askable!(f32);
impl_askable!(f64);

#[cfg(feature = "num-bigint")]
impl_askable!(BigInt);
#[cfg(feature = "num-bigint")]
impl_askable!(BigUint);

#[cfg(feature = "num-complex")]
impl_askable!(Complex32);
#[cfg(feature = "num-complex")]
impl_askable!(Complex64);

#[cfg(feature = "num-bigfloat")]
impl_askable!(BigFloat);

#[cfg(feature = "num-rational")]
impl_askable!(Rational32);
#[cfg(feature = "num-rational")]
impl_askable!(Rational64);
#[cfg(feature = "num-rational")]
impl_askable!(BigRational);

// Waiting for specialization to become stable
// #[cfg(feature = "nightly")]
// default impl<T> Askable for T
//     where   T: FromStr {
//     fn convert<S: AsRef<str>>(s: S) -> Result<Self> where Self: Sized {
//         match s.as_ref().parse::<Self>() {
//             Ok(s) => Ok(s),
//             _ => Err(InterviewError::ParseError {
//                 origin: s.as_ref().to_string(),
//                 target: std::any::type_name::<Self>().to_string(),
//             })
//         }
//     }
// }