-
Notifications
You must be signed in to change notification settings - Fork 59
/
bcs.rs
85 lines (72 loc) · 2.59 KB
/
bcs.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
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0
use crate::natives::helpers::{make_module_natives, make_native};
use move_binary_format::errors::{PartialVMError, PartialVMResult};
use move_core_types::gas_algebra::InternalGas;
use move_core_types::vm_status::StatusCode;
use move_vm_runtime::native_functions::{NativeContext, NativeFunction};
use move_vm_types::{
loaded_data::runtime_types::Type, natives::function::NativeResult, pop_arg, values::Value,
};
use smallvec::smallvec;
use std::collections::VecDeque;
#[derive(Debug, Clone)]
pub struct FromBytesGasParameters {
pub base: InternalGas,
}
impl FromBytesGasParameters {
pub fn zeros() -> Self {
Self { base: 0.into() }
}
}
/// Rust implementation of Move's `native public(friend) fun from_bytes<T>(vector<u8>): T in bcs module`
/// Bytes are in BCS (Binary Canonical Serialization) format.
#[inline]
fn native_from_bytes(
_gas_params: &FromBytesGasParameters,
context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert_eq!(ty_args.len(), 1);
debug_assert_eq!(args.len(), 1);
let cost = 0.into();
// TODO(Gas): charge for getting the layout
let layout = context.type_to_type_layout(&ty_args[0])?.ok_or_else(|| {
PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR).with_message(format!(
"Failed to get layout of type {:?} -- this should not happen",
ty_args[0]
))
})?;
let bytes = pop_arg!(args, Vec<u8>);
let val = match Value::simple_deserialize(&bytes, &layout) {
Some(val) => val,
None => {
// TODO(gas): charge the gas for the failure.
return Err(PartialVMError::new(StatusCode::VALUE_DESERIALIZATION_ERROR));
}
};
// TODO(gas): charge gas for deserialization
Ok(NativeResult::ok(cost, smallvec![val]))
}
/***************************************************************************************************
* module
**************************************************************************************************/
#[derive(Debug, Clone)]
pub struct GasParameters {
pub from_bytes: FromBytesGasParameters,
}
impl GasParameters {
pub fn zeros() -> Self {
Self {
from_bytes: FromBytesGasParameters::zeros(),
}
}
}
pub fn make_all(gas_params: GasParameters) -> impl Iterator<Item = (String, NativeFunction)> {
let natives = [(
"from_bytes",
make_native(gas_params.from_bytes, native_from_bytes),
)];
make_module_natives(natives)
}