multiversx_sc/types/managed/wrapped/
managed_vec_item.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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
use core::borrow::Borrow;

use multiversx_chain_core::types::{EsdtLocalRole, EsdtTokenType};
use multiversx_sc_codec::multi_types::{MultiValue2, MultiValue3};

use crate::{
    api::{use_raw_handle, HandleConstraints, ManagedTypeApi},
    types::{
        BigInt, BigUint, EllipticCurve, ManagedAddress, ManagedBuffer, ManagedByteArray,
        ManagedRef, ManagedType, ManagedVec, TokenIdentifier,
    },
};

use super::{
    EgldOrEsdtTokenIdentifier, ManagedVecItemNestedTuple, ManagedVecItemPayload,
    ManagedVecItemPayloadAdd, ManagedVecItemPayloadBuffer, ManagedVecRef,
};

/// Types that implement this trait can be items inside a `ManagedVec`.
/// All these types need a payload, i.e a representation that gets stored
/// in the underlying managed buffer.
/// Not all data needs to be stored as payload, for instance for most managed types
/// the payload is just the handle, whereas the mai ndata is kept by the VM.
pub trait ManagedVecItem: 'static {
    /// Type managing the underlying binary representation in a ManagedVec..
    type PAYLOAD: ManagedVecItemPayload;

    /// If true, then the encoding of the item is identical to the payload,
    /// and no further conversion is necessary
    /// (the underlying buffer can be used as-is during serialization).
    /// False for all managed types, but true for basic types (like `u32`).
    const SKIPS_RESERIALIZATION: bool;

    /// Reference representation of the ManagedVec item.
    ///
    /// Implementations:
    /// - For items with Copy semantics, it should be the type itself.
    /// - For managed types, ManagedRef does the job.
    /// - For any other types, `Self` is currently used, although this is technically unsafe.
    ///
    /// TODO: wrap other types in readonly wrapper.
    type Ref<'a>: Borrow<Self>;

    fn payload_size() -> usize {
        Self::PAYLOAD::payload_size()
    }

    /// Parses given bytes as a an owned object.
    fn read_from_payload(payload: &Self::PAYLOAD) -> Self;

    /// Parses given bytes as a representation of the object, either owned, or a reference.
    ///
    /// # Safety
    ///
    /// In certain cases this involves practically disregarding the lifetimes, hence it is unsafe.
    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a>;

    /// Converts the object into bytes.
    ///
    /// The method is used when instering (push, overwrite) into a ManagedVec.
    ///
    /// Note that a destructor should not be called at this moment, since the ManagedVec will take ownership of the item.
    fn save_to_payload(self, payload: &mut Self::PAYLOAD);
}

/// Used by the ManagedVecItem derive.
///
/// ## Safety
///
/// Only works correctly if the given index is correct, otherwise undefined behavior is possible.
pub unsafe fn managed_vec_item_read_from_payload_index<T, P>(payload: &P, index: &mut usize) -> T
where
    T: ManagedVecItem,
    P: ManagedVecItemPayload,
{
    let value = T::read_from_payload(payload.slice_unchecked(*index));
    *index += T::PAYLOAD::payload_size();
    value
}

/// Used by the ManagedVecItem derive.
///
/// ## Safety
///
/// Only works correctly if the given index is correct, otherwise undefined behavior is possible.
pub unsafe fn managed_vec_item_save_to_payload_index<T, P>(
    item: T,
    payload: &mut P,
    index: &mut usize,
) where
    T: ManagedVecItem,
    P: ManagedVecItemPayload,
{
    item.save_to_payload(payload.slice_unchecked_mut(*index));
    *index += T::PAYLOAD::payload_size();
}

macro_rules! impl_int {
    ($ty:ident, $payload_size:expr) => {
        impl ManagedVecItem for $ty {
            type PAYLOAD = ManagedVecItemPayloadBuffer<$payload_size>;
            const SKIPS_RESERIALIZATION: bool = true;
            type Ref<'a> = Self;

            fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
                $ty::from_be_bytes(payload.buffer)
            }

            unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
                $ty::from_be_bytes(payload.buffer)
            }

            fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
                payload.buffer = self.to_be_bytes();
            }
        }
    };
}
impl_int! {u8, 1}
impl_int! {u16, 2}
impl_int! {u32, 4}
impl_int! {u64, 8}
impl_int! {i32, 4}
impl_int! {i64, 8}

