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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Dia-Args

Copyright (C) 2018-2019, 2021-2024  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2018-2019".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # Arguments

mod stream;

use {
    alloc::{
        collections::{
            BTreeMap,
            VecDeque,
            btree_map::Entry,
        },
        sync::Arc,
    },
    core::{
        any::TypeId,
        fmt::Debug,
        mem,
        str::FromStr,
    },
    std::{
        env,
        fs::File,
        io::{BufReader, Error, ErrorKind, Read},
        path::Path,
        sync::RwLock,
    },
    crate::{MergeOption, Result},
    self::{
        kind::Kind,
        stream::*,
        value::Value,
    },
};

#[cfg(test)]
mod tests;

mod kind;
mod value;

type Options = BTreeMap<String, Vec<Value>>;

const TRUE_AS_STR: &str = "true";
const FALSE_AS_STR: &str = "false";

/// # Description of argument file format, in English
///
/// This constant can be useful if you want to include in your program's documentation. It has a title and its own content. So you don't have to
/// prefix with any message/description.
///
/// ## Examples
///
/// ```
/// use std::borrow::Cow;
/// use dia_args::{
///     DIA_ARGS_FILE_FORMAT, DIA_ARGS_FILE_NAME,
///     docs::{Cfg, Docs, I18n},
/// };
///
/// let docs = format!(
///     concat!(
///         // Here is program documentation.
///         "This program does something.\n\n",
///         "Options can be set via either command line or from {:?} file at root",
///         " directory of the program. Options set via command line will",
///         " override the ones from file.\n\n",
///
///         // Here is description of argument file format. Note that we don't need
///         // a title for it.
///         "{}",
///     ),
///     DIA_ARGS_FILE_NAME, DIA_ARGS_FILE_FORMAT,
/// );
/// Docs::new(Cow::Borrowed("Some Program"), Cow::Owned(docs)).print()?;
///
/// # Ok::<_, std::io::Error>(())
/// ```
pub const DIA_ARGS_FILE_FORMAT: &str = concat!(
    "Argument file format:\n\n",
    "- Empty lines or lines starting with `#` will be ignored.\n",
    "- Each command, argument, or option must be placed on a separate line.\n",
    "- Option key and value are separated by either: equal symbol `=` (can have leading/trailing white spaces), or at least one white space.",
    ' ', "Key and value will be trimmed.",
);

#[test]
fn test_dia_args_file_format() -> Result<()> {
    use crate::docs::Docs;

    Docs::new("Some Program".into(), format!("This program does something.\n\n{}", DIA_ARGS_FILE_FORMAT).into()).print()?;

    Ok(())
}

const DASH: char = '-';

/// # Arguments
///
/// ## Examples
///
/// ```
/// use dia_args;
///
/// let mut args = dia_args::parse_strings(["run", "--debug", "--port=99"])?;
/// assert_eq!(args.take(&["--debug"])?, Some(true));
/// assert_eq!(args.take::<u16>(&["--port"])?.unwrap(), 99);
///
/// # dia_args::Result::Ok(())
/// ```
#[derive(Default, Debug)]
pub struct Args {
    args: VecDeque<Value>,
    options: Options,
    sub_args: Vec<String>,
}

impl Args {

    /// # Gets the command
    pub fn cmd(&self) -> Option<&str> {
        match self.args.front() {
            None => None,
            Some(Value::Owned(s)) => Some(s.as_ref()),
            Some(Value::Borrowed(_)) => None,
        }
    }

    /// # Sub arguments
    pub fn sub_args(&self) -> &[String] {
        &self.sub_args
    }

    /// # Checks if there are no arguments/options/sub arguments
    pub fn is_empty(&self) -> bool {
        self.options.is_empty() && self.sub_args.is_empty() && self.args.iter().filter(|a| match a {
            Value::Owned(_) => true,
            Value::Borrowed(a) => match a.try_read() {
                Ok(a) => a.is_some(),
                Err(_) => true,
            },
        }).count() == usize::MIN
    }

