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
use alloc::{string::String, vec::Vec};

use crate::{
    api::{EndpointFinishApi, ErrorApi, ManagedTypeApi},
    types::{BoxedBytes, ManagedBuffer, ManagedFrom, ManagedType},
};

use super::SCError;

/// Smart contract error that can concatenate multiple message pieces.
/// The message is kept as a managed buffer in the VM.
pub struct ManagedSCError<M>
where
    M: ManagedTypeApi + ErrorApi,
{
    buffer: ManagedBuffer<M>,
}

impl<M> SCError for ManagedSCError<M>
where
    M: ManagedTypeApi + ErrorApi,
{
    fn finish_err<FA: EndpointFinishApi>(&self, api: FA) -> ! {
        api.signal_error_from_buffer(self.buffer.get_raw_handle())
    }
}

impl<M> ManagedSCError<M>
where
    M: ManagedTypeApi + ErrorApi,
{
    #[inline]
    pub fn new_empty(api: M) -> Self {
        ManagedSCError {
            buffer: ManagedBuffer::new(api),
        }
    }

    #[inline(always)]
    pub fn new_from_bytes(api: M, bytes: &[u8]) -> Self {
        ManagedSCError {
            buffer: ManagedBuffer::new_from_bytes(api, bytes),
        }
    }

    #[inline]
    pub fn append_bytes(&mut self, slice: &[u8]) {
        self.buffer.append_bytes(slice)
    }

    #[inline]
    pub fn exit_now(&self) -> ! {
        self.buffer
            .api
            .signal_error_from_buffer(self.buffer.get_raw_handle())
    }
}

impl<M> ManagedFrom<M, &[u8]> for ManagedSCError<M>
where
    M: ManagedTypeApi,
{
    #[inline]
    fn managed_from(api: M, message: &[u8]) -> Self {
        Self::new_from_bytes(api, message)
    }
}

impl<M> ManagedFrom<M, BoxedBytes> for ManagedSCError<M>
where
    M: ManagedTypeApi,
{
    #[inline]
    fn managed_from(api: M, message: BoxedBytes) -> Self {
        Self::new_from_bytes(api, message.as_slice())
    }
}

impl<M> ManagedFrom<M, &str> for ManagedSCError<M>
where
    M: ManagedTypeApi,
{
    #[inline]
    fn managed_from(api: M, message: &str) -> Self {
        Self::new_from_bytes(api, message.as_bytes())
    }
}

impl<M> ManagedFrom<M, String> for ManagedSCError<M>
where
    M: ManagedTypeApi,
{
    #[inline]
    fn managed_from(api: M, message: String) -> Self {
        Self::new_from_bytes(api, message.as_bytes())
    }
}

impl<M> ManagedFrom<M, Vec<u8>> for ManagedSCError<M>
where
    M: ManagedTypeApi,
{
    #[inline]
    fn managed_from(api: M, message: Vec<u8>) -> Self {
        Self::new_from_bytes(api, message.as_slice())
    }
}

impl<M> From<ManagedBuffer<M>> for ManagedSCError<M>
where
    M: ManagedTypeApi,
{
    #[inline]
    fn from(message: ManagedBuffer<M>) -> Self {
        ManagedSCError { buffer: message }
    }
}