impl ManagedVecItem for usize {
    type PAYLOAD = ManagedVecItemPayloadBuffer<4>;
    const SKIPS_RESERIALIZATION: bool = true;
    type Ref<'a> = Self;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        u32::read_from_payload(payload) as usize
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        Self::read_from_payload(payload)
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        (self as u32).save_to_payload(payload);
    }
}

impl ManagedVecItem for bool {
    type PAYLOAD = ManagedVecItemPayloadBuffer<1>;
    const SKIPS_RESERIALIZATION: bool = true;
    type Ref<'a> = Self;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        u8::read_from_payload(payload) > 0
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        Self::read_from_payload(payload)
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        // true -> 1u8
        // false -> 0u8
        u8::from(self).save_to_payload(payload);
    }
}

impl<T> ManagedVecItem for Option<T>
where
    ManagedVecItemPayloadBuffer<1>: ManagedVecItemPayloadAdd<T::PAYLOAD>,
    T: ManagedVecItem,
{
    type PAYLOAD = <ManagedVecItemPayloadBuffer<1> as ManagedVecItemPayloadAdd<T::PAYLOAD>>::Output;
    const SKIPS_RESERIALIZATION: bool = false;
    type Ref<'a> = ManagedVecRef<'a, Self>;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        let (p1, p2) = <ManagedVecItemPayloadBuffer<1> as ManagedVecItemPayloadAdd<
            T::PAYLOAD,
        >>::split_from_add(payload);

        let disc = u8::read_from_payload(p1);
        if disc == 0 {
            None
        } else {
            Some(T::read_from_payload(p2))
        }
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        ManagedVecRef::new(Self::read_from_payload(payload))
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        let (p1, p2) = <ManagedVecItemPayloadBuffer<1> as ManagedVecItemPayloadAdd<
            T::PAYLOAD,
        >>::split_mut_from_add(payload);

        if let Some(t) = self {
            1u8.save_to_payload(p1);
            t.save_to_payload(p2);
        }
    }
}

macro_rules! impl_managed_type {
    ($ty:ident) => {
        impl<M: ManagedTypeApi> ManagedVecItem for $ty<M> {
            type PAYLOAD = ManagedVecItemPayloadBuffer<4>;
            const SKIPS_RESERIALIZATION: bool = false;
            type Ref<'a> = ManagedRef<'a, M, Self>;

            fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
                let handle = use_raw_handle(i32::read_from_payload(payload));
                unsafe { Self::from_handle(handle) }
            }

            unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
                let handle = use_raw_handle(i32::read_from_payload(payload));
                ManagedRef::wrap_handle(handle)
            }

            fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
                let handle = unsafe { self.forget_into_handle() };
                handle.get_raw_handle().save_to_payload(payload);
            }
        }
    };
}

impl_managed_type! {ManagedBuffer}
impl_managed_type! {BigUint}
impl_managed_type! {BigInt}
impl_managed_type! {EllipticCurve}
impl_managed_type! {ManagedAddress}
impl_managed_type! {TokenIdentifier}
impl_managed_type! {EgldOrEsdtTokenIdentifier}

impl<M, const N: usize> ManagedVecItem for ManagedByteArray<M, N>
where
    M: ManagedTypeApi,
{
    type PAYLOAD = ManagedVecItemPayloadBuffer<4>;
    const SKIPS_RESERIALIZATION: bool = false;
    type Ref<'a> = ManagedRef<'a, M, Self>;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        let handle = use_raw_handle(i32::read_from_payload(payload));
        unsafe { Self::from_handle(handle) }
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        let handle = use_raw_handle(i32::read_from_payload(payload));
        ManagedRef::wrap_handle(handle)
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        let handle = unsafe { self.forget_into_handle() };
        handle.get_raw_handle().save_to_payload(payload);
    }
}