    /// # Transforms into sub command
    ///
    /// For example:
    ///
    /// - Command line:
    ///     ```shell
    ///     ~> program help version 1
    ///     ```
    ///
    /// - Parsed as:
    ///     ```code
    ///     help version 1
    ///     ```
    ///
    /// - After calling this function:
    ///     ```code
    ///     version 1
    ///     ```
    ///
    /// ```
    /// use dia_args;
    ///
    /// const CMD_VERSION: &str = "version";
    ///
    /// let (cmd, args) = dia_args::parse()?.try_into_sub_cmd()?;
    /// match cmd.as_ref().map(|s| s.as_str()) {
    ///     Some(CMD_VERSION) => if args.is_empty() {
    ///         println!("Version: ...");
    ///     } else {
    ///         eprintln!("{:?} command doesn't take arguments", CMD_VERSION);
    ///     },
    ///     Some(other) => eprintln!("Command {:?} not supported", other),
    ///     None => eprintln!("Missing command"),
    /// };
    ///
    /// # Ok::<_, std::io::Error>(())
    /// ```
    pub fn try_into_sub_cmd(mut self) -> Result<(Option<String>, Self)> {
        self.clean_up_args()?;
        match self.args.pop_front() {
            None => Ok((None, self)),
            Some(Value::Owned(s)) => Ok((Some(s), self)),
            Some(Value::Borrowed(_)) => Err(Error::new(ErrorKind::Unsupported, "The first argument is not owned")),
        }
    }

