sap 0.2.0

A small, simple and sweet argument parser for Rust
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
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
#![warn(clippy::pedantic)]
#![warn(clippy::complexity)]
#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
//! # Sap - a Small Argument Parser
//!
//! A minimal, zero-dependency Unix command-line argument parser for Rust.
//!
//! Sap exposes an iterator-based API that handles GNU-style options and gives
//! you full control over how each argument is consumed.
//!
//! ## Features
//!
//! - **GNU-style option parsing**: short (`-a`), long (`--verbose`), and combined options (`-abc`)
//! - **Value handling**: options with values via `--name=value` or as a separate following argument
//! - **POSIX compliance**: `--` separator and `-` (stdin) are handled correctly
//! - **Zero dependencies**: no external crates
//! - **Iterator-based**: works with any iterator yielding [`ArgLike`] items (`&str`, `String`, `OsStr`, etc.),
//!   so you can parse args from the environment, a `Vec`, or a test fixture without conversion
//! - **Error handling**: errors carry the offending argument and the parser transitions to a defined poisoned state
//!
//! For a `#[derive(Parser)]` interface built on top of this crate, see the
//! companion crate [`treesap`](https://crates.io/crates/treesap).
//!
//! ## Example
//!
//! ```rust
//! use sap::{Parser, Argument};
//!
//! let mut parser = Parser::from_arbitrary(["myprogram", "-v", "--file=input.txt"]).unwrap();
//!
//! while let Some(arg) = parser.forward().unwrap() {
//!     match arg {
//!         Argument::Short('v') => println!("Verbose mode enabled"),
//!         Argument::Long("file") => {
//!             if let Some(filename) = parser.value().unwrap() {
//!                 println!("Processing file: {}", filename);
//!             }
//!         }
//!         Argument::Value(val) => println!("Positional argument: {}", val),
//!         _ => {}
//!     }
//! }
//! ```

#[cfg(not(feature = "std"))]
extern crate alloc;

use core::{error::Error, ffi::CStr, fmt::Display, iter::Peekable, mem, str::Utf8Error};

#[cfg(feature = "std")]
use std::{
    borrow::Cow,
    env,
    ffi::{CString, OsStr, OsString},
    fmt::Debug,
};

#[cfg(not(feature = "std"))]
use alloc::{
    borrow::{Cow, ToOwned},
    ffi::CString,
    string::{String, ToString},
};

/// A [`Result`] type alias using [`ParsingError`] as the default error type.
///
/// This type alias is used throughout the Sap API to reduce boilerplate when
/// returning parsing results.
///
/// # Examples
///
/// ```rust
/// use sap::{Result, ParsingError};
///
/// fn parse_config() -> Result<String> {
///     // Returns Result<String, ParsingError>
///     Ok("config".to_string())
/// }
/// ```
pub type Result<T, E = ParsingError> = core::result::Result<T, E>;

/// Represents a parsed command-line argument.
///
/// Each argument parsed by [`Parser::forward`] is represented as one of these variants.
/// The parser automatically categorizes arguments based on their prefix and structure.
///
/// # Examples
///
/// ```rust
/// use sap::{Parser, Argument};
///
/// let mut parser = Parser::from_arbitrary(["prog", "--verbose", "-x", "file.txt"]).unwrap();
///
/// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("verbose")));
/// assert_eq!(parser.forward().unwrap(), Some(Argument::Short('x')));
/// assert_eq!(parser.forward().unwrap(), Some(Argument::Value("file.txt".into())));
/// ```
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)]
pub enum Argument<'a> {
    /// A long option starting with `--` (e.g., `--verbose`, `--file`).
    ///
    /// Long options can have associated values via `--option=value` syntax.
    /// Use [`Parser::value`] after parsing to retrieve the value if present.
    Long(&'a str),

    /// A short option starting with `-` followed by a single character (e.g., `-v`, `-x`).
    ///
    /// Short options can be combined (`-abc` becomes three separate `Short` arguments).
    /// They cannot have values attached with `=` syntax, but can consume the next argument as a value.
    Short(char),

    /// A positional argument or operand (e.g., `file.txt`, `/path/to/file`).
    ///
    /// This includes any argument that doesn't start with `-` or `--`, as well as
    /// all arguments following the `--` terminator.
    Value(Cow<'a, str>),

    /// The special `-` argument, typically representing stdin/stdout.
    ///
    /// This is commonly used in Unix tools to indicate reading from standard input
    /// or writing to standard output.
    Stdio,
}

impl Argument<'_> {
    /// Converts this argument into a [`ParsingError::Unexpected`] error.
    ///
    /// This is a convenience method for creating contextual error messages when an argument
    /// is encountered but not expected by the application. The resulting error message
    /// includes appropriate formatting based on the argument type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::Argument;
    ///
    /// // Long option
    /// let arg = Argument::Long("unknown");
    /// let error = arg.unexpected();
    /// assert_eq!(error.to_string(), "unexpected argument: --unknown");
    ///
    /// // Short option
    /// let arg = Argument::Short('x');
    /// let error = arg.unexpected();
    /// assert_eq!(error.to_string(), "unexpected argument: -x");
    ///
    /// // Positional value
    /// let arg = Argument::Value("file".into());
    /// let error = arg.unexpected();
    /// assert_eq!(error.to_string(), "unexpected argument: file");
    ///
    /// // Stdio argument
    /// let arg = Argument::Stdio;
    /// let error = arg.unexpected();
    /// assert_eq!(error.to_string(), "unexpected argument: -");
    /// ```
    #[must_use]
    pub fn unexpected(&self) -> ParsingError {
        ParsingError::Unexpected {
            argument: self.to_string(),
        }
    }
}

