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
//! Definitions for inputs which have multiple distinct subcomponents.
//!
//! Unfortunately, since both [`serde::de::Deserialize`] and [`Clone`] require [`Sized`], it is not
//! possible to dynamically define a single input with dynamic typing. As such, [`MultipartInput`]
//! requires that each subcomponent be the same subtype.

use alloc::{
    string::{String, ToString},
    vec::Vec,
};

use arrayvec::ArrayVec;
use serde::{Deserialize, Serialize};

use crate::inputs::Input;

/// An input composed of multiple parts. Use in situations where subcomponents are not necessarily
/// related, or represent distinct parts of the input.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MultipartInput<I> {
    parts: Vec<I>,
    names: Vec<String>,
}

impl<I> Default for MultipartInput<I> {
    fn default() -> Self {
        Self::new()
    }
}

impl<I> MultipartInput<I> {
    /// Create a new multipart input.
    #[must_use]
    pub fn new() -> Self {
        Self {
            parts: Vec::new(),
            names: Vec::new(),
        }
    }

    fn idxs_to_skips(idxs: &mut [usize]) {
        for following in (1..idxs.len()).rev() {
            let first = idxs[following - 1];
            let second = idxs[following];

            idxs[following] = second
                .checked_sub(first)
                .expect("idxs was not sorted")
                .checked_sub(1)
                .expect("idxs had duplicate elements");
        }
    }

    /// Get the individual parts of this input.
    #[must_use]
    pub fn parts(&self) -> &[I] {
        &self.parts
    }

    /// Access multiple parts mutably.
    ///
    /// ## Panics
    ///
    /// Panics if idxs is not sorted, has duplicate elements, or any entry is out of bounds.
    #[must_use]
    pub fn parts_mut<const N: usize>(&mut self, mut idxs: [usize; N]) -> [&mut I; N] {
        Self::idxs_to_skips(&mut idxs);

        let mut parts = self.parts.iter_mut();
        if let Ok(arr) = idxs
            .into_iter()
            .map(|i| parts.nth(i).expect("idx had an out of bounds entry"))
            .collect::<ArrayVec<_, N>>()
            .into_inner()
        {
            arr
        } else {
            // avoid Debug trait requirement for expect/unwrap
            panic!("arrayvec collection failed somehow")
        }
    }

    /// Get a specific part of this input by index.
    pub fn part_mut(&mut self, idx: usize) -> Option<&mut I> {
        self.parts.get_mut(idx)
    }

    /// Get the names associated with the subparts of this input. Used to distinguish between the
    /// input components in the case where some parts may or may not be present, or in different
    /// orders.
    #[must_use]
    pub fn names(&self) -> &[String] {
        &self.names
    }

    /// Gets a reference to each part with the provided name.
    pub fn parts_by_name<'a, 'b>(
        &'b self,
        name: &'a str,
    ) -> impl Iterator<Item = (usize, &'b I)> + 'a
    where
        'b: 'a,
    {
        self.names()
            .iter()
            .zip(&self.parts)
            .enumerate()
            .filter_map(move |(i, (s, item))| (s == name).then_some((i, item)))
    }

    /// Gets a mutable reference to each part with the provided name.
    pub fn parts_by_name_mut<'a, 'b>(
        &'b mut self,
        name: &'a str,
    ) -> impl Iterator<Item = (usize, &'b mut I)> + 'a
    where
        'b: 'a,
    {
        self.names
            .iter()
            .zip(&mut self.parts)
            .enumerate()
            .filter_map(move |(i, (s, item))| (s == name).then_some((i, item)))
    }

    /// Adds a part to this input, potentially with the same name as an existing part.
    pub fn add_part(&mut self, name: String, part: I) {
        self.parts.push(part);
        self.names.push(name);
    }

    /// Iterate over the parts of this input; no order is specified.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &I)> {
        self.names.iter().map(String::as_ref).zip(self.parts())
    }
}

impl<I, It, S> From<It> for MultipartInput<I>
where
    It: IntoIterator<Item = (S, I)>,
    S: AsRef<str>,
{
    fn from(parts: It) -> Self {
        let mut input = MultipartInput::new();
        for (name, part) in parts {
            input.add_part(name.as_ref().to_string(), part);
        }
        input
    }
}

impl<I> Input for MultipartInput<I>
where
    I: Input,
{
    fn generate_name(&self, idx: usize) -> String {
        self.names
            .iter()
            .cloned()
            .zip(self.parts.iter().map(|i| i.generate_name(idx)))
            .map(|(name, generated)| format!("{name}-{generated}"))
            .collect::<Vec<_>>()
            .join(",")
    }
}