numbat_wasm_debug/
managed_test_util.rs

1use numbat_wasm::{
2    contract_base::ManagedSerializer,
3    numbat_codec::{test_util::check_top_encode, DecodeError, TopDecode, TopEncode},
4    types::{BoxedBytes, ManagedBuffer},
5};
6
7use crate::TxContext;
8
9use core::fmt::Debug;
10
11/// Uses the managed types api to test encoding.
12/// Can be used on any type, but managed types are especially relevant.
13pub fn check_managed_top_encode<T: TopEncode>(api: TxContext, obj: &T) -> BoxedBytes {
14    let serializer = ManagedSerializer::new(api);
15    let as_mb = serializer.top_encode_to_managed_buffer(obj);
16    let as_bb = serializer.top_encode_to_boxed_bytes(obj);
17    assert_eq!(as_mb.to_boxed_bytes(), as_bb);
18
19    // also check classic encoding
20    let unmanaged_encoded = check_top_encode(obj);
21    assert_eq!(
22        as_mb.to_boxed_bytes().as_slice(),
23        unmanaged_encoded.as_slice()
24    );
25
26    as_bb
27}
28
29/// Uses the managed types api to test encoding.
30/// Can be used on any type, but managed types are especially relevant.
31/// Also works on types that have no un-managed decoding,
32/// by allowing DecodeError::UNSUPPORTED_OPERATION result.
33pub fn check_managed_top_decode<T: TopDecode + PartialEq + Debug>(
34    api: TxContext,
35    bytes: &[u8],
36) -> T {
37    let serializer = ManagedSerializer::new(api.clone());
38    let mb = ManagedBuffer::new_from_bytes(api, bytes);
39    let from_mb: T = serializer.top_decode_from_managed_buffer(&mb);
40    let from_slice: T = serializer.top_decode_from_byte_slice(bytes);
41    assert_eq!(from_mb, from_slice);
42
43    match T::top_decode(bytes) {
44        Ok(from_unmanaged) => {
45            assert_eq!(from_unmanaged, from_mb);
46        },
47        Err(DecodeError::UNSUPPORTED_OPERATION) => {
48            // Ok
49        },
50        Err(err) => {
51            panic!(
52                "Unexpected encoding error:: {}",
53                core::str::from_utf8(err.message_bytes()).unwrap()
54            )
55        },
56    }
57
58    from_mb
59}
60
61/// Uses the managed types api to test encoding both ways.
62pub fn check_managed_top_encode_decode<V>(api: TxContext, element: V, expected_bytes: &[u8])
63where
64    V: TopEncode + TopDecode + PartialEq + Debug + 'static,
65{
66    // serialize
67    let serialized_bytes = check_managed_top_encode(api.clone(), &element);
68    assert_eq!(serialized_bytes.as_slice(), expected_bytes);
69
70    // deserialize
71    let deserialized: V = check_managed_top_decode::<V>(api, serialized_bytes.as_slice());
72    assert_eq!(deserialized, element);
73}