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
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! A sorted, deduplicated list of features from a single package.

use crate::{
    graph::{
        feature::{FeatureId, FeatureLabel},
        PackageMetadata,
    },
    sorted_set::SortedSet,
    PackageId,
};
use std::{fmt, slice, vec};

/// A sorted, deduplicated list of features from a single package.
///
/// This provides a convenient way to query and print out lists of features.
///
/// Returned by methods on `FeatureSet`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FeatureList<'g> {
    package: PackageMetadata<'g>,
    labels: SortedSet<FeatureLabel<'g>>,
}

impl<'g> FeatureList<'g> {
    /// Creates a new `FeatureList` from a package and an iterator over feature labels.
    pub fn new(
        package: PackageMetadata<'g>,
        labels: impl IntoIterator<Item = FeatureLabel<'g>>,
    ) -> Self {
        Self {
            package,
            labels: labels.into_iter().collect(),
        }
    }

    /// Returns the package corresponding to this feature list.
    pub fn package(&self) -> &PackageMetadata<'g> {
        &self.package
    }

    /// Returns true if this feature list contains this feature label.
    pub fn contains(&self, label: FeatureLabel<'_>) -> bool {
        self.labels.contains(&label)
    }

    /// Returns true if this feature list contains the "base" feature.
    ///
    /// The "base" feature represents the package with no features enabled.
    #[inline]
    pub fn has_base(&self) -> bool {
        self.contains(FeatureLabel::Base)
    }

    /// Returns true if this feature list contains the specified named feature.
    #[inline]
    pub fn has_named_feature(&self, feature_name: &str) -> bool {
        self.contains(FeatureLabel::Named(feature_name))
    }

    /// Returns true if this feature list contains the specified optional dependency.
    #[inline]
    pub fn has_optional_dependency(&self, dep_name: &str) -> bool {
        self.contains(FeatureLabel::OptionalDependency(dep_name))
    }

    /// Returns the list of labels as a slice.
    ///
    /// This slice is guaranteed to be sorted and unique.
    pub fn labels(&self) -> &[FeatureLabel<'g>] {
        self.labels.as_slice()
    }

    /// Returns an iterator containing all named features.
    ///
    /// The iterator is guaranteed to be sorted and unique.
    pub fn named_features(&self) -> impl Iterator<Item = &'g str> + '_ {
        // XXX: binary search?
        self.labels.iter().filter_map(|label| match label {
            FeatureLabel::Named(feature_name) => Some(*feature_name),
            _ => None,
        })
    }

    /// Returns an iterator containing all optional dependencies.
    ///
    /// The iterator is guaranteed to be sorted and unique.
    pub fn optional_deps(&self) -> impl Iterator<Item = &'g str> + '_ {
        // XXX: binary search?
        self.labels.iter().filter_map(|label| match label {
            FeatureLabel::OptionalDependency(dep_name) => Some(*dep_name),
            _ => None,
        })
    }

    /// Returns a borrowed iterator over feature IDs.
    pub fn iter<'a>(&'a self) -> Iter<'g, 'a> {
        self.into_iter()
    }

    /// Returns a pretty-printer over the list of feature labels.
    pub fn display_features<'a>(&'a self) -> DisplayFeatures<'g, 'a> {
        DisplayFeatures(self.labels())
    }

    /// Returns a vector of feature labels.
    ///
    /// The vector is guaranteed to be sorted and unique.
    pub fn into_labels(self) -> Vec<FeatureLabel<'g>> {
        self.labels.into_inner().into_vec()
    }
}

impl<'g> IntoIterator for FeatureList<'g> {
    type Item = FeatureId<'g>;
    type IntoIter = IntoIter<'g>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self)
    }
}

impl<'a, 'g> IntoIterator for &'a FeatureList<'g> {
    type Item = FeatureId<'g>;
    type IntoIter = Iter<'g, 'a>;

    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

/// An owned iterator over a `FeatureList`.
pub struct IntoIter<'g> {
    package_id: &'g PackageId,
    iter: vec::IntoIter<FeatureLabel<'g>>,
}

impl<'g> IntoIter<'g> {
    /// Creates a new iterator.
    pub fn new(feature_list: FeatureList<'g>) -> Self {
        Self {
            package_id: feature_list.package.id(),
            iter: feature_list.into_labels().into_iter(),
        }
    }
}

impl<'g> Iterator for IntoIter<'g> {
    type Item = FeatureId<'g>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|label| FeatureId::new(self.package_id, label))
    }
}

/// A borrowed iterator over a `FeatureList`.
pub struct Iter<'g, 'a> {
    package_id: &'g PackageId,
    iter: slice::Iter<'a, FeatureLabel<'g>>,
}

impl<'g, 'a> Iter<'g, 'a> {
    /// Creates a new iterator.
    pub fn new(feature_list: &'a FeatureList<'g>) -> Self {
        Self {
            package_id: feature_list.package.id(),
            iter: feature_list.labels().iter(),
        }
    }
}

impl<'g, 'a> Iterator for Iter<'g, 'a> {
    type Item = FeatureId<'g>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|&label| FeatureId::new(self.package_id, label))
    }
}

/// A pretty-printer for a list of features.
///
/// Returned by `FeatureList::display_filters`.
#[derive(Clone, Copy, Debug)]
pub struct DisplayFeatures<'g, 'a>(&'a [FeatureLabel<'g>]);

impl<'g, 'a> fmt::Display for DisplayFeatures<'g, 'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let len = self.0.len();
        for (idx, label) in self.0.iter().enumerate() {
            write!(f, "{}", label)?;
            if idx < len - 1 {
                write!(f, ", ")?;
            }
        }
        Ok(())
    }
}