1use wasm_bindgen::prelude::{wasm_bindgen, JsValue};
2
3use cml_core::serialization::{Deserialize, Serialize};
4
5pub use cml_core::serialization::RawBytesEncoding;
7
8#[macro_use]
9pub mod wasm_wrappers;
10
11#[wasm_bindgen]
12#[derive(Clone, Debug)]
13pub struct Int(cml_core::Int);
14
15#[wasm_bindgen]
16
17impl Int {
18 pub fn to_cbor_bytes(&self) -> Vec<u8> {
19 Serialize::to_cbor_bytes(&self.0)
20 }
21
22 pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result<Int, JsValue> {
23 Deserialize::from_cbor_bytes(cbor_bytes)
24 .map(Self)
25 .map_err(|e| JsValue::from_str(&format!("from_bytes: {e}")))
26 }
27
28 pub fn to_json(&self) -> Result<String, JsValue> {
29 serde_json::to_string_pretty(&self.0)
30 .map_err(|e| JsValue::from_str(&format!("to_json: {e}")))
31 }
32
33 pub fn to_json_value(&self) -> Result<JsValue, JsValue> {
34 serde_wasm_bindgen::to_value(&self.0)
35 .map_err(|e| JsValue::from_str(&format!("to_js_value: {e}")))
36 }
37
38 pub fn from_json(json: &str) -> Result<Int, JsValue> {
39 serde_json::from_str(json)
40 .map(Self)
41 .map_err(|e| JsValue::from_str(&format!("from_json: {e}")))
42 }
43
44 pub fn new(x: i64) -> Self {
45 if x >= 0 {
46 Self(cml_core::Int::new_uint(x as u64))
47 } else {
48 Self(cml_core::Int::new_nint((x + 1).unsigned_abs()))
49 }
50 }
51
52 pub fn to_str(&self) -> String {
53 self.0.to_string()
54 }
55
56 #[allow(clippy::should_implement_trait)]
57 pub fn from_str(string: &str) -> Result<Int, JsValue> {
58 std::str::FromStr::from_str(string)
60 .map(Self)
61 .map_err(|e| JsValue::from_str(&format!("Int.from_str({string}): {e:?}")))
62 }
63}
64
65impl From<cml_core::Int> for Int {
66 fn from(native: cml_core::Int) -> Self {
67 Self(native)
68 }
69}
70
71impl From<Int> for cml_core::Int {
72 fn from(wasm: Int) -> Self {
73 wasm.0
74 }
75}
76
77impl AsRef<cml_core::Int> for Int {
78 fn as_ref(&self) -> &cml_core::Int {
79 &self.0
80 }
81}