    /// # Takes an option using given keys
    ///
    /// ## Examples
    ///
    /// ```
    /// use dia_args;
    ///
    /// let mut args = dia_args::parse_strings(["--type", "rs"])?;
    /// assert_eq!(args.take::<String>(&["--type"])?.unwrap(), "rs");
    /// assert!(args.take::<String>(&["--type"])?.is_none());
    ///
    /// # Ok::<_, std::io::Error>(())
    /// ```
    pub fn take<T>(&mut self, keys: &[&str]) -> Result<Option<T>> where T: FromStr + 'static, <T as FromStr>::Err: Debug {
        let mut result = None;
        for key in keys {
            let parse = |s| T::from_str(s).map_err(|err|
                Error::new(ErrorKind::InvalidData, format!("Failed parsing value {s:?} of {key:?}: {err:?}"))
            );
            if let Some(mut values) = self.options.remove(*key) {
                if result.is_some() {
                    return Err(Error::new(ErrorKind::InvalidData, format!("Duplicate value for {key:?}")));
                }
                match values.len() {
                    0 => if TypeId::of::<T>() == TypeId::of::<bool>() {
                        result = Some(T::from_str(TRUE_AS_STR).map_err(|_| err!())?);
                    } else {
                        return Err(Error::new(ErrorKind::InvalidData, format!("Missing value for {key:?}")));
                    },
                    1 => match values.remove(usize::MIN) {
                        Value::Owned(v) => result = Some(parse(&v)?),
                        Value::Borrowed(v) => {
                            let mut v = v.try_write().map_err(|e| err!("{e}"))?;
                            let s = v.take().ok_or_else(|| err!())?;
                            if TypeId::of::<T>() == TypeId::of::<bool>() {
                                match s.as_str() {
                                    TRUE_AS_STR | FALSE_AS_STR => {
                                        result = Some(parse(&s)?);
                                        drop(v);
                                        self.clean_up_args()?;
                                    },
                                    _ => {
                                        *v = Some(s);
                                        result = Some(T::from_str(TRUE_AS_STR).map_err(|_| err!())?);
                                    },
                                };
                            } else {
                                result = Some(parse(&s)?);
                                drop(v);
                                self.clean_up_args()?;
                            }
                        },
                    },
                    _ => return Err(Error::new(ErrorKind::InvalidData, format!("Expected 1 value, got: {values:?}"))),
                };
            }
        }
        Ok(result)
    }

    /// # Cleans up args
    fn clean_up_args(&mut self) -> Result<()> {
        let args = VecDeque::with_capacity(self.args.len());
        self.args = mem::take(&mut self.args).into_iter().try_fold(args, |mut result, next| {
            match &next {
                Value::Owned(_) => result.push_back(next),
                Value::Borrowed(a) => if a.try_read().map_err(|e| err!("{e}"))?.is_some() {
                    result.push_back(next);
                },
            };
            Result::Ok(result)
        })?;
        Ok(())
    }

    /// # Takes an option using given keys
    ///
    /// ## Examples
    ///
    /// ```
    /// use dia_args;
    ///
    /// let mut args = dia_args::parse_strings(["-l", "c", "-l", "c++"])?;
    /// let mut languages = args.take_vec::<String>(&["-l"])?.unwrap();
    /// languages.sort();
    /// assert_eq!(languages, &["c", "c++"]);
    /// assert!(args.is_empty());
    ///
    /// # Ok::<_, std::io::Error>(())
    /// ```
    pub fn take_vec<T>(&mut self, keys: &[&str]) -> Result<Option<Vec<T>>> where T: FromStr, <T as FromStr>::Err: Debug {
        let mut result: Option<Vec<_>> = None;

        for key in keys {
            if let Some(values) = self.options.remove(*key) {
                let count = values.len();
                for (index, value) in values.into_iter().enumerate() {
                    let value = match value {
                        Value::Owned(s) => s,
                        Value::Borrowed(s) => {
                            let s = s.try_write().map_err(|e| err!("{e}"))?.take().ok_or_else(|| err!())?;
                            self.clean_up_args()?;
                            s
                        },
                    };
                    let value = T::from_str(&value)
                        .map_err(|err| Error::new(ErrorKind::InvalidData, format!("Failed parsing value {value:?} of {key:?}: {err:?}")))?;
                    match result.as_mut() {
                        Some(result) => {
                            if index == usize::MIN {
                                result.reserve(count);
                            }
                            result.push(value);
                        },
                        None => result = Some({
                            let mut result = Vec::with_capacity(count);
                            result.push(value);
                            result
                        }),
                    };
                }
            }
        }

        Ok(result)
    }

    /// # Takes arguments out
    ///
    /// ## Notes
    ///
    /// This function can only be called when there are no options left.
    ///
    /// ## Examples
    ///
    /// ```
    /// use dia_args;
    ///
    /// let mut args = dia_args::parse_strings(["do", "this"])?;
    /// assert_eq!(args.take_args()?, &["do", "this"]);
    ///
    /// # Ok::<_, std::io::Error>(())
    /// ```
    pub fn take_args(&mut self) -> Result<Vec<String>> {
        if self.options.is_empty() {
            let result = Vec::with_capacity(self.args.len());
            return self.args.drain(..).try_fold(result, |mut result, next| {
                match next {
                    Value::Owned(s) => result.push(s),
                    Value::Borrowed(s) => if let Some(s) = s.try_write().map_err(|e| err!("{e}"))?.take() {
                        result.push(s);
                    },
                };
                Ok(result)
            });
        }
        Err(Error::new(ErrorKind::Unsupported, "take_args() can only be called when there are no options"))
    }

    /// # Takes sub arguments out
    ///
    /// ## Examples
    ///
    /// ```
    /// use dia_args;
    ///
    /// let mut args = dia_args::parse_strings(
    ///     ["eat", "chicken", "--", "with", "ronnie-coleman"]
    /// )?;
    /// assert_eq!(args.take_sub_args(), &["with", "ronnie-coleman"]);
    ///
    /// # Ok::<_, std::io::Error>(())
    /// ```
    pub fn take_sub_args(&mut self) -> Vec<String> {
        mem::take(&mut self.sub_args)
    }

    /// # Merges _options_ with other
    ///
    /// - This function works on _options_, not commands/sub arguments...
    /// - Other's options will be taken out, if conditions are met.
    /// - Result is number of items merged.
    ///
    /// ## Parameters
    ///
    /// - `filter`:
    ///
    ///     + If you provide some sets of keys, only those (from other) are accepted.
    ///     + If you provide an empty slice, or any of its items is empty, an error is returned.
    ///
    /// ## Examples
    ///
    /// Your program allows the user to set options from file. Later you want to give the user new ability to set options via command line,
    /// overwriting the ones from file. Then this function can help.
    ///
    /// ```
    /// use dia_args::MergeOption;
    ///
    /// const OPTION_DEBUG: &[&str] = &["-d", "--debug"];
    /// const OPTION_PORT: &[&str] = &["--port"];
    ///
    /// // Here in test, we're parsing from strings.
    /// // In real code, you might want to use dia_args::parse_file()
    /// let mut args_from_file = dia_args::parse_strings(
    ///     ["--debug=false", "--port=6789"]
    /// )?;
    ///
    /// // Command line arguments
    /// let mut cmd_line_args = dia_args::parse_strings(
    ///     ["-d=true", "--address", "localhost"]
    /// )?;
    ///
    /// // Merge
    /// let count = cmd_line_args.merge_options(
    ///     &mut args_from_file, &[OPTION_DEBUG, OPTION_PORT], MergeOption::IgnoreExisting,
    /// )?;
    /// assert_eq!(count, 1);
    ///
    /// // Verify
    /// assert_eq!(cmd_line_args.take(OPTION_DEBUG)?, Some(true));
    /// assert_eq!(cmd_line_args.take::<String>(&["--address"])?.unwrap(), "localhost");
    /// assert_eq!(cmd_line_args.take::<u16>(OPTION_PORT)?, Some(6789));
    ///
    /// # Ok::<_, std::io::Error>(())
    /// ```
    pub fn merge_options(&mut self, other: &mut Self, filter: &[&[&str]], merge_option: MergeOption) -> Result<usize> {
        if filter.is_empty() || filter.iter().any(|keys| keys.is_empty()) {
            return Err(Error::new(ErrorKind::InvalidInput, format!("Invalid filter: {:?}", filter)));
        }

        let mut count = 0;

        for (key, other_value) in mem::take(&mut other.options) {
            let keys = {
                match filter.iter().find(|keys| keys.contains(&key.as_str())) {
                    Some(keys) => keys,
                    None => {
                        other.options.insert(key, other_value);
                        continue;
                    },
                }
            };
            match merge_option {
                MergeOption::TakeAll => keys.iter().for_each(|k| drop(self.options.remove(*k))),
                MergeOption::IgnoreExisting => if keys.iter().any(|k| self.options.contains_key(*k)) {
                    other.options.insert(key, other_value);
                    continue;
                },
            };

            self.options.insert(key, other_value);
            count += 1;
        }

        Ok(count)
    }

}

