ezmenulib 0.2.10

Build easily a CLI menu.
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Module defining the different types of menus.
//!
//! ## The types
//!
//! There are two types of menus:
//! - the [value-menus](ValueMenu): they corresponds to the menu where the user has to enter
//! the value himself, for example for a name providing.
//! - the [selectable menus](SelectMenu): they corresponds to the menu where the user has to select
//! a value among proposed values by a list.
//!
//! ## Fields
//!
//! The `ValueMenu` can contain [`ValueField`s](crate::field::ValueField)
//! and [`SelectMenu`s](SelectMenu).
//! This behavior allows to use the selectable menus as sub-menus to retrieve
//! values.
//!
//! The `SelectMenu` contains [`SelectField`s](crate::field::SelectField).
//!
//! ## Formatting
//!
//! The formatting rules are defined by the [`ValueFieldFormatting`](crate::field::ValueFieldFormatting) struct.
//! It manages how the output of a message before the user input should be displayed.
//!
//! For a value-menu, you can apply global formatting rules with the [`ValueMenu::fmt`] method,
//! which will be applied on all the fields it contains. You can also apply rules on
//! specific fields.
//!
//! When a `SelectMenu` inherits the rules of its parent `ValueMenu`, they are applied on its title.
//!
//! ## Outputs
//!
//! The values entered by the user are provided by the [`MenuBuilder`] trait.
//! This trait is implemented on both menus type and uses the [`MenuBuilder::next_output`] method
//! to return the next output provided by the user.
//!
//! When calling this method, you need to provide your own type to convert the input from.
//!
//! The next output of a value-menu corresponds to its next fields, so if it is, for example, a
//! selectable menu field, it will display the list of output values, then return the value the user
//! selected. Attention: if all the fields have been retrieved, the value-menu will be empty, and the
//! next call of this method will panic.
//!
//! Therefore, a selectable menu can return many times the value selected by the user at different
//! points of the code.
//!
//! ## Example
//!
//! ```
//! use std::str::FromStr;
//! use ezmenulib::customs;
//! use ezmenulib::prelude::*;
//!
//! enum Type {
//!     MIT,
//!     GPL,
//!     BSD,
//! }
//!
//! impl FromStr for Type {
//!     type Err = MenuError;
//!
//!     fn from_str(s: &str) -> MenuResult<Self> {
//!         match s.to_lowercase().as_str() {
//!             "mit" => Ok(Self::MIT),
//!             "gpl" => Ok(Self::GPL),
//!             "bsd" => Ok(Self::BSD),
//!             s => Err(MenuError::from(format!("unknown license type: {}", s))),
//!         }
//!     }
//! }
//!
//! let mut license = ValueMenu::from([
//!     Field::Value(ValueField::from("Authors")),
//!     Field::Select(SelectMenu::from([
//!         SelectField::from("MIT"),
//!         SelectField::from("GPL"),
//!         SelectField::from("BSD"),
//!     ])
//!     .default(0)
//!     .title(SelectTitle::from("Select the license type"))),
//! ]);
//!
//! let authors: customs::MenuVec<String> = license.next_output().unwrap();
//! let ty: Type = license.next_output().unwrap();
//! ```

mod stream;

pub use crate::menu::stream::MenuStream;
use crate::menu::stream::Stream;
use crate::prelude::*;
use std::fmt::{self, Debug, Display, Formatter};
use std::io::{BufRead, BufReader, Stdin, Stdout, Write};
use std::rc::Rc;
use std::str::FromStr;
use std::vec::IntoIter;

/// The default input stream used by a menu, using the standard input stream.
pub type In = BufReader<Stdin>;

/// The default output stream used by a menu, using the standard output stream.
pub type Out = Stdout;

