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
use crate::natives::helpers::make_module_natives;
use move_binary_format::errors::PartialVMResult;
use move_core_types::{
gas_schedule::GasAlgebra, vm_status::sub_status::NFE_BCS_SERIALIZATION_FAILURE,
};
use move_vm_runtime::native_functions::{NativeContext, NativeFunction};
use move_vm_types::{
loaded_data::runtime_types::Type,
natives::function::NativeResult,
pop_arg,
values::{values_impl::Reference, Value},
};
use smallvec::smallvec;
use std::{collections::VecDeque, sync::Arc};
#[derive(Debug, Clone)]
pub struct ToBytesGasParameters {
pub input_unit_cost: u64,
pub output_unit_cost: u64,
pub legacy_min_output_size: usize,
pub failure_cost: u64,
}
#[inline]
fn native_to_bytes(
gas_params: &ToBytesGasParameters,
context: &mut NativeContext,
mut ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert!(ty_args.len() == 1);
debug_assert!(args.len() == 1);
let mut cost = 0;
let ref_to_val = pop_arg!(args, Reference);
let arg_type = ty_args.pop().unwrap();
if gas_params.input_unit_cost != 0 {
cost += gas_params.input_unit_cost * arg_type.size().get()
}
let layout = match context.type_to_type_layout(&arg_type)? {
Some(layout) => layout,
None => {
cost += gas_params.failure_cost;
return Ok(NativeResult::err(cost, NFE_BCS_SERIALIZATION_FAILURE));
}
};
let val = ref_to_val.read_ref()?;
if gas_params.input_unit_cost != 0 {
cost += gas_params.input_unit_cost * val.size().get()
}
let serialized_value = match val.simple_serialize(&layout) {
Some(serialized_value) => serialized_value,
None => {
cost += gas_params.failure_cost;
return Ok(NativeResult::err(cost, NFE_BCS_SERIALIZATION_FAILURE));
}
};
cost += gas_params.output_unit_cost
* usize::max(serialized_value.len(), gas_params.legacy_min_output_size) as u64;
Ok(NativeResult::ok(
cost,
smallvec![Value::vector_u8(serialized_value)],
))
}
pub fn make_native_to_bytes(gas_params: ToBytesGasParameters) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_to_bytes(&gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct GasParameters {
pub to_bytes: ToBytesGasParameters,
}
pub fn make_all(gas_params: GasParameters) -> impl Iterator<Item = (String, NativeFunction)> {
let natives = [("to_bytes", make_native_to_bytes(gas_params.to_bytes))];
make_module_natives(natives)
}