/// # Parses from an iterator of strings
pub fn parse_strings<S, I>(args: I) -> Result<Args> where S: AsRef<str>, I: IntoIterator<Item=S> {
    let args = args.into_iter();
    let mut result = Args {
        args: VecDeque::with_capacity(args.size_hint().0),
        options: BTreeMap::new(),
        sub_args: Vec::new(),
    };

    let mut args = args.peekable();
    while let Some(arg) = args.next() {
        let arg = arg.as_ref();
        match Kind::parse(arg)? {
            Kind::Command => {
                let arg = arg.trim();
                if arg.is_empty() == false {
                    result.args.push_back(Value::Owned(arg.to_string()));
                }
            },
            Kind::ShortOption | Kind::LongOption => {
                let value = match args.peek().map(|s| s.as_ref().starts_with(DASH)) {
                    Some(true) | None => None,
                    Some(false) => {
                        let value = Arc::new(RwLock::new(Some(args.next().map(|s| s.as_ref().to_string()).ok_or_else(||
                            // This shouldn't happen, but it's better than ::unwrap()
                            Error::new(ErrorKind::InvalidData, format!("Missing value for {:?}", &arg))
                        )?)));
                        result.args.push_back(Value::Borrowed(value.clone()));
                        Some(Value::Borrowed(value))
                    },
                };
                add_option(&mut result.options, arg.to_string(), value)?;
            },
            Kind::ShortOptionWithValue { option, value } | Kind::LongOptionWithValue { option, value } => {
                add_option(&mut result.options, option, Some(Value::Owned(value)))?;
            },
            Kind::SubArgsSeparator => {
                result.sub_args = args.map(|s| s.as_ref().to_string()).collect();
                break;
            },
        };
    }

    Ok(result)
}