/// Used to retrieve the stream contained in a menu.
pub trait GetStream<'s, R: 's, W: 's>: Sized {
    /// Returns the menu stream, consuming the menu.
    fn get_stream(self) -> MenuStream<'s, R, W>;

    /// Returns the input and output streams, consuming the menu.
    /// See [`MenuStream::retrieve`](stream::MenuStream::retrieve) for more information.
    ///
    /// ## Panics
    ///
    /// If it hasn't been given a reader and a writer, this method will panic, because it needs
    /// to own the reader and writer to retrieve it at the end.
    #[inline]
    fn retrieve(self) -> (R, W) {
        self.get_stream().retrieve()
    }
}

/// The position of the title for an enum menu.
/// By default, the title position is at the top.
///
/// ## Example
///
/// ```
/// use ezmenulib::prelude::*;
///
/// let amount: MenuResult<u8> = SelectMenu::from([
///     SelectField::from("first"),
///     SelectField::from("second"),
///     SelectField::from("third"),
/// ])
/// .title(SelectTitle::from("set the podium").pos(TitlePos::Bottom))
/// .next_output();
/// ```
#[derive(Clone, Copy)]
pub enum TitlePos {
    /// Position at the top of the menu:
    /// ```text
    /// <title>
    /// 1 - field0
    /// 2 - field1
    /// ...
    /// >>
    /// ```
    Top,
    /// Position at the bottom of the menu:
    /// ```text
    /// 1 - field0
    /// 2 - field1
    /// ...
    /// <title>
    /// >>
    /// ```
    Bottom,
}

impl Default for TitlePos {
    /// Default position for the menu title is at the top.
    fn default() -> Self {
        Self::Top
    }
}

/// Struct modeling a selective menu.
///
/// ## Example
///
/// ```
/// use std::str::FromStr;
/// use ezmenulib::prelude::*;
///
/// enum Type {
///     MIT,
///     GPL,
///     BSD,
/// }
///
/// impl FromStr for Type {
///     type Err = MenuError;
///
///     fn from_str(s: &str) -> MenuResult<Self> {
///         match s.to_lowercase().as_str() {
///             "mit" => Ok(Self::MIT),
///             "gpl" => Ok(Self::GPL),
///             "bsd" => Ok(Self::BSD),
///             s => Err(MenuError::from(format!("unknown license type: {}", s))),
///         }
///     }
/// }
///
/// let license_type: Type = SelectMenu::from([
///     SelectField::from("MIT"),
///     SelectField::from("GPL"),
///     SelectField::from("BSD"),
/// ])
/// .title(SelectTitle::from("Choose a license type"))
/// .default(0)
/// .next_output()
/// .unwrap();
/// ```
///
/// ## Formatting
///
/// The selective menu has two editable formatting rules.
/// Like [`ValueFieldFormatting`], it contains a `chip` and a `prefix`:
/// ```text
/// X<chip><message>
/// X<chip><message>
/// ...
/// <prefix>
/// ```
///
/// The default chip is `" - "`, and the default prefix is `">> "`.
pub struct SelectMenu<'a, R = In, W = Out> {
    title: SelectTitle<'a>,
    fields: Vec<SelectField<'a, R, W>>,
    stream: Stream<'a, MenuStream<'a, R, W>>,
    default: Option<usize>,
    prefix: &'a str,
}

/// Represents the title of a selectable menu.
///
/// It has its own type because it manages its position, its formatting,
/// and the formatting of the fields inside the selectable menu.
///
/// ## Example
///
/// ```
/// use ezmenulib::{prelude::*, customs::MenuBool};
///     
/// let is_adult: MenuBool = SelectMenu::from([
///     SelectField::from("yes"),
///     SelectField::from("no"),
/// ])
/// .title(SelectTitle::from("Are you an adult?")
///     .fmt(ValueFieldFormatting::chip("==> "))
///     .pos(TitlePos::Top))
/// .default(1)
/// .next_output()
/// .unwrap();
/// ```
pub struct SelectTitle<'a> {
    inner: &'a str,
    fmt: ValueFieldFormatting<'a>,
    custom_fmt: bool,
    pub(crate) pos: TitlePos,
}

