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
use alloc::format;

use crate::{
    abi::{TypeAbi, TypeAbiFrom, TypeDescriptionContainer, TypeName},
    api::{ErrorApi, ErrorApiImpl},
    codec::{self, arrayvec::ArrayVec, NestedDecode, NestedEncode, TopDecode, TopEncode},
};
use core::marker::PhantomData;

const EMPTY_ENTRY: usize = 0;
static INVALID_INDEX_ERR_MSG: &[u8] = b"Index out of bounds";

/// A special type of array that initially holds the values from 0 to N
/// If array[i] == i, then the default value (0) is stored instead
#[derive(Clone)]
pub struct SparseArray<E, const CAPACITY: usize>
where
    E: ErrorApi,
{
    array: [usize; CAPACITY],
    len: usize,
    _phantom: PhantomData<E>,
}

impl<E, const CAPACITY: usize> SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    /// initializes a sparse array that holds the values from range [0, len)
    pub fn new(len: usize) -> Self {
        if len > CAPACITY {
            E::error_api_impl().signal_error(b"Length exceeds capacity");
        }

        SparseArray {
            array: [0usize; CAPACITY],
            len,
            _phantom: PhantomData,
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the underlying array as a slice, without converting 0-values to their actual value
    #[inline]
    pub fn as_raw_slice(&self) -> &[usize] {
        &self.array[..self.len]
    }

    /// Gets the value at the given `index`.
    /// If the value is 0, then `index` is returned.
    pub fn get(&self, index: usize) -> usize {
        self.require_valid_index(index);
        self.get_item_unchecked(index)
    }

    /// Sets the value at the given `index`.
    /// If the `index` and `value` are equal, then `0` is stored.
    pub fn set(&mut self, index: usize, value: usize) {
        self.require_valid_index(index);
        self.set_item_unchecked(index, value);
    }

    /// Removes the value at the given index.
    /// The value at `index` is set to the last item in the array
    /// and length is decremented
    pub fn swap_remove(&mut self, index: usize) -> usize {
        self.require_valid_index(index);

        let last_item_index = self.len - 1;
        let last_item = self.get_item_unchecked(last_item_index);

        let current_item = if index != last_item_index {
            let item_at_index = self.get_item_unchecked(index);
            self.set_item_unchecked(index, last_item);

            item_at_index
        } else {
            last_item
        };

        self.set_item_unchecked(last_item_index, EMPTY_ENTRY);
        self.len -= 1;

        current_item
    }

    fn get_item_unchecked(&self, index: usize) -> usize {
        let value = self.array[index];
        if value == EMPTY_ENTRY {
            index
        } else {
            value
        }
    }

    fn set_item_unchecked(&mut self, index: usize, value: usize) {
        if index == value {
            self.array[index] = EMPTY_ENTRY;
        } else {
            self.array[index] = value;
        }
    }

    fn require_valid_index(&self, index: usize) {
        if index >= self.len {
            E::error_api_impl().signal_error(INVALID_INDEX_ERR_MSG);
        }
    }

    pub fn iter(&self) -> SparseArrayIterator<E, CAPACITY> {
        SparseArrayIterator::new(self)
    }
}

impl<'a, E, const CAPACITY: usize> IntoIterator for &'a SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    type Item = usize;

    type IntoIter = SparseArrayIterator<'a, E, CAPACITY>;

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

pub struct SparseArrayIterator<'a, E, const CAPACITY: usize>
where
    E: ErrorApi,
{
    array_ref: &'a SparseArray<E, CAPACITY>,
    current_index: usize,
    last_index: usize,
}

impl<'a, E, const CAPACITY: usize> SparseArrayIterator<'a, E, CAPACITY>
where
    E: ErrorApi,
{
    pub fn new(array: &'a SparseArray<E, CAPACITY>) -> Self {
        Self {
            array_ref: array,
            current_index: 0,
            last_index: array.len - 1,
        }
    }
}

impl<'a, E, const CAPACITY: usize> Iterator for SparseArrayIterator<'a, E, CAPACITY>
where
    E: ErrorApi,
{
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        let next_index = self.current_index;
        if next_index > self.last_index {
            return None;
        }

        self.current_index += 1;

        Some(self.array_ref.get(next_index))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.last_index - self.current_index + 1;
        (remaining, Some(remaining))
    }
}

