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
//! This module supplies the API that the CNI specification recommends.
//!
//! The function names are provided with the Rust naming convention.

use std::cell::RefCell;
use std::collections::BTreeSet;
use std::iter::FromIterator;

/// Provides the recommended API functions:
/// * [`SubTree`] and [`SubLeaves`]
///     * `ListTree` and `ListLeaves` by using e.g. [`HashMap::values`] on this
///     * `KeyTree` and `KeyLeaves` by using e.g. [`HashMap::keys`] on this
/// * [`WalkTree`] and [`WalkLeaves`]
/// * [`SectionTree`] and [`SectionLeaves`]
///
/// You can use the blanket implementations for this trait by importing it.
///
/// [`SubTree`]: CniExt::sub_tree
/// [`SubLeaves`]: CniExt::sub_leaves
/// [`WalkTree`]: CniExt::walk_tree
/// [`WalkLeaves`]: CniExt::walk_leaves
/// [`SectionTree`]: CniExt::section_tree
/// [`SectionLeaves`]: CniExt::section_leaves
/// [`HashMap::values`]: ::std::collections::HashMap::values
/// [`HashMap::keys`]: ::std::collections::HashMap::keys
pub trait CniExt<V>: Sized {
    /// The type of the underlying iterator produced by some functions.
    type Iter;
    /// Returns a clone of self that only contains child elements of the
    /// specified section. The section name and delimiter will be removed in
    /// the result.
    ///
    /// The CNI specification calls this `SubTree`.
    ///
    /// Use e.g. [`HashMap::values`] to get `ListTree`.
    /// Use e.g. [`HashMap::keys`] to get `KeyTree`.
    ///
    /// # Examples
    /// ```ignore <https://github.com/rust-lang/rust/issues/67295>
    /// use std::collections::HashMap;
    /// use cni_format::CniExt;
    ///
    /// let cni = r"
    /// [section]
    /// key = value
    /// subsection.key = other value
    /// [otherSection]
    /// key = value
    /// ";
    ///
    /// let parsed = cni_format::from_str(&cni).expect("could not parse CNI");
    ///
    /// let mut result = HashMap::new();
    /// result.insert("key".to_string(), "value".to_string());
    /// result.insert("subsection.key".to_string(), "other value".to_string());
    ///
    /// assert_eq!(parsed.sub_tree("section"), result);
    /// ```
    ///
    /// [`HashMap::values`]: ::std::collections::HashMap::values
    /// [`HashMap::keys`]: ::std::collections::HashMap::keys
    fn sub_tree(&self, section: &str) -> Self
    where
        Self: Clone + FromIterator<(String, V)>;
    /// Returns a clone of self that only contains direct child elements of the
    /// specified section. The section name and delimiter will be removed in
    /// the result.
    ///
    /// The CNI specification calls this `SubLeaves`.
    /// Use e.g. [`HashMap::values`] to get `ListLeaves`.
    /// Use e.g. [`HashMap::keys`] to get `KeyLeaves`.
    ///
    /// # Examples
    /// ```ignore <https://github.com/rust-lang/rust/issues/67295>
    /// use std::collections::HashMap;
    /// use cni_format::CniExt;
    ///
    /// let cni = r"
    /// [section]
    /// key = value
    /// subsection.key = other value
    /// [otherSection]
    /// key = value
    /// ";
    ///
    /// let parsed = cni_format::from_str(&cni).expect("could not parse CNI");
    ///
    /// let mut result = HashMap::new();
    /// result.insert("key".to_string(), "value".to_string());
    ///
    /// assert_eq!(parsed.sub_leaves("section"), result);
    /// ```
    ///
    /// [`HashMap::values`]: ::std::collections::HashMap::values
    /// [`HashMap::keys`]: ::std::collections::HashMap::keys
    fn sub_leaves(&self, section: &str) -> Self
    where
        Self: Clone + FromIterator<(String, V)>;
    /// Returns an iterator that only contains child elements of the
    /// specified section. The section name and delimiter will be included in
    /// the result. The order is unspecified.
    ///
    /// The CNI specification calls this `WalkTree`.
    ///
    /// # Examples
    /// ```ignore <https://github.com/rust-lang/rust/issues/67295>
    /// use std::collections::HashMap;
    /// use cni_format::CniExt;
    ///
    /// let cni = r"
    /// [section]
    /// key = value
    /// subsection.key = other value
    /// [otherSection]
    /// key = value
    /// ";
    ///
    /// let mut parsed = cni_format::from_str(&cni)
    ///     .expect("could not parse CNI")
    ///     .iter()
    ///     .walk_tree("section")
    ///     // have to clone here because we want to store the result
    ///     .map(|(k, v)| (k.clone(), v.clone()))
    ///     .collect::<Vec<_>>();
    /// // because the order is unspecified, have to sort to compare
    /// parsed.sort();
    ///
    /// assert_eq!(
    ///     parsed,
    ///     vec![
    ///         ("section.key".to_string(), "value".to_string()),
    ///         ("section.subsection.key".to_string(), "other value".to_string()),
    ///     ]
    /// );
    /// ```
    fn walk_tree(self, section: &str) -> SectionFilter<Self::Iter>;
    /// Returns an iterator that only contains direct child elements of the
    /// specified section. The section name and delimiter will be included in
    /// the result. The order is unspecified.
    ///
    /// The CNI specification calls this `WalkLeaves`.
    ///
    /// # Examples
    /// ```ignore <https://github.com/rust-lang/rust/issues/67295>
    /// use std::collections::HashMap;
    /// use cni_format::CniExt;
    ///
    /// let cni = r"
    /// [section]
    /// key = value
    /// subsection.key = other value
    /// [otherSection]
    /// key = value
    /// ";
    ///
    /// let mut parsed = cni_format::from_str(&cni)
    ///     .expect("could not parse CNI")
    ///     .iter()
    ///     .walk_leaves("section")
    ///     // have to clone here because we want to store the result
    ///     .map(|(k, v)| (k.clone(), v.clone()))
    ///     .collect::<Vec<_>>();
    /// // because the order is unspecified, have to sort to compare
    /// parsed.sort();
    ///
    /// assert_eq!(
    ///     parsed,
    ///     vec![
    ///         ("section.key".to_string(), "value".to_string()),
    ///     ]
    /// );
    /// ```
    fn walk_leaves(self, section: &str) -> SectionFilter<Self::Iter>;
    /// Returns the names of subsection of the specified section. Note that
    /// this does not necessarily mean that the respective section names are in
    /// the source as section headers.
    ///
    /// The CNI specification calls this `SectionTree`.
    ///
    /// # Examples
    /// ```ignore <https://github.com/rust-lang/rust/issues/67295>
    /// use std::collections::HashMap;
    /// use cni_format::CniExt;
    ///
    /// let cni = r"
    /// [section]
    /// key = value
    /// subsection.key = other value
    /// [otherSection]
    /// key = value
    /// ";
    ///
    /// let mut sections = cni_format::from_str(&cni)
    ///     .expect("could not parse CNI")
    ///     .iter()
    ///     .section_tree("section");
    ///
    /// assert_eq!(
    ///     sections.into_iter().collect::<Vec<_>>(),
    ///     vec![
    ///         "subsection".to_string(),
    ///     ]
    /// );
    /// ```
    fn section_tree(&self, section: &str) -> BTreeSet<String>
    where
        Self: Clone;
    /// Returns the names of direct subsections of the specified section. Note
    /// that this does not necessarily mean that the respective section names
    /// are in the source as section headers.
    ///
    /// The CNI specification calls this `SectionTree`.
    ///
    /// # Examples
    /// ```ignore <https://github.com/rust-lang/rust/issues/67295>
    /// use std::collections::HashMap;
    /// use cni_format::CniExt;
    ///
    /// let cni = r"
    /// [section]
    /// key = value
    /// subsection.key = other value
    /// [otherSection]
    /// key = value
    /// ";
    ///
    /// let mut sections = cni_format::from_str(&cni)
    ///     .expect("could not parse CNI")
    ///     .iter()
    ///     // get direct subsections of top level section
    ///     .section_leaves("");
    ///
    /// assert_eq!(
    ///     sections.into_iter().collect::<Vec<_>>(),
    ///     vec![
    ///         "otherSection".to_string(), "section".to_string(),
    ///     ]
    /// );
    /// ```
    fn section_leaves(&self, section: &str) -> BTreeSet<String>
    where
        Self: Clone;
}