impl Default for SelectTitle<'_> {
    fn default() -> Self {
        Self {
            inner: "",
            fmt: ValueFieldFormatting {
                chip: "",
                prefix: "",
                new_line: true,
                ..Default::default()
            },
            custom_fmt: false,
            pos: Default::default(),
        }
    }
}

impl<'a> From<&'a str> for SelectTitle<'a> {
    fn from(inner: &'a str) -> Self {
        Self {
            inner,
            fmt: ValueFieldFormatting::prefix(":"),
            custom_fmt: false,
            pos: Default::default(),
        }
    }
}

impl<'a> SelectTitle<'a> {
    /// Sets the formatting of the selectable menu title.
    ///
    /// The formatting type is the same as the [`ValueField`](crate::field::ValueField) is using.
    pub fn fmt(mut self, fmt: ValueFieldFormatting<'a>) -> Self {
        self.fmt = fmt;
        self.custom_fmt = true;
        self
    }

    /// Sets the position of the title.
    ///
    /// By default, the title position is at the top (see [`TitlePos`]).
    pub fn pos(mut self, pos: TitlePos) -> Self {
        self.pos = pos;
        self
    }

    /// Inherits the formatting rules from a parent menu (the [`ValueMenu`](crate::menu::ValueMenu)).
    ///
    /// It saves the prefix, because the default prefix is `>> ` and is not compatible with the
    /// title displaying.
    pub(crate) fn inherit_fmt(&mut self, fmt: Rc<ValueFieldFormatting<'a>>) {
        self.fmt = ValueFieldFormatting {
            chip: fmt.chip,
            new_line: fmt.new_line,
            default: fmt.default,
            // saving prefix
            prefix: self.fmt.prefix,
        };
        self.custom_fmt = false;
    }
}

impl Display for SelectTitle<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.inner.is_empty() {
            return Ok(());
        }

        let disp = format!(
            "{chip}{title}{prefix}",
            chip = self.fmt.chip,
            title = self.inner,
            prefix = self.fmt.prefix,
        );

        if self.fmt.new_line {
            writeln!(f, "{}", disp)
        } else {
            write!(f, "{}", disp)
        }
    }
}

impl<'a> From<Vec<SelectField<'a>>> for SelectMenu<'a> {
    /// Builds the menu from its fields vector.
    #[inline]
    fn from(fields: Vec<SelectField<'a>>) -> Self {
        Self::with_owned(MenuStream::default(), fields)
    }
}

impl<'a, const N: usize> From<[SelectField<'a>; N]> for SelectMenu<'a> {
    /// Builds the menu from an array of fields.
    #[inline]
    fn from(fields: [SelectField<'a>; N]) -> Self {
        Self::from(Vec::from(fields))
    }
}

impl<'a, R, W> SelectMenu<'a, R, W> {
    fn inner_new(
        stream: Stream<'a, MenuStream<'a, R, W>>,
        fields: Vec<SelectField<'a, R, W>>,
    ) -> Self {
        Self {
            title: Default::default(),
            fields,
            stream,
            default: None,
            prefix: ">> ",
        }
    }

    /// Builds the menu from its owned menu stream, with its fields vector.
    #[inline]
    pub fn with_owned(stream: MenuStream<'a, R, W>, fields: Vec<SelectField<'a, R, W>>) -> Self {
        Self::inner_new(Stream::Owned(stream), fields)
    }

    /// Builds the menu from a mutable reference of a menu stream, with its fields vector.
    #[inline]
    pub fn with_ref(
        stream: &'a mut MenuStream<'a, R, W>,
        fields: Vec<SelectField<'a, R, W>>,
    ) -> Self {
        Self::inner_new(Stream::Borrowed(stream), fields)
    }

    /// Builds the menu from mutable references of the reader and writer, with its fields vector.
    #[inline]
    pub fn new_ref(
        reader: &'a mut R,
        writer: &'a mut W,
        fields: Vec<SelectField<'a, R, W>>,
    ) -> Self {
        Self::with_owned(MenuStream::with(reader, writer), fields)
    }