impl<M, T> ManagedVecItem for ManagedVec<M, T>
where
    M: ManagedTypeApi,
    T: ManagedVecItem,
{
    type PAYLOAD = ManagedVecItemPayloadBuffer<4>;
    const SKIPS_RESERIALIZATION: bool = false;
    type Ref<'a> = ManagedRef<'a, M, Self>;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        let handle = use_raw_handle(i32::read_from_payload(payload));
        unsafe { Self::from_handle(handle) }
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        let handle = use_raw_handle(i32::read_from_payload(payload));
        ManagedRef::wrap_handle(handle)
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        let handle = unsafe { self.forget_into_handle() };
        handle.get_raw_handle().save_to_payload(payload);
    }
}

impl ManagedVecItem for EsdtTokenType {
    type PAYLOAD = ManagedVecItemPayloadBuffer<1>;
    const SKIPS_RESERIALIZATION: bool = true;
    type Ref<'a> = Self;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        u8::read_from_payload(payload).into()
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        Self::read_from_payload(payload)
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        self.as_u8().save_to_payload(payload);
    }
}

impl ManagedVecItem for EsdtLocalRole {
    type PAYLOAD = ManagedVecItemPayloadBuffer<2>;
    const SKIPS_RESERIALIZATION: bool = false; // TODO: might be ok to be true, but needs testing
    type Ref<'a> = Self;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        u16::read_from_payload(payload).into()
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        Self::read_from_payload(payload)
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        self.as_u16().save_to_payload(payload);
    }
}

impl<T1, T2> ManagedVecItem for MultiValue2<T1, T2>
where
    T1: ManagedVecItem,
    T2: ManagedVecItem,
    (T1, (T2, ())): ManagedVecItemNestedTuple,
{
    type PAYLOAD = <(T1, (T2, ())) as ManagedVecItemNestedTuple>::PAYLOAD;
    const SKIPS_RESERIALIZATION: bool = T1::SKIPS_RESERIALIZATION && T2::SKIPS_RESERIALIZATION;
    type Ref<'a> = ManagedVecRef<'a, Self>;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        let mut index = 0;
        unsafe {
            (
                managed_vec_item_read_from_payload_index(payload, &mut index),
                managed_vec_item_read_from_payload_index(payload, &mut index),
            )
                .into()
        }
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        ManagedVecRef::new(Self::read_from_payload(payload))
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        let tuple = self.into_tuple();
        let mut index = 0;

        unsafe {
            managed_vec_item_save_to_payload_index(tuple.0, payload, &mut index);
            managed_vec_item_save_to_payload_index(tuple.1, payload, &mut index);
        }
    }
}

impl<T1, T2, T3> ManagedVecItem for MultiValue3<T1, T2, T3>
where
    T1: ManagedVecItem,
    T2: ManagedVecItem,
    T3: ManagedVecItem,
    (T1, (T2, (T3, ()))): ManagedVecItemNestedTuple,
{
    type PAYLOAD = <(T1, (T2, (T3, ()))) as ManagedVecItemNestedTuple>::PAYLOAD;
    const SKIPS_RESERIALIZATION: bool = T1::SKIPS_RESERIALIZATION && T2::SKIPS_RESERIALIZATION;
    type Ref<'a> = ManagedVecRef<'a, Self>;

    fn read_from_payload(payload: &Self::PAYLOAD) -> Self {
        let mut index = 0;
        unsafe {
            (
                managed_vec_item_read_from_payload_index(payload, &mut index),
                managed_vec_item_read_from_payload_index(payload, &mut index),
                managed_vec_item_read_from_payload_index(payload, &mut index),
            )
                .into()
        }
    }

    unsafe fn borrow_from_payload<'a>(payload: &Self::PAYLOAD) -> Self::Ref<'a> {
        ManagedVecRef::new(Self::read_from_payload(payload))
    }

    fn save_to_payload(self, payload: &mut Self::PAYLOAD) {
        let tuple = self.into_tuple();
        let mut index = 0;

        unsafe {
            managed_vec_item_save_to_payload_index(tuple.0, payload, &mut index);
            managed_vec_item_save_to_payload_index(tuple.1, payload, &mut index);
            managed_vec_item_save_to_payload_index(tuple.2, payload, &mut index);
        }
    }
}