impl Display for Argument<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use Argument::{Long, Short, Stdio, Value};

        match self {
            Long(s) => write!(f, "--{s}"),
            Short(ch) => write!(f, "-{ch}"),
            Value(cow) => write!(f, "{cow}"),
            Stdio => write!(f, "-"),
        }
    }
}

/// A stateful command-line argument parser.
///
/// The `Parser` processes arguments one at a time using an iterator-based approach,
/// maintaining internal state to handle complex scenarios like combined short options
/// and option values.
///
/// # Type Parameters
///
/// * `I` - An iterator that yields items convertible to `String` (e.g., `&str`, `String`, `OsString`)
///
/// # Examples
///
/// ```rust
/// use sap::{Parser, Argument};
///
/// // Parse from environment arguments
/// let mut parser = Parser::from_env().unwrap();
///
/// // Or parse from string arrays directly
/// let mut parser = Parser::from_arbitrary(["myprogram", "-abc", "--verbose"]).unwrap();
///
/// // Process arguments one by one
/// while let Some(arg) = parser.forward().unwrap() {
///     match arg {
///         Argument::Short(c) => println!("Short option: -{}", c),
///         Argument::Long(name) => println!("Long option: --{}", name),
///         Argument::Value(val) => println!("Value: {}", val),
///         Argument::Stdio => println!("Stdin/stdout argument"),
///     }
/// }
/// ```
pub struct Parser<I: Iterator> {
    iter: Peekable<I>,
    state: State,
    name: String,
    last_arg: String,
}

/// Internal parser state for handling complex parsing scenarios.
///
/// The parser uses this state machine to track context between calls to [`Parser::forward`],
/// enabling proper handling of combined options, option values, and argument terminators.
enum State {
    /// Normal parsing state with no special context.
    NotInteresting,
    /// Contains a value from a previous option (e.g., from `--option=value`).
    LeftoverValue(String),
    /// Processing combined short options like `-abc` (position in string, remaining chars).
    Combined(usize, String),
    /// All remaining arguments are positional values (after encountering `--`).
    End,
    /// Parser encountered an error and stopped consuming from the underlying iterator.
    Poisoned,
}

#[cfg(feature = "std")]
impl Parser<env::Args> {
    /// Creates a `Parser` using the program's command-line arguments from [`std::env::args`].
    ///
    /// This is the most common way to create a parser for typical CLI applications.
    /// The first argument (program name) is consumed and can be accessed via [`Parser::name`].
    ///
    /// # Errors
    ///
    /// Returns [`ParsingError::Empty`] if no arguments are available (which should not
    /// happen in normal program execution).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::Parser;
    ///
    /// let parser = Parser::from_env().unwrap();
    /// println!("Program name: {}", parser.name());
    /// ```
    pub fn from_env() -> Result<Self> {
        Self::from_arbitrary(env::args())
    }
}

