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
use core::marker::PhantomData;

use alloc::vec::Vec;

use crate::{
    api::{ErrorApi, ErrorApiImpl, ManagedTypeApi},
    err_msg,
    types::{BoxedBytes, ManagedBytesTopDecodeInput},
    DynArgInput,
};

/// Consumes a vector of `BoxedBytes` and deserializes from the vector one by one.
pub struct BytesArgLoader<A>
where
    A: ManagedTypeApi,
{
    bytes_vec: Vec<BoxedBytes>,
    next_index: usize,
    _phantom: PhantomData<A>,
}

impl<A> BytesArgLoader<A>
where
    A: ManagedTypeApi,
{
    pub fn new(bytes_vec: Vec<BoxedBytes>) -> Self {
        BytesArgLoader {
            bytes_vec,
            next_index: 0,
            _phantom: PhantomData,
        }
    }
}

impl<A> DynArgInput for BytesArgLoader<A>
where
    A: ManagedTypeApi + ErrorApi,
{
    type ItemInput = ManagedBytesTopDecodeInput<A>;

    type ManagedTypeErrorApi = A;

    #[inline]
    fn has_next(&self) -> bool {
        self.next_index < self.bytes_vec.len()
    }

    fn next_arg_input(&mut self) -> ManagedBytesTopDecodeInput<A> {
        if !self.has_next() {
            A::error_api_impl().signal_error(err_msg::ARG_WRONG_NUMBER);
        }

        // consume from the vector, get owned bytes
        // no clone
        // no vector resize
        let boxed_bytes =
            core::mem::replace(&mut self.bytes_vec[self.next_index], BoxedBytes::empty());
        self.next_index += 1;
        ManagedBytesTopDecodeInput::new(boxed_bytes)
    }
}