upend/wasm/src/lib.rs

77 lines
1.8 KiB
Rust

use upend_base::{
addressing::{Address, AddressComponents},
constants,
error::UpEndError,
};
use wasm_bindgen::prelude::*;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[derive(Debug, Clone)]
pub struct WasmError(String);
impl std::fmt::Display for WasmError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for WasmError {}
#[allow(clippy::from_over_into)]
impl Into<JsValue> for WasmError {
fn into(self) -> JsValue {
JsValue::from_str(&self.0)
}
}
#[wasm_bindgen]
pub fn addr_to_components(address: String) -> Result<AddressComponents, WasmError> {
let address: Address = address
.parse()
.map_err(|e: UpEndError| WasmError(e.to_string()))?;
Ok(address.as_components())
}
#[wasm_bindgen]
pub fn components_to_addr(components: AddressComponents) -> Result<String, WasmError> {
let address =
Address::from_components(components).map_err(|e: UpEndError| WasmError(e.to_string()))?;
Ok(address.to_string())
}
#[wasm_bindgen]
pub struct AddressTypeConstants {}
#[wasm_bindgen]
#[allow(non_snake_case, clippy::new_without_default)]
impl AddressTypeConstants {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
AddressTypeConstants {}
}
#[wasm_bindgen(getter)]
pub fn Hash(&self) -> String {
constants::TYPE_HASH_ADDRESS.to_string()
}
#[wasm_bindgen(getter)]
pub fn Uuid(&self) -> String {
constants::TYPE_UUID_ADDRESS.to_string()
}
#[wasm_bindgen(getter)]
pub fn Attribute(&self) -> String {
constants::TYPE_ATTRIBUTE_ADDRESS.to_string()
}
#[wasm_bindgen(getter)]
pub fn Url(&self) -> String {
constants::TYPE_URL_ADDRESS.to_string()
}
}