/// # Adds option
fn add_option(options: &mut Options, option: String, value: Option<Value>) -> Result<()> {
    match options.entry(option) {
        Entry::Vacant(vacant) => drop(match value {
            None => vacant.insert(vec!()),
            Some(value) => vacant.insert(vec!(value)),
        }),
        Entry::Occupied(mut occupied) => match value {
            None => return Err(Error::new(ErrorKind::InvalidData, format!("Expected 1 value for {:?}", occupied.key()))),
            Some(value) => occupied.get_mut().push(value),
        },
    };
    Ok(())
}

/// # Parses from process' arguments
pub fn parse() -> Result<Args> {
    parse_strings(env::args().skip(1))
}

/// # Parses from file
///
/// ## Rules
///
/// ### Default file
///
/// - Default file is a file named [`DIA_ARGS_FILE_NAME`][const:DIA_ARGS_FILE_NAME] within directory of the program. On Unix, if the program
///   is a symlink, its parent directory is used. The parent directory of the original file is ***not*** used.<sup><a id='::&1' href='#::1'>
///   `[1]`</a></sup>
/// - If `None` is given, default file will be used.
/// - If the file does not exist, `None` is returned.
///
/// ### Limits and syntax
///
/// - If `max_size` is zero, an error is returned. If `None`, [`MAX_DIA_ARGS_FILE_SIZE`][const:MAX_DIA_ARGS_FILE_SIZE] will be used. If the
///   file's size is larger than provided value, an error is returned.
/// - Empty lines or lines starting with `#` will be ignored.
/// - Each command, argument, or option must be placed on a separate line.
/// - Normally, a shell will remove leading/trailing marks such as `"..."` or `'...'`. ***However*** those are _not_ required in this file. So
///   you can separate options like these:
///
///     ```shell
///     --passphrase=secret passphrase with white-spaces in it
///     --passphrase        =       secret passphrase with white-spaces in it
///     --passphrase        secret passphrase with white-spaces in it
///     ```
///
///   They're all the same. Also, note that values will be trimmed.
///
/// ---
///
/// 1. <a id='::1' href='#::&1'>`^^`</a> In theory, that is the goal. However [`env::current_exe()`][fn:env/current_exe] function might
///    return the original file (not the symlink). In that case, the parent directory of the original file will be used.
///
/// [const:DIA_ARGS_FILE_NAME]: constant.DIA_ARGS_FILE_NAME.html
/// [const:MAX_DIA_ARGS_FILE_SIZE]: constant.MAX_DIA_ARGS_FILE_SIZE.html
/// [fn:env/current_exe]: https://doc.rust-lang.org/std/env/fn.current_exe.html
pub fn parse_file<P>(file: Option<P>, max_size: Option<u64>) -> Result<Option<Args>> where P: AsRef<Path> {
    // NOTES:
    //
    // - If you change file format, update documentation of this function *and* DIA_ARGS_FILE_FORMAT constant.

    let max_size = max_size.unwrap_or(crate::MAX_DIA_ARGS_FILE_SIZE);
    if max_size == 0 {
        return Err(Error::new(ErrorKind::InvalidInput, "max_size must be larger than 0"));
    }

    let current_exe = env::current_exe()?;
    let file = match file.map(|f| f.as_ref().to_path_buf()) {
        Some(file) => file,
        None => match current_exe.parent() {
            Some(dir) => dir.join(crate::DIA_ARGS_FILE_NAME),
            None => return Err(Error::new(ErrorKind::NotFound, "Could not find parent directory of the program")),
        },
    };
    let file = if file.exists() {
        if file.is_file() {
            match file.canonicalize() {
                Ok(file) => file,
                Err(err) => return Err(Error::new(err.kind(), format!("Failed getting canonical path of {file:?}: {err:?}"))),
            }
        } else {
            return Err(Error::new(ErrorKind::InvalidInput, format!("Not a file: {file:?}")));
        }
    } else {
        return Ok(None);
    };

    // Check file size
    let file_size = file
        .metadata().map_err(|e| Error::new(ErrorKind::Other, format!("Failed getting file size of {file:?}: {e:?}")))?
        .len();
    if file_size > max_size {
        return Err(Error::new(ErrorKind::InvalidInput, format!("File too large: {file:?} (max allowed: {max_size})")));
    }

    let mut args: Vec<String> = vec![];
    for line in read_file_to_string(file)?.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with(DASH) == false || false == ['=', ' ', '\t'].iter().any(|separator| match line.find(*separator) {
            Some(idx) => {
                args.push(format!("{}={}", line[..idx].trim(), line[idx + 1..].trim()));
                true
            },
            None => false,
        }) {
            args.push(line.to_owned());
        }
    }

    parse_strings(args.into_iter()).map(|args| Some(args))
}

