#[cfg(target_arch = "wasm32")]
pub const WASM_TARGET: &str = "wasm32-unknown-unknown";
#[cfg(target_arch = "wasm32")]
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
#[cfg(target_arch = "wasm32")]
pub struct WasmTimestamp {
pub ms: f64,
}
#[cfg(target_arch = "wasm32")]
impl WasmTimestamp {
#[must_use]
pub fn new(ms: f64) -> Self {
Self { ms }
}
#[must_use]
pub fn seconds(&self) -> f64 {
self.ms / 1000.0
}
}
#[cfg(target_arch = "wasm32")]
#[derive(Debug, Clone)]
pub struct WasmError {
pub message: String,
pub code: u32,
}
#[cfg(target_arch = "wasm32")]
impl WasmError {
pub fn new(message: impl Into<String>, code: u32) -> Self {
Self {
message: message.into(),
code,
}
}
}
#[cfg(target_arch = "wasm32")]
impl std::fmt::Display for WasmError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "WasmError({}): {}", self.code, self.message)
}
}
#[cfg(target_arch = "wasm32")]
pub struct WasmAllocatorConfig {
pub initial_pages: u32,
pub max_pages: Option<u32>,
}
#[cfg(target_arch = "wasm32")]
impl Default for WasmAllocatorConfig {
fn default() -> Self {
Self {
initial_pages: 256, max_pages: Some(4096), }
}
}
#[cfg(target_arch = "wasm32")]
pub struct WasmBuffer {
data: Vec<u8>,
}
#[cfg(target_arch = "wasm32")]
impl WasmBuffer {
#[must_use]
pub fn new(capacity: usize) -> Self {
Self {
data: Vec::with_capacity(capacity),
}
}
#[must_use]
pub fn from_bytes(bytes: Vec<u8>) -> Self {
Self { data: bytes }
}
#[must_use]
pub fn as_slice(&self) -> &[u8] {
&self.data
}
#[must_use]
pub fn len(&self) -> usize {
self.data.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
#[must_use]
pub fn capacity(&self) -> usize {
self.data.capacity()
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_wasm_timestamp_seconds() {
let ms = 2000.0_f64;
let seconds = ms / 1000.0;
assert!((seconds - 2.0).abs() < f64::EPSILON);
}
#[test]
fn test_wasm_error_display() {
let code: u32 = 42;
let message = "something went wrong";
let formatted = format!("WasmError({code}): {message}");
assert!(formatted.contains("WasmError(42)"));
assert!(formatted.contains("something went wrong"));
}
#[test]
fn test_wasm_allocator_config_default() {
let initial_pages: u32 = 256;
let max_pages: Option<u32> = Some(4096);
assert_eq!(initial_pages, 256);
assert_eq!(max_pages, Some(4096));
}
#[test]
fn test_wasm_buffer_from_bytes() {
let bytes = vec![1u8, 2, 3, 4, 5];
let len = bytes.len();
assert_eq!(len, 5);
}
}