chiark / gitweb /
wip wasm bindings
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Sun, 11 Oct 2020 21:12:35 +0000 (22:12 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Sun, 11 Oct 2020 21:12:35 +0000 (22:12 +0100)
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
wasm/wasm.rs

index 819cba58643072a924b2766b0b9fdc0accc6db45..af7a2c7e08aa38fe618d2934b93b9ffb72e3a159 100644 (file)
@@ -1,12 +1,41 @@
 
 use wasm_bindgen::prelude::*;
 use fehler::throws;
+use std::fmt::Display;
 
 use zcoord::ZCoord;
 
 #[wasm_bindgen]
 pub struct ZCoordIterator (zcoord::Mutable);
 
+trait WasmError {
+  fn e(self) -> JsValue;
+}
+
+impl<E> WasmError for E where E: Display {
+  fn e(self) -> JsValue {
+    let s = format!("{}", self);
+    JsValue::from_str(&s)
+  }
+}
+
+trait WasmResult<V> {
+  fn e(self) -> Result<V,JsValue>;
+}
+
+impl<E:Display, V> WasmResult<V> for Result<V, E> {
+  fn e(self) -> Result<V, JsValue> { self.map_err(WasmError::e) }
+}
+
+#[throws(JsValue)]
+#[wasm_bindgen]
+pub fn check(packed: &JsValue) {
+  let s = packed.as_string().ok_or_else(
+    ||"packed Z coordinate wrong JS type (not a string)"
+  ).e()?;
+  ZCoord::check_str(&s).ok_or(zcoord::ParseError).e()?;
+}
+
 const X : &'static str = "invalid value passed to wasm";
 
 #[throws(JsValue)]