Debian Codegraph @

crates/wasm-wave/src/lib.rs

raw
1 //! Web Assembly Value Encoding
2 //!
3 //! WAVE is a human-oriented text encoding of WebAssembly Component Model values.
4 //!
5 //! For more information, see the [README](https://github.com/bytecodealliance/wasm-tools/tree/main/crates/wasm-wave#readme).
6 #![deny(missing_docs)]
7
8 pub mod ast;
9 pub mod lex;
10 pub mod parser;
11 mod strings;
12 pub mod untyped;
13 pub mod value;
14 pub mod wasm;
15 pub mod writer;
16
17 use parser::Parser;
18 use wasm::WasmValue;
19 use writer::Writer;
20
21 /// Parses a [`WasmValue`] from the given WAVE-encoded string.
22 /// ```
23 /// # fn main() -> Result<(), wasm_wave::parser::ParserError> {
24 /// use wasm_wave::{wasm::WasmValue, value::{Type, Value}};
25 /// let val: Value = wasm_wave::from_str(&Type::CHAR, r"'\u{1F44B}'")?;
26 /// assert_eq!(val, Value::make_char('👋'));
27 /// # Ok(())
28 /// # }
29 /// ```
30 pub fn from_str<V: WasmValue>(ty: &V::Type, s: &str) -> Result<V, parser::ParserError> {
31 let mut parser = Parser::new(s);
32
33 let value = parser.parse_value(ty)?;
34
35 // Ensure that we've parsed the entire string.
36 parser.finish()?;
37
38 Ok(value)
39 }
40
41 /// Returns the given [`WasmValue`] as a WAVE-encoded string.
42 /// ```
43 /// # fn main() -> Result<(), wasm_wave::writer::WriterError> {
44 /// use wasm_wave::{wasm::WasmValue, value::Value};
45 /// let wave_str = wasm_wave::to_string(&Value::make_char('\u{1F44B}'))?;
46 /// assert_eq!(wave_str, "'👋'");
47 /// # Ok(())
48 /// # }
49 pub fn to_string(val: &impl WasmValue) -> Result<String, writer::WriterError> {
50 let mut buf = vec![];
51 Writer::new(&mut buf).write_value(val)?;
52 Ok(String::from_utf8(buf).unwrap_or_else(|err| panic!("invalid UTF-8: {err:?}")))
53 }
54
55 fn canonicalize_nan32(val: f32) -> f32 {
56 if val.is_nan() {
57 f32::from_bits(0x7fc00000)
58 } else {
59 val
60 }
61 }
62
63 fn canonicalize_nan64(val: f64) -> f64 {
64 if val.is_nan() {
65 f64::from_bits(0x7ff8000000000000)
66 } else {
67 val
68 }
69 }