    /// Sets the title of the selective menu.
    ///
    /// The title is by default displayed at the top of the selective fields,
    /// but you can edit this behavior by setting the title position to `TitlePos::Bottom`, with
    /// `SelectMenu::title_pos` method.
    #[inline]
    pub fn title(mut self, title: SelectTitle<'a>) -> Self {
        self.title = title;
        self
    }

    /// Sets the default selective field.
    ///
    /// If you have specified a default field, the latter will be marked as `"(default)"`.
    /// Thus, if the user skips the selective menu (by pressing enter without input), it will return
    /// the default selective field.
    pub fn default(mut self, default: usize) -> Self {
        self.default = Some(default);
        self
    }

    /// Sets the user input prefix of the selective menu.
    ///
    /// By default, the prefix used is `">> "`.
    pub fn prefix(mut self, prefix: &'a str) -> Self {
        self.prefix = prefix;
        self
    }

    /// Sets the chip of the selective menu.
    ///
    /// The chip is the short string slice placed between the field index and the field message.
    /// It acts as a list style attribute.
    pub fn chip(mut self, chip: &'a str) -> Self {
        for field in self.fields.as_mut_slice() {
            field.set_chip(chip);
        }
        self
    }

    #[inline]
    pub(crate) fn inherit_fmt(&mut self, fmt: Rc<ValueFieldFormatting<'a>>) {
        self.title.inherit_fmt(fmt);
    }
}

impl<'a, R, W> GetStream<'a, R, W> for SelectMenu<'a, R, W> {
    #[inline]
    fn get_stream(self) -> MenuStream<'a, R, W> {
        self.stream.retrieve()
    }
}

impl<R, W> Display for SelectMenu<'_, R, W> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        // displays title at top
        if let TitlePos::Top = self.title.pos {
            write!(f, "{}", self.title)?;
        }

        // displays fields
        for (i, field) in self.fields.iter().enumerate() {
            writeln!(
                f,
                "{i}{msg}{def}",
                i = i + 1,
                msg = field,
                def = if matches!(self.default, Some(d) if d == i) {
                    " (default)"
                } else {
                    ""
                },
            )?;
        }

        // displays title at bottom
        if let TitlePos::Bottom = self.title.pos {
            write!(f, "{}", self.title)?;
        }
        Ok(())
    }
}

/// Returns an error meaning that the value type contained in the string slice is incorrect.
#[inline]
fn err_ty<E: 'static + Debug>(e: E) -> MenuError {
    MenuError::from(format!("incorrect default value type: {:?}", e))
}

