multiversx_sc/contract_base/wrappers/
error_helper.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
use core::{borrow::Borrow, marker::PhantomData};

use crate::codec::{DecodeError, EncodeError};

use crate::{
    api::{ErrorApiImpl, ManagedTypeApi},
    types::{heap::BoxedBytes, ManagedBuffer, ManagedSCError, ManagedType},
};

#[derive(Default)]
pub struct ErrorHelper<M: ManagedTypeApi> {
    _phantom: PhantomData<M>,
}

impl<M: ManagedTypeApi> ErrorHelper<M> {
    pub fn new() -> Self {
        ErrorHelper {
            _phantom: PhantomData,
        }
    }

    pub fn new_error(&self) -> ManagedSCError<M> {
        ManagedSCError::new_empty()
    }

    pub fn signal_error_with_message<T>(message: T) -> !
    where
        T: IntoSignalError<M>,
    {
        message.signal_error_with_message()
    }
}

/// Indicates how an object can be used as the basis for performing `signal_error` with itself as message.
pub trait IntoSignalError<M: ManagedTypeApi> {
    fn signal_error_with_message(self) -> !;
}

impl<M: ManagedTypeApi> IntoSignalError<M> for &str {
    #[inline]
    fn signal_error_with_message(self) -> ! {
        M::error_api_impl().signal_error(self.as_bytes())
    }
}

impl<M: ManagedTypeApi> IntoSignalError<M> for &[u8] {
    #[inline]
    fn signal_error_with_message(self) -> ! {
        M::error_api_impl().signal_error(self)
    }
}

impl<M: ManagedTypeApi> IntoSignalError<M> for BoxedBytes {
    #[inline]
    fn signal_error_with_message(self) -> ! {
        M::error_api_impl().signal_error(self.as_slice())
    }
}

impl<M: ManagedTypeApi> IntoSignalError<M> for EncodeError {
    #[inline]
    fn signal_error_with_message(self) -> ! {
        M::error_api_impl().signal_error(self.message_bytes())
    }
}

impl<M: ManagedTypeApi> IntoSignalError<M> for DecodeError {
    #[inline]
    fn signal_error_with_message(self) -> ! {
        M::error_api_impl().signal_error(self.message_bytes())
    }
}

// Handles `ManagedBuffer`, `&ManagedBuffer` and `ManagedRef<ManagedBuffer>`.
impl<M, B> IntoSignalError<M> for B
where
    M: ManagedTypeApi,
    B: Borrow<ManagedBuffer<M>>,
{
    fn signal_error_with_message(self) -> ! {
        M::error_api_impl().signal_error_from_buffer(self.borrow().get_handle())
    }
}