Merge sync_lib and sync_wasm

This commit is contained in:
Andras Schmelczer 2024-12-08 21:58:28 +00:00
parent dfb747c206
commit a2a4611497
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
9 changed files with 134 additions and 58 deletions

View file

@ -1,5 +1,6 @@
use base64::DecodeError;
use thiserror::Error;
use wasm_bindgen::JsValue;
#[derive(Error, Debug)]
pub enum SyncLibError {
@ -22,3 +23,7 @@ impl From<std::string::FromUtf8Error> for SyncLibError {
}
}
}
impl From<SyncLibError> for JsValue {
fn from(val: SyncLibError) -> Self { JsValue::from_str(&val.to_string()) }
}

View file

@ -1,19 +1,42 @@
use base64::{Engine as _, engine::general_purpose::STANDARD_NO_PAD};
use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine as _};
use errors::SyncLibError;
use wasm_bindgen::prelude::*;
pub mod errors;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
pub fn bytes_to_base64(input: &[u8]) -> String { STANDARD_NO_PAD.encode(input) }
#[wasm_bindgen]
pub fn string_to_base64(input: &str) -> String { bytes_to_base64(input.as_bytes()) }
#[wasm_bindgen]
pub fn base64_to_bytes(input: &str) -> Result<Vec<u8>, SyncLibError> {
STANDARD_NO_PAD.decode(input).map_err(SyncLibError::from)
}
#[wasm_bindgen]
pub fn base64_to_string(input: &str) -> Result<String, SyncLibError> {
let bytes = base64_to_bytes(input)?;
String::from_utf8(bytes).map_err(SyncLibError::from)
}
#[wasm_bindgen]
pub fn is_binary(data: &[u8]) -> bool { data.iter().any(|&b| b == 0) }
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}