/// Returns the default value among the fields.
///
/// If the default value index or the aimed default field type is incorrect,
/// it will return an error (See [`MenuError::IncorrectType`]).
fn default_parse<Output, R, W>(
    default: usize,
    fields: &[SelectField<'_, R, W>],
    stream: &mut MenuStream<R, W>,
) -> MenuResult<Output>
where
    Output: FromStr,
    Output::Err: 'static + Debug,
{
    let field = fields.get(default).unwrap_or_else(|| {
        default_parse_failed(
            default,
            format!(
                "incorrect index: fields vector length is {}, index is {}",
                fields.len(),
                default
            ),
        )
    });
    field.call_bind(stream)?;
    Ok(field
        .msg
        .parse()
        .unwrap_or_else(|e| default_parse_failed(default, e)))
}

impl<Output, R, W> MenuBuilder<Output, R, W> for SelectMenu<'_, R, W>
where
    Output: FromStr,
    Output::Err: 'static + Debug,
    R: BufRead,
    W: Write,
{
    /// Displays the selective menu to the user, then return the field he selected.
    ///
    /// ## Example
    ///
    /// ```
    /// use std::str::FromStr;
    /// use ezmenulib::prelude::*;
    ///
    /// enum Amount {
    ///     Exact(u8),
    ///     More,
    /// }
    ///
    /// impl FromStr for Amount {
    ///     type Err = MenuError;
    ///
    ///     fn from_str(s: &str) -> Result<Self, Self::Err> {
    ///         match s {
    ///             "one" => Ok(Self::Exact(1)),
    ///             "two" => Ok(Self::Exact(2)),
    ///             "three" => Ok(Self::Exact(3)),
    ///             "more" => Ok(Self::More),
    ///             _ => Err(MenuError::from("no")),
    ///         }
    ///     }
    /// }
    ///
    /// let amount: Amount = SelectMenu::from([
    ///     SelectField::from("one"),
    ///     SelectField::from("two"),
    ///     SelectField::from("three"),
    ///     SelectField::from("more"),
    /// ])
    /// .next_output()
    /// .unwrap();
    /// ```
    ///
    /// ## Panic
    ///
    /// This method panics if an incorrect index has been specified as default.
    fn next_output(&mut self) -> MenuResult<Output> {
        {
            let s = format!("{}", self);
            self.stream.write_all(s.as_bytes())?;
        }

        // loops while incorrect input
        loop {
            match select(&mut self.stream, self.prefix, self.default, &self.fields) {
                Ok(out) => break Ok(out),
                Err(_) => {
                    if let Some(default) = self.default {
                        break Ok(default_parse(default, &self.fields, &mut self.stream)?);
                    }
                }
            }
        }
    }

    /// Displays the selective menu to the user, then return the field he selected,
    /// using the given menu stream.
    ///
    /// ## Panic
    ///
    /// This method panics if an incorrect index has been specified as default.
    fn next_output_with(&mut self, stream: &mut MenuStream<R, W>) -> MenuResult<Output> {
        stream.write_all(format!("{}", self).as_bytes())?;

        loop {
            match select(stream, self.prefix, self.default, &self.fields) {
                Ok(out) => break Ok(out),
                Err(_) => {
                    if let Some(default) = self.default {
                        break Ok(default_parse(default, &self.fields, stream)?);
                    }
                }
            }
        }
    }

    /// Displays the selective menu to the user, then return the field he selected,
    /// or return the default value of the type specified.
    ///
    /// ## Panic
    ///
    /// This method panics if an incorrect index has been specified as default.
    fn next_or_default(&mut self) -> Output
    where
        Output: Default,
    {
        if {
            let s = format!("{}", self);
            self.stream.write_all(s.as_bytes())
        }
        .is_ok()
        {
            select(&mut self.stream, self.prefix, self.default, &self.fields).unwrap_or_default()
        } else {
            Output::default()
        }
    }

    /// Displays the selective menu to the user, then return the field he selected,
    /// or return the default value of the type specified, using the given menu stream.
    ///
    /// ## Panic
    ///
    /// This method panics if an incorrect index has been specified as default.
    fn next_or_default_with(&mut self, stream: &mut MenuStream<R, W>) -> Output
    where
        Output: Default,
    {
        if stream.write_all(format!("{}", self).as_bytes()).is_ok() {
            select(stream, self.prefix, self.default, &self.fields).unwrap_or_default()
        } else {
            Output::default()
        }
    }
}

// We need to use this function from the owned selectable menu stream,
// or from a provided one, so we don't mutate the whole selectable menu struct.
fn select<Output, R, W>(
    stream: &mut MenuStream<R, W>,
    prefix: &str,
    default: Option<usize>,
    fields: &[SelectField<R, W>],
) -> MenuResult<Output>
where
    W: Write,
    R: BufRead,
    Output: FromStr,
    Output::Err: 'static + Debug,
{
    stream.write_all(prefix.as_bytes())?;
    stream.flush()?;

    let out = raw_read_input(stream)?;

    if let Some(field) = fields
        .iter()
        .find(|field| field.msg.to_lowercase() == out.to_lowercase())
    {
        match out.parse::<Output>() {
            Ok(out) => {
                field.call_bind(stream)?;
                Ok(out)
            }
            Err(_) => {
                if let Some(default) = default {
                    default_parse(default, fields, stream)
                } else {
                    Err(MenuError::Select(out))
                }
            }
        }
    } else {
        match out.parse::<usize>() {
            Ok(idx) if idx >= 1 => {
                if let Some(field) = fields.get(idx - 1) {
                    field.call_bind(stream)?;
                    field.msg.parse().map_err(err_ty)
                } else {
                    Err(MenuError::Select(out))
                }
            }
            Err(_) => {
                if let Some(default) = default {
                    default_parse(default, fields, stream)
                } else {
                    Err(MenuError::Select(out))
                }
            }
            _ => Err(MenuError::Select(out)),
        }
    }
}

/// Represents a value-menu type, which means a menu that retrieves values from the user inputs.
///
/// The `R` type parameter represents its reader type, and the `W` type parameter means its writer type.
/// By default, it uses the standard input and output streams to get values from the user.
/// It wraps the streams into a [`MenuStream`].
///
/// It has a global formatting applied to the fields it contains by inheritance.
pub struct ValueMenu<'a, R = In, W = Out> {
    title: &'a str,
    fmt: Rc<ValueFieldFormatting<'a>>,
    fields: IntoIter<Field<'a, R, W>>,
    stream: Stream<'a, MenuStream<'a, R, W>>,
    popped: bool,
}

