wasmlib/wasmtypes/
scint32.rs

1// Copyright 2020 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use std::convert::TryInto;
5
6use crate::*;
7
8// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\
9
10pub const SC_INT32_LENGTH: usize = 4;
11
12// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\
13
14pub fn int32_decode(dec: &mut WasmDecoder) -> i32 {
15    dec.vli_decode(32) as i32
16}
17
18pub fn int32_encode(enc: &mut WasmEncoder, value: i32) {
19    enc.vli_encode(value as i64);
20}
21
22pub fn int32_from_bytes(buf: &[u8]) -> i32 {
23    if buf.len() == 0 {
24        return 0;
25    }
26    if buf.len() != SC_INT32_LENGTH {
27        panic("invalid Int32 length");
28    }
29    i32::from_le_bytes(buf.try_into().expect("WTF?"))
30}
31
32pub fn int32_to_bytes(value: i32) -> Vec<u8> {
33    value.to_le_bytes().to_vec()
34}
35
36pub fn int32_from_string(value: &str) -> i32 {
37    value.parse::<i32>().unwrap()
38}
39
40pub fn int32_to_string(value: i32) -> String {
41    value.to_string()
42}
43
44// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\
45
46pub struct ScImmutableInt32 {
47    proxy: Proxy,
48}
49
50impl ScImmutableInt32 {
51    pub fn new(proxy: Proxy) -> ScImmutableInt32 {
52        ScImmutableInt32 { proxy }
53    }
54
55    pub fn exists(&self) -> bool {
56        self.proxy.exists()
57    }
58
59    pub fn to_string(&self) -> String {
60        int32_to_string(self.value())
61    }
62
63    pub fn value(&self) -> i32 {
64        int32_from_bytes(&self.proxy.get())
65    }
66}
67
68// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\
69
70// value proxy for mutable i32 in host container
71pub struct ScMutableInt32 {
72    proxy: Proxy,
73}
74
75impl ScMutableInt32 {
76    pub fn new(proxy: Proxy) -> ScMutableInt32 {
77        ScMutableInt32 { proxy }
78    }
79
80    pub fn delete(&self) {
81        self.proxy.delete();
82    }
83
84    pub fn exists(&self) -> bool {
85        self.proxy.exists()
86    }
87
88    pub fn set_value(&self, value: i32) {
89        self.proxy.set(&int32_to_bytes(value));
90    }
91
92    pub fn to_string(&self) -> String {
93        int32_to_string(self.value())
94    }
95
96    pub fn value(&self) -> i32 {
97        int32_from_bytes(&self.proxy.get())
98    }
99}