1use crate::utils::{from_hex, to_hex};
2use hex::FromHexError;
3use serde::*;
4#[cfg(target_arch = "wasm32")]
5use wasm_bindgen::prelude::*;
6#[cfg(target_arch = "wasm32")]
7use wasm_bindgen::{throw_str, JsValue};
8
9#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
13#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Bytes(#[serde(serialize_with = "to_hex", deserialize_with = "from_hex")] pub(crate) Vec<u8>);
15
16impl Bytes {
17 pub(crate) fn from_hex_impl(hex_str: &str) -> Result<Bytes, FromHexError> {
18 let bytes = hex::decode(hex_str)?;
19 Ok(Bytes(bytes))
20 }
21}
22
23#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
24impl Bytes {
25 #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = readReverse))]
26 pub fn to_slice_le(&self) -> Vec<u8> {
27 let mut bytes = self.0.clone();
28 bytes.reverse();
29 bytes
30 }
31
32 #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = read))]
33 pub fn to_slice_be(&self) -> Vec<u8> {
34 self.0.clone()
35 }
36
37 pub fn reverse(&mut self) {
38 self.0.reverse();
39 }
40
41 #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = toHex))]
42 pub fn to_hex(&self) -> String {
43 hex::encode(&self.0)
44 }
45}
46
47#[cfg(target_arch = "wasm32")]
48#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
49impl Bytes {
50 #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = fromHex))]
51 pub fn from_hex(hex_str: &str) -> Result<Bytes, JsValue> {
52 match Bytes::from_hex_impl(hex_str) {
53 Ok(v) => Ok(v),
54 Err(e) => Err(JsValue::from_str(&e.to_string())),
55 }
56 }
57}
58
59#[cfg(not(target_arch = "wasm32"))]
60impl Bytes {
61 pub fn from_hex(hex_str: &str) -> Result<Bytes, FromHexError> {
62 Bytes::from_hex_impl(hex_str)
63 }
64}