impl<'a, const N: usize> From<[Field<'a>; N]> for ValueMenu<'a> {
    /// Instantiate the value-menu from its value-fields array.
    #[inline]
    fn from(fields: [Field<'a>; N]) -> Self {
        Self::from(Vec::from(fields))
    }
}

impl<'a> From<Vec<Field<'a>>> for ValueMenu<'a> {
    #[inline]
    fn from(fields: Vec<Field<'a>>) -> Self {
        Self::with_owned(MenuStream::default(), fields)
    }
}

impl<'a, R, W> ValueMenu<'a, R, W> {
    fn inner_new(
        stream: Stream<'a, MenuStream<'a, R, W>>,
        mut fields: Vec<Field<'a, R, W>>,
    ) -> Self {
        let fmt: Rc<ValueFieldFormatting> = Rc::default();

        // inherits fmt on submenus title
        for field in fields.iter_mut() {
            field.inherit_fmt(fmt.clone());
        }

        Self {
            fields: fields.into_iter(),
            title: "",
            fmt,
            stream,
            popped: false,
        }
    }

    /// Builds the menu from its owned menu stream, with its fields vector.
    #[inline]
    pub fn with_owned(stream: MenuStream<'a, R, W>, fields: Vec<Field<'a, R, W>>) -> Self {
        Self::inner_new(Stream::Owned(stream), fields)
    }

    /// Builds the menu from a mutable reference of a menu stream, with its fields vector.
    #[inline]
    pub fn with_ref(stream: &'a mut MenuStream<'a, R, W>, fields: Vec<Field<'a, R, W>>) -> Self {
        Self::inner_new(Stream::Borrowed(stream), fields)
    }

    /// Builds the menu from its owned input and output streams, with its fields vector.
    #[inline]
    pub fn new(reader: R, writer: W, fields: Vec<Field<'a, R, W>>) -> Self {
        Self::with_owned(MenuStream::new(reader, writer), fields)
    }

    /// Builds the menu from mutable references of the reader and writer, with its fields vector.
    #[inline]
    pub fn new_ref(reader: &'a mut R, writer: &'a mut W, fields: Vec<Field<'a, R, W>>) -> Self {
        Self::with_owned(MenuStream::with(reader, writer), fields)
    }

    /// Give the global formatting applied to all the fields the menu contains.
    /// If a field has a custom formatting, it will uses the formatting rules of the field
    /// when printing to the writer.
    pub fn fmt(mut self, fmt: ValueFieldFormatting<'a>) -> Self {
        self.fmt = Rc::new(fmt);
        for field in self.fields.as_mut_slice() {
            field.inherit_fmt(self.fmt.clone());
        }
        self
    }

    /// Give the main title of the menu.
    /// It is printed at the beginning, right before the first field.
    pub fn title(mut self, title: &'a str) -> Self {
        self.title = title;
        self
    }

    #[inline]
    fn next_field(&mut self) -> Field<'a, R, W> {
        self.fields.next().expect("no more field in the value-menu")
    }
}