/// # Reads file to string
fn read_file_to_string<P>(file: P) -> Result<String> where P: AsRef<Path> {
    const BUF_SIZE: usize = 8 * 1024;

    let file = file.as_ref();
    let limit = file.metadata()?.len();
    let mut reader = BufReader::new(File::open(file)?).take(limit);

    let mut buf = [0; BUF_SIZE];
    let mut data = Vec::with_capacity(limit.try_into().map_err(|_| err!())?);
    loop {
        match reader.read(&mut buf)? {
            0 => return String::from_utf8(data).map_err(|e| Error::new(ErrorKind::InvalidData, e)),
            read => data.extend(&buf[..read]),
        };
    }
}

/// # Parses a stream of strings, separated by null byte (`0`)
///
/// This function can be useful for securely passing/parsing arguments across processes.
///
/// ## Notes
///
/// - If `max_size` is zero, an error is returned. If `None`, [`MAX_DIA_ARGS_FILE_SIZE`][const:MAX_DIA_ARGS_FILE_SIZE] will be used. If the
///   stream has more data than provided value, an error is returned.
/// - If the stream contains an invalid UTF-8 string, an error is returned.
/// - The stream is used as-is. So you might want to use [`BufReader`][struct:BufReader].
///
/// ## Examples
///
/// ```
/// let stream = b"run\0--faster=true";
///
/// let mut args = dia_args::parse_stream(&mut &stream[..], None)?;
/// assert_eq!(args.cmd(), Some("run"));
/// assert_eq!(args.take(&["--faster"])?, Some(true));
///
/// # Ok::<_, std::io::Error>(())
/// ```
///
/// [const:MAX_DIA_ARGS_FILE_SIZE]: constant.MAX_DIA_ARGS_FILE_SIZE.html
/// [struct:BufReader]: https://doc.rust-lang.org/std/io/struct.BufReader.html
pub fn parse_stream<R>(stream: &mut R, max_size: Option<u64>) -> Result<Args> where R: Read {
    let max_size = max_size.unwrap_or(crate::MAX_DIA_ARGS_FILE_SIZE);
    if max_size == 0 {
        return Err(Error::new(ErrorKind::InvalidInput, "max_size must be larger than 0"));
    }

    let mut strings = Vec::with_capacity(128);
    for s in Stream::make(stream, max_size)? {
        strings.push(s?);
    }
    parse_strings(strings.into_iter())
}