impl<'a, E, const CAPACITY: usize> ExactSizeIterator for SparseArrayIterator<'a, E, CAPACITY> where
    E: ErrorApi
{
}

impl<'a, E, const CAPACITY: usize> DoubleEndedIterator for SparseArrayIterator<'a, E, CAPACITY>
where
    E: ErrorApi,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        let next_index = self.last_index;
        if next_index < self.current_index {
            return None;
        }

        self.last_index -= 1;

        Some(self.array_ref.get(next_index))
    }
}

impl<'a, E, const CAPACITY: usize> Clone for SparseArrayIterator<'a, E, CAPACITY>
where
    E: ErrorApi,
{
    fn clone(&self) -> Self {
        Self {
            array_ref: self.array_ref,
            current_index: self.current_index,
            last_index: self.last_index,
        }
    }
}

impl<E, const CAPACITY: usize> TopEncode for SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    fn top_encode_or_handle_err<O, H>(&self, output: O, h: H) -> Result<(), H::HandledErr>
    where
        O: codec::TopEncodeOutput,
        H: codec::EncodeErrorHandler,
    {
        let mut nested_buffer = output.start_nested_encode();
        for item in self.iter() {
            item.dep_encode_or_handle_err(&mut nested_buffer, h)?;
        }
        output.finalize_nested_encode(nested_buffer);

        Ok(())
    }
}

impl<E, const CAPACITY: usize> NestedEncode for SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    fn dep_encode_or_handle_err<O, H>(&self, dest: &mut O, h: H) -> Result<(), H::HandledErr>
    where
        O: codec::NestedEncodeOutput,
        H: codec::EncodeErrorHandler,
    {
        self.len.dep_encode_or_handle_err(dest, h)?;
        for item in self.iter() {
            item.dep_encode_or_handle_err(dest, h)?;
        }

        Ok(())
    }
}

impl<E, const CAPACITY: usize> TopDecode for SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    fn top_decode_or_handle_err<I, H>(input: I, h: H) -> Result<Self, H::HandledErr>
    where
        I: codec::TopDecodeInput,
        H: codec::DecodeErrorHandler,
    {
        match ArrayVec::<usize, CAPACITY>::top_decode(input) {
            Ok(array_vec) => {
                let len = array_vec.len();
                let mut array = [0usize; CAPACITY];
                let array_slice = &mut array[..len];
                array_slice.copy_from_slice(array_vec.as_slice());

                Ok(Self {
                    array,
                    len: array_vec.len(),
                    _phantom: PhantomData,
                })
            },
            Err(e) => Err(h.handle_error(e)),
        }
    }
}

impl<E, const CAPACITY: usize> NestedDecode for SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    fn dep_decode_or_handle_err<I, H>(input: &mut I, h: H) -> Result<Self, H::HandledErr>
    where
        I: codec::NestedDecodeInput,
        H: codec::DecodeErrorHandler,
    {
        match ArrayVec::<usize, CAPACITY>::dep_decode(input) {
            Ok(array_vec) => {
                let len = array_vec.len();
                let mut array = [0usize; CAPACITY];
                let array_slice = &mut array[..len];
                array_slice.copy_from_slice(array_vec.as_slice());

                Ok(Self {
                    array,
                    len: array_vec.len(),
                    _phantom: PhantomData,
                })
            },
            Err(e) => Err(h.handle_error(e)),
        }
    }
}

impl<E, const CAPACITY: usize> TypeAbiFrom<Self> for SparseArray<E, CAPACITY> where E: ErrorApi {}
impl<E, const CAPACITY: usize> TypeAbiFrom<&Self> for SparseArray<E, CAPACITY> where E: ErrorApi {}

impl<E, const CAPACITY: usize> TypeAbi for SparseArray<E, CAPACITY>
where
    E: ErrorApi,
{
    type Unmanaged = Self;

    /// It is semantically equivalent to any list of `usize`.
    fn type_name() -> TypeName {
        <&[usize] as TypeAbi>::type_name()
    }

    fn type_name_rust() -> TypeName {
        format!("SparseArray<$API, {CAPACITY}usize>")
    }

    fn provide_type_descriptions<TDC: TypeDescriptionContainer>(accumulator: &mut TDC) {
        usize::provide_type_descriptions(accumulator);
    }
}