impl<T, I, K, V> CniExt<V> for T
where
    T: IntoIterator<IntoIter = I>,
    I: Iterator<Item = (K, V)>,
    K: AsRef<str>,
{
    type Iter = I;

    /// Implements the `SubTree` API function.
    fn sub_tree(&self, section: &str) -> Self
    where
        Self: Clone + FromIterator<(String, V)>,
    {
        self.clone()
            .into_iter()
            .filter_map(|(k, v)| {
                let k = k.as_ref();
                if section.is_empty() {
                    Some((k.to_string(), v))
                } else if k.starts_with(section) && k[section.len()..].starts_with('.') {
                    Some((k[section.len() + 1..].to_string(), v))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Implements the `SubLeaves` API function.
    fn sub_leaves(&self, section: &str) -> Self
    where
        Self: Clone + FromIterator<(String, V)>,
    {
        self.clone()
            .into_iter()
            .filter_map(|(k, v)| {
                let k = k.as_ref();
                if section.is_empty() && !k.contains('.') {
                    Some((k.to_string(), v))
                } else if k.starts_with(section)
                    && k[section.len()..].starts_with('.')
                    && !k[section.len() + 1..].contains('.')
                {
                    Some((k[section.len() + 1..].to_string(), v))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Implements the `WalkTree` API function.
    fn walk_tree(self, section: &str) -> SectionFilter<I> {
        SectionFilter {
            iter: RefCell::new(self.into_iter()),
            section,
            only_direct_children: false,
        }
    }

    /// Implements the `WalkLeaves` API function.
    fn walk_leaves(self, section: &str) -> SectionFilter<I> {
        SectionFilter {
            iter: RefCell::new(self.into_iter()),
            section,
            only_direct_children: true,
        }
    }

    /// Implements the `SectionTree` API function.
    fn section_tree(&self, section: &str) -> BTreeSet<String>
    where
        T: Clone,
    {
        // TODO: `keys` could be simplified if nightly feature map_first_last is
        // stabilized, see <https://github.com/rust-lang/rust/issues/62924>
        let mut keys = vec![];
        let mut result = BTreeSet::new();
        keys.extend(
            self.clone()
                .walk_tree(section)
                // ignore current section's name
                .map(|(k, _)| {
                    if section.is_empty() {
                        k.as_ref().to_string()
                    } else {
                        k.as_ref()[section.len() + 1..].to_string()
                    }
                }),
        );

        while let Some(key) = keys.pop() {
            if let Some(pos) = key.rfind('.') {
                let section = key.split_at(pos).0.to_string();
                if !keys.contains(&section) && !result.contains(&section) {
                    keys.push(section.clone());
                }
                result.insert(section.to_string());
            }
        }

        result
    }

    fn section_leaves(&self, section: &str) -> BTreeSet<String>
    where
        T: Clone,
    {
        // TODO: `keys` could be simplified if nightly feature map_first_last is
        // stabilized, see <https://github.com/rust-lang/rust/issues/62924>
        let mut keys = vec![];
        let mut result = BTreeSet::new();
        keys.extend(
            self.clone()
                .walk_tree(section)
                // ignore current section's name
                .map(|(k, _)| {
                    if section.is_empty() {
                        k.as_ref().to_string()
                    } else {
                        k.as_ref()[section.len() + 1..].to_string()
                    }
                }),
        );

        while let Some(key) = keys.pop() {
            if let Some(pos) = key.rfind('.') {
                let section = key.split_at(pos).0.to_string();
                if section.contains('.') {
                    continue;
                }
                if !keys.contains(&section) && !result.contains(&section) {
                    keys.push(section.clone());
                }
                result.insert(section.to_string());
            }
        }

        result
    }
}

/// An iterator that filters the elements of a key-value iterator for keys in
/// a specific section.
///
/// This `struct` is created by the [`walk_tree`]  and [`walk_leaves`]
/// methods on [`CniExt`]. See its documentation for more.
///
/// [`walk_tree`]: CniExt::walk_tree
/// [`walk_leaves`]: CniExt::walk_leaves
pub struct SectionFilter<'section, I> {
    // this has to use interior mutability because of how `next` has to be done
    iter: RefCell<I>,
    section: &'section str,
    only_direct_children: bool,
}

impl<I, K, V> Iterator for SectionFilter<'_, I>
where
    I: Iterator<Item = (K, V)>,
    K: AsRef<str>,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.borrow_mut().find(|(k, _)| {
            // using self inside closure requires interior mutability on iter
            let k = k.as_ref();
            k.starts_with(self.section)
                && (k[self.section.len()..].starts_with('.') || self.section.is_empty())
                && !(self.only_direct_children && k[self.section.len() + 1..].contains('.'))
        })
    }
}