/// Trait for types that can be used as command-line arguments.
///
/// This is a sealed trait implemented for common string-like types:
/// `String`, `&str`, `&CStr`, `CString`, and (with the `std` feature)
/// `OsStr` and `OsString`. It cannot be implemented outside this crate.
pub trait ArgLike: sealed::Sealed {
    /// Converts this value into an argument string.
    ///
    /// # Errors
    ///
    /// Returns a [`Utf8Error`] if the value is not valid UTF-8.
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error>;

    /// Borrows this value as an argument string.
    ///
    /// # Errors
    ///
    /// Returns a [`Utf8Error`] if the value is not valid UTF-8.
    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error>;
}

impl ArgLike for String {
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error> {
        Ok(Cow::Owned(self))
    }

    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error> {
        Ok(Cow::Borrowed(self.as_str()))
    }
}

impl ArgLike for &str {
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error> {
        Ok(Cow::Owned(self.to_owned()))
    }

    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error> {
        Ok(Cow::Borrowed(*self))
    }
}

impl ArgLike for &CStr {
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error> {
        Ok(Cow::Owned(self.to_str()?.to_owned()))
    }

    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error> {
        self.to_str().map(Cow::Borrowed)
    }
}

impl ArgLike for CString {
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error> {
        self.into_string()
            .map(Cow::Owned)
            .map_err(|e| e.utf8_error())
    }

    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error> {
        self.to_str().map(Cow::Borrowed)
    }
}

#[cfg(feature = "std")]
impl ArgLike for &OsStr {
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error> {
        core::str::from_utf8(self.as_encoded_bytes()).map(|s| Cow::Owned(s.to_owned()))
    }

    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error> {
        match self.to_str() {
            Some(s) => Ok(Cow::Borrowed(s)),
            None => Err(core::str::from_utf8(self.as_encoded_bytes()).unwrap_err()),
        }
    }
}

#[cfg(feature = "std")]
impl ArgLike for OsString {
    fn into_arg<'v>(self) -> Result<Cow<'v, str>, Utf8Error> {
        core::str::from_utf8(self.as_encoded_bytes()).map(|s| Cow::Owned(s.to_owned()))
    }

    fn as_arg(&self) -> Result<Cow<'_, str>, Utf8Error> {
        match self.to_str() {
            Some(s) => Ok(Cow::Borrowed(s)),
            None => Err(core::str::from_utf8(self.as_encoded_bytes()).unwrap_err()),
        }
    }
}

mod sealed {
    #[cfg(not(feature = "std"))]
    use alloc::ffi::CString;
    use core::ffi::CStr;
    #[cfg(feature = "std")]
    use std::ffi::{CString, OsStr, OsString};

    pub trait Sealed {}

    impl Sealed for String {}
    impl Sealed for &str {}
    impl Sealed for &CStr {}
    impl Sealed for CString {}
    #[cfg(feature = "std")]
    impl Sealed for &OsStr {}
    #[cfg(feature = "std")]
    impl Sealed for OsString {}
}

impl<'a, I, V> Parser<I>
where
    I: Iterator<Item = V>,
    V: ArgLike,
{
    /// Creates a `Parser` from any iterator that yields [`ArgLike`] items.
    ///
    /// The first item is consumed as the program name (accessible via [`Parser::name`]).
    /// All subsequent items are parsed as arguments. Accepts string arrays, `Vec<String>`,
    /// or any other iterable of string-like values, which makes this the natural choice
    /// for tests and for parsing argument lists that don't come from the environment.
    ///
    /// # Errors
    ///
    /// Returns [`ParsingError::Empty`] if the iterator is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::Parser;
    ///
    /// // Parse from string arrays directly
    /// let parser = Parser::from_arbitrary(["myprogram", "-v", "file.txt"]).unwrap();
    /// assert_eq!(parser.name(), "myprogram");
    ///
    /// // Also works with vectors of strings
    /// let args = vec!["prog".to_string(), "--verbose".to_string()];
    /// let parser = Parser::from_arbitrary(args).unwrap();
    /// ```
    pub fn from_arbitrary<A>(iter: A) -> Result<Parser<I>>
    where
        A: IntoIterator<IntoIter = I>,
    {
        let mut iter = iter.into_iter().peekable();
        let name = iter
            .next()
            .ok_or(ParsingError::Empty)?
            .into_arg()?
            .into_owned();

        Ok(Parser {
            iter,
            state: State::NotInteresting,
            name,
            last_arg: String::new(),
        })
    }

    /// Advances the parser to the next argument and returns it.
    ///
    /// This is the main parsing method. Call it repeatedly to process all arguments.
    /// The parser maintains state between calls to properly handle complex scenarios
    /// like combined short options (`-abc`) and option values.
    ///
    /// # Returns
    ///
    /// - `Some(arg)` - Successfully parsed the next argument
    /// - `None` - No more arguments to process
    ///
    /// # Errors
    ///
    /// Returns an error when:
    /// - Short options have attached values using `=` (e.g., `-x=value`)
    /// - Option values are left unconsumed from previous calls
    /// - Invalid argument syntax is encountered
    ///
    /// ## Poisoned State
    ///
    /// After returning an error, the parser enters a "poisoned" state where:
    /// - All subsequent calls to `forward()` will return `Ok(None)`
    /// - The underlying iterator will not be polled further
    /// - The iterator can still be recovered using [`Parser::into_inner`] if needed
    ///
    /// This ensures predictable behavior after errors and allows recovering the
    /// remaining unparsed arguments without risking inconsistent parser state.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// let mut parser = Parser::from_arbitrary(["prog", "-abc", "--file=test.txt"]).unwrap();
    ///
    /// // Combined short options are parsed individually
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Short('a')));
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Short('b')));
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Short('c')));
    ///
    /// // Long option with attached value
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("file")));
    /// assert_eq!(parser.value()?, Some("test.txt".to_string()));
    ///
    /// assert_eq!(parser.forward().unwrap(), None);
    /// ```
    pub fn forward(&'a mut self) -> Result<Option<Argument<'a>>> {
        loop {
            match self.state {
                State::Poisoned => return Ok(None),
                State::End => {
                    return match self.iter.next() {
                        Some(v) => Ok(Some(Argument::Value(v.into_arg()?))),
                        None => Ok(None),
                    };
                }
                State::Combined(index, ref mut options) => {
                    let options = mem::take(options);

                    match options.chars().nth(index) {
                        Some(char) => {
                            if char == '=' {
                                self.state = State::Poisoned;

                                return Err(ParsingError::InvalidSyntax {
                                    reason: "Short options do not support values",
                                });
                            }

                            self.state = State::Combined(index + 1, options);

                            return Ok(Some(Argument::Short(char)));
                        }
                        None => self.state = State::NotInteresting,
                    }
                }
                State::NotInteresting => {
                    let next = match self.iter.next() {
                        Some(s) => s.into_arg()?,
                        None => return Ok(None),
                    };

                    match next.strip_prefix("-") {
                        Some("") => return Ok(Some(Argument::Stdio)),
                        Some("-") => {
                            self.state = State::End;
                        }
                        Some(rest) => {
                            if rest.starts_with('-') {
                                self.last_arg = next.into_owned();

                                if let Some(index) = self.last_arg.find('=') {
                                    self.state =
                                        State::LeftoverValue(self.last_arg[index + 1..].to_owned());

                                    return Ok(Some(Argument::Long(&self.last_arg[2..index])));
                                }

                                return Ok(Some(Argument::Long(&self.last_arg[2..])));
                            }

                            self.state = State::Combined(0, rest.to_owned());
                        }

                        None => {
                            return Ok(Some(Argument::Value(next)));
                        }
                    }
                }
                State::LeftoverValue(ref mut value) => {
                    let value = mem::take(value);
                    self.state = State::Poisoned;

                    return Err(ParsingError::UnconsumedValue { value });
                }
            }
        }
    }

    /// Retrieves and consumes the value associated with the most recent option.
    ///
    /// This method handles two cases:
    ///
    /// 1. **Inline value** (`--option=value` syntax): If the most recently parsed long
    ///    option had an attached value, that value is returned and consumed.
    ///
    /// 2. **Separate argument**: If there is no inline value, the method peeks at the
    ///    next iterator item. If it does not start with `-` (i.e., it is not another
    ///    option or the `-` stdin marker), it is consumed and returned as the value.
    ///    Otherwise, `None` is returned and the next item remains unconsumed.
    ///
    /// Note: Calling `value()` while processing combined short options (e.g., between
    /// flags of `-abc`) always returns `None`. Once all flags in the cluster are
    /// exhausted, `value()` falls back to the separate-argument behavior described above.
    ///
    /// # Errors
    ///
    /// Returns an error if the next argument value is not valid UTF-8.
    ///
    /// # Returns
    ///
    /// - `Some(value)` - The option has an attached or following value
    /// - `None` - The option has no value, or it was already consumed, or the next
    ///   argument starts with `-`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// // Inline value via --option=value
    /// let mut parser = Parser::from_arbitrary(["prog", "--file=input.txt", "--verbose"]).unwrap();
    ///
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("file")));
    /// assert_eq!(parser.value()?, Some("input.txt".to_string()));
    /// assert_eq!(parser.value()?, None); // Already consumed
    ///
    /// // Option without value
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("verbose")));
    /// assert_eq!(parser.value()?, None);
    ///
    /// // Separate argument value: --file myfile.txt
    /// let mut parser = Parser::from_arbitrary(["prog", "--file", "myfile.txt"]).unwrap();
    ///
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("file")));
    /// assert_eq!(parser.value()?, Some("myfile.txt".to_string()));
    ///
    /// // Short option with separate value: -f myfile.txt
    /// let mut parser = Parser::from_arbitrary(["prog", "-f", "myfile.txt"]).unwrap();
    ///
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Short('f')));
    /// assert_eq!(parser.value()?, Some("myfile.txt".to_string()));
    /// ```
    pub fn value(&mut self) -> Result<Option<String>> {
        // If all combined short flags have been consumed, treat the state as
        // NotInteresting so we can peek at the next argument as a separate value.
        // This needs to stay a match statement to mantain msrv 1.85
        match self.state {
            State::Combined(index, ref options) if index >= options.len() => {
                self.state = State::NotInteresting;
            }
            _ => {}
        }

        match self.state {
            State::End | State::Poisoned | State::Combined(..) => Ok(None),
            State::LeftoverValue(ref mut value) => {
                let value = mem::take(value);
                self.state = State::NotInteresting;

                Ok(Some(value))
            }
            State::NotInteresting => {
                let arg = match self.iter.peek() {
                    Some(v) => {
                        let arg = v.as_arg()?;

                        if arg.starts_with('-') {
                            return Ok(None);
                        }

                        arg.into_owned()
                    }
                    None => return Ok(None),
                };

                self.iter.next();

                Ok(Some(arg))
            }
        }
    }

    /// Discards any value associated with the most recent option.
    ///
    /// This is a convenience method that calls [`Parser::value`] and discards the result.
    /// Use this when you know an option might have a value but you don't need it,
    /// preventing unconsumed value errors.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// let mut parser = Parser::from_arbitrary(["prog", "--debug=verbose"]).unwrap();
    ///
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("debug")));
    /// parser.ignore_value(); // Discard the "verbose" value
    /// ```
    pub fn ignore_value(&mut self) {
        let _ = self.value();
    }

    /// Returns the program name (the first argument from the iterator).
    ///
    /// This is typically the name or path of the executable, depending on how
    /// the program was invoked.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::Parser;
    ///
    /// let parser = Parser::from_arbitrary(["/usr/bin/myprogram", "-v"]).unwrap();
    /// assert_eq!(parser.name(), "/usr/bin/myprogram");
    /// ```
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns `true` if the parser is in a poisoned state due to a previous error.
    ///
    /// When poisoned, `forward()` will always return `Ok(None)`. Use `into_inner()`
    /// to recover the underlying iterator if needed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// let mut parser = Parser::from_arbitrary(["prog", "--file=test"]).unwrap();
    ///
    /// assert!(!parser.is_poisoned());
    ///
    /// // Parse option without consuming value
    /// parser.forward().unwrap();
    ///
    /// // This errors and poisons the parser
    /// assert!(parser.forward().is_err());
    /// assert!(parser.is_poisoned());
    /// ```
    pub const fn is_poisoned(&self) -> bool {
        matches!(self.state, State::Poisoned)
    }

    /// Returns `true` if there is an unconsumed value from a previous option.
    ///
    /// This occurs when parsing options like `--file=value` where the value has not
    /// yet been retrieved via `value()` or discarded via `ignore_value()`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// let mut parser = Parser::from_arbitrary(["prog", "--file=test.txt"]).unwrap();
    ///
    /// assert!(!parser.has_leftover_value());
    ///
    /// // Parse the option
    /// parser.forward().unwrap();
    ///
    /// // Now there's a leftover value
    /// assert!(parser.has_leftover_value());
    ///
    /// // Consume it
    /// parser.value()?;
    /// assert!(!parser.has_leftover_value());
    /// ```
    pub const fn has_leftover_value(&self) -> bool {
        matches!(self.state, State::LeftoverValue(_))
    }

    /// Consumes the parser and returns the underlying iterator.
    ///
    /// This allows access to any remaining, unparsed arguments. The iterator's
    /// position reflects where parsing stopped.
    ///
    /// # Error Recovery
    ///
    /// When the parser enters a poisoned state, the underlying iterator is left
    /// intact. Call `into_inner` to retrieve it and inspect or reprocess the
    /// arguments that were not yet consumed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// let mut parser = Parser::from_arbitrary(["prog", "-v", "remaining"]).unwrap();
    ///
    /// // Parse one argument
    /// parser.forward().unwrap();
    ///
    /// // Get the remaining iterator
    /// let remaining: Vec<String> = parser.into_inner().map(|s| s.into()).collect();
    /// assert_eq!(remaining, vec!["remaining"]);
    /// ```
    ///
    /// ```rust
    /// use sap::{Parser, Argument};
    ///
    /// let mut parser = Parser::from_arbitrary(["prog", "--file=test", "--other"]).unwrap();
    ///
    /// // Parse first option but forget to consume value
    /// assert_eq!(parser.forward().unwrap(), Some(Argument::Long("file")));
    ///
    /// // This will error due to unconsumed value, poisoning the parser
    /// assert!(parser.forward().is_err());
    ///
    /// // Recover the remaining unparsed arguments
    /// let remaining: Vec<String> = parser.into_inner().map(|s| s.into()).collect();
    /// assert_eq!(remaining, vec!["--other"]);
    /// ```
    pub fn into_inner(self) -> Peekable<I> {
        self.iter
    }
}

/// Errors that can occur during argument parsing.
///
/// All parsing operations return a `Result` with this error type. Each variant
/// provides specific context about what went wrong during parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsingError {
    /// The argument iterator was empty (contained no program name).
    ///
    /// Returned by [`Parser::from_arbitrary`] when the iterator yields no items,
    /// or by [`Parser::from_env`] if the OS provides an empty argument list.
    Empty,

    /// Invalid option syntax or format was encountered.
    ///
    /// This currently occurs when short options are given values with `=` syntax
    /// (e.g., `-x=value`).
    ///
    /// # Fields
    ///
    /// * `reason` - Human-readable description of what was invalid
    InvalidSyntax {
        /// Human-readable description of what was invalid.
        reason: &'static str,
    },

    /// An option value was not consumed after being parsed.
    ///
    /// This occurs when a long option has an attached value (e.g., `--file=input.txt`)
    /// but the application doesn't call [`Parser::value`] or [`Parser::ignore_value`]
    /// before parsing the next argument.
    ///
    /// # Fields
    ///
    /// * `value` - The unconsumed value that was attached to the option
    UnconsumedValue {
        /// The unconsumed value that was attached to the option.
        value: String,
    },

    /// An unexpected or unrecognized argument was encountered.
    ///
    /// This error is typically created by calling [`Argument::unexpected`] when
    /// the application encounters an argument it doesn't know how to handle.
    ///
    /// # Fields
    ///
    /// * `argument` - The formatted argument string (e.g., "--unknown", "-x value", "file.txt")
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sap::{Argument, ParsingError};
    ///
    /// let error = Argument::Long("unknown").unexpected();
    /// assert_eq!(error.to_string(), "unexpected argument: --unknown");
    /// ```
    Unexpected {
        /// The formatted argument string (e.g., `--unknown`, `-x`, `file.txt`).
        argument: String,
    },

    /// A UTF-8 decoding error from converting an argument to a string.
    ///
    /// Propagated from [`ArgLike`] implementations when an argument contains
    /// invalid UTF-8 sequences.
    Utf8Error(Utf8Error),
}

impl Display for ParsingError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Empty => write!(f, "argument list is empty"),
            Self::InvalidSyntax { reason } => write!(f, "invalid syntax: {reason}"),
            Self::UnconsumedValue { value } => write!(f, "unconsumed value: {value}"),
            Self::Unexpected { argument } => write!(f, "unexpected argument: {argument}"),
            Self::Utf8Error(err) => Display::fmt(err, f),
        }
    }
}

impl Error for ParsingError {}

impl From<Utf8Error> for ParsingError {
    fn from(err: Utf8Error) -> Self {
        ParsingError::Utf8Error(err)
    }
}