brownstone/
builder.rs

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
/*!
A low level builder type for creating fixed size arrays. See [`ArrayBuilder`]
for details.
*/

use core::fmt::{self, Debug, Formatter};

use arrayvec::ArrayVec;

/**
Error type returned from [`ArrayBuilder::try_push`], indicating that the
builder was already full. Includes the value that couldn't be pushed to the
array.
*/
#[derive(Debug, Clone, Copy)]
pub struct Overflow<T>(pub T);

/**
Result type returned from [`ArrayBuilder::push`], indicating whether the
array is full after the push. `ArrayBuilder::push` panics on overflow, so this
only indicates if there is room to push additional elements.
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushResult {
    NotFull,
    Full,
}

/**
Low-level builder type for `[T; N]` arrays. Uses a
[`push`][ArrayBuilder::push] + [`finish`][ArrayBuilder::finish] interface to
build an array 1 element at a time.

The interface provided by this type is fairly low level; most of its methods
are fallible in some way (returning a [`Result`] or panicking on errors).
Consider instead the misuse-resistant
[`move_builder::ArrayBuilder`][crate::move_builder::ArrayBuilder], which uses
ownership semantics to provide only infallible operations, or the
[`build!`][crate::build] macro at the top level of the crate.
*/
#[derive(Clone)]
pub struct ArrayBuilder<T, const N: usize> {
    vec: ArrayVec<T, N>,
}

impl<T, const N: usize> ArrayBuilder<T, N> {
    /**
    Create a new, empty `ArrayBuilder`.
    */
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self {
            vec: ArrayVec::new_const(),
        }
    }

    /**
    Returns true if every element in the array is initialized. If the
    builder is full, the next call to `finish` will return the built array.
    */
    #[inline]
    #[must_use]
    pub fn is_full(&self) -> bool {
        self.vec.is_full()
    }

    /**
    Returns true if no elements in the array are initialized.
    */
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.vec.is_empty()
    }

    /**
    Returns the number of initialized elements in the array.
    */
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    /**
    Get a PushResult after a push. Indicates if the array is full or not.
    */
    #[inline]
    #[must_use]
    fn push_result(&self) -> PushResult {
        match self.len() >= N {
            true => PushResult::Full,
            false => PushResult::NotFull,
        }
    }

    /// Add an initialized element to the array, without performing a bounds
    /// check.
    ///
    /// # Safety
    ///
    /// This must only be called when the builder is not full.
    #[inline]
    pub unsafe fn push_unchecked(&mut self, value: T) -> PushResult {
        debug_assert!(self.vec.len() < N);

        // Safety: the caller has ensured that the array isn't full yet.
        self.vec.push_unchecked(value);
        self.push_result()
    }

    /**
    Try to add an initialized element to the array. Returns an error if the
    array is already full, or a [`PushResult`] indicating if the array is now full
    and can be retrieved via [`finish`][Self::finish].
    */
    #[inline]
    pub fn try_push(&mut self, value: T) -> Result<PushResult, Overflow<T>> {
        // We could avoid the unsafe and use try_push, but we'd prefer to
        // contain the logic as much as possible
        match self.vec.is_full() {
            false => Ok(unsafe { self.push_unchecked(value) }),
            true => Err(Overflow(value)),
        }
    }

    /**
    Add an initialized element to the array. Returns a [`PushResult`]
    indicating if the array is now full and can be retrieved via
    [`finish`][Self::finish].

    # Panics

    Panics if the array is already full.
    */
    #[inline]
    pub fn push(&mut self, value: T) -> PushResult {
        match self.try_push(value) {
            Ok(result) => result,
            Err(..) => panic!("ArrayBuilder::push overflow"),
        }
    }

    /// Return the fully initialized array without checking that it's fully
    /// initialized.
    ///
    /// # Safety
    ///
    /// This must only be called when the builder is full.
    #[inline]
    pub unsafe fn finish_unchecked(self) -> [T; N] {
        debug_assert!(self.is_full());
        self.vec.into_inner_unchecked()
    }

    /**
    Try to return the fully initialized array. Returns the builder if the
    array isn't fully initialized yet.
    */
    #[inline]
    pub fn try_finish(self) -> Result<[T; N], Self> {
        match self.is_full() {
            true => Ok(unsafe { self.finish_unchecked() }),
            false => Err(self),
        }
    }

    /**
    Return the fully initialized array.

    # Panics

    Panics if the array isn't fully initialized yet.
    */
    #[inline]
    pub fn finish(self) -> [T; N] {
        match self.try_finish() {
            Ok(array) => array,
            Err(..) => panic!("ArrayBuilder::finish incomplete"),
        }
    }

    /**
    Get the slice of the array that has already been initialized.
    */
    #[inline]
    #[must_use]
    pub fn finished_slice(&self) -> &[T] {
        self.vec.as_slice()
    }

    /**
    Get the mutable slice of the array that has already been initialized.
    */
    #[inline]
    #[must_use]
    pub fn finished_slice_mut(&mut self) -> &mut [T] {
        self.vec.as_mut_slice()
    }
}

impl<T, const N: usize> Default for ArrayBuilder<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Debug, const N: usize> Debug for ArrayBuilder<T, N> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("ArrayBuilder")
            .field("array", &self.finished_slice())
            .field("progress", &format_args!("{} / {}", self.len(), N))
            .finish()
    }
}

impl<T, const N: usize> Extend<T> for ArrayBuilder<T, N> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        iter.into_iter().for_each(|item| {
            self.push(item);
        })
    }

    // TODO: extend_one, when it's stable
}