/// Trait used to return the next output of the menu.
pub trait MenuBuilder<Output, R, W> {
    /// Returns the next output from the menu.
    fn next_output(&mut self) -> MenuResult<Output>;

    /// Returns the next output from the menu using a given menu stream in parameter.
    fn next_output_with(&mut self, stream: &mut MenuStream<R, W>) -> MenuResult<Output>;

    /// Returns the next output from the menu, or its default value if an error occurred.
    fn next_or_default(&mut self) -> Output
    where
        Output: Default,
    {
        self.next_output().unwrap_or_default()
    }

    /// Returns the next output from the menu using a given menu stream in parameter,
    /// or its default value if an error occurred.
    fn next_or_default_with(&mut self, stream: &mut MenuStream<R, W>) -> Output
    where
        Output: Default,
    {
        self.next_output_with(stream).unwrap_or_default()
    }
}

impl<Output, R, W> MenuBuilder<Output, R, W> for ValueMenu<'_, R, W>
where
    Output: FromStr,
    Output::Err: 'static + Debug,
    R: BufRead,
    W: Write,
{
    /// Returns the output of the next field if present.
    ///
    /// ## Panic
    ///
    /// This function panics if there is no more field in the value-menu,
    /// or if an incorrect value type has been used as default.
    fn next_output(&mut self) -> MenuResult<Output> {
        print_title(&mut self.stream, self.title, &mut self.popped)?;
        self.next_field().menu_build(&mut self.stream)
    }

    /// Returns the output of the next field if present using the given menu stream.
    ///
    /// ## Panic
    ///
    /// This function panics if there is no more field in the value-menu,
    /// or if an incorrect value type has been used as default.
    fn next_output_with(&mut self, stream: &mut MenuStream<R, W>) -> MenuResult<Output> {
        print_title(&mut self.stream, self.title, &mut self.popped)?;
        self.next_field().menu_build(stream)
    }

    /// Returns the output of the next field if present or its default type.
    ///
    /// ## Panic
    ///
    /// This function panics if there is no more field in the value-menu,
    /// or if an incorrect value type has been used as default.
    fn next_or_default(&mut self) -> Output
    where
        Output: Default,
    {
        let field = self.next_field();
        next_or_default(&mut self.stream, field, &mut self.popped, self.title)
    }

    /// Returns the output of the next field if present or its default type,
    /// using the given menu stream.
    ///
    /// ## Panic
    ///
    /// This function panics if there is no more field in the value-menu,
    /// or if an incorrect value type has been used as default.
    fn next_or_default_with(&mut self, stream: &mut MenuStream<R, W>) -> Output
    where
        Output: Default,
    {
        let field = self.next_field();
        next_or_default(stream, field, &mut self.popped, self.title)
    }
}

fn next_or_default<Output, R, W>(
    stream: &mut MenuStream<R, W>,
    mut field: Field<'_, R, W>,
    popped: &mut bool,
    title: &str,
) -> Output
where
    Output: FromStr + Default,
    Output::Err: 'static + Debug,
    W: Write,
    R: BufRead,
{
    if print_title(stream, title, popped).is_ok() {
        field.menu_build_or_default(stream)
    } else {
        Output::default()
    }
}

fn print_title<R, W>(
    stream: &mut MenuStream<R, W>,
    title: &str,
    popped: &mut bool,
) -> MenuResult<()>
where
    W: Write,
{
    if !*popped && !title.is_empty() {
        writeln!(stream, "{}", title)?;
        *popped = true;
    }
    Ok(())
}

impl<'a, R, W> GetStream<'a, R, W> for ValueMenu<'a, R, W> {
    /// Returns the menu stream, consuming the menu.
    ///
    /// ## Panic
    ///
    /// If it hasn't been given a menu stream, this method will panic,
    /// because it needs to own its stream to retrieve it at the end.
    #[inline]
    fn get_stream(self) -> MenuStream<'a, R, W> {
        self.stream.retrieve()
    }
}