stk_json/lib.rs
1//! The json package, providing access to functions to serialize and deserialize
2//! json.
3//!
4//! ## Usage
5//!
6//! Add the following to your `Cargo.toml`:
7//!
8//! ```toml
9//! stk = "0.2"
10//! stk-json = "0.2"
11//! ```
12//!
13//! Install it into your context:
14//!
15//! ```rust
16//! # fn main() -> stk::Result<()> {
17//! let mut context = stk::Context::with_default_packages()?;
18//! context.install(stk_json::module()?)?;
19//! # Ok(())
20//! # }
21//! ```
22//!
23//! Use it in Rune:
24//!
25//! ```rust,ignore
26//! use json;
27//!
28//! fn main() {
29//! let data = json::from_string("{\"key\": 42}");
30//! dbg(data);
31//! }
32//! ```
33
34use stk::packages::bytes::Bytes;
35use stk::{ContextError, Module, ValuePtr};
36
37fn from_bytes(bytes: &[u8]) -> stk::Result<ValuePtr> {
38 Ok(serde_json::from_slice(&bytes)?)
39}
40
41/// Get value from json string.
42fn from_string(string: &str) -> stk::Result<ValuePtr> {
43 Ok(serde_json::from_str(string)?)
44}
45
46/// Convert any value to a json string.
47fn to_string(value: ValuePtr) -> stk::Result<String> {
48 Ok(serde_json::to_string(&value)?)
49}
50
51/// Convert any value to a json string.
52fn to_bytes(value: ValuePtr) -> stk::Result<Bytes> {
53 let bytes = serde_json::to_vec(&value)?;
54 Ok(Bytes::from_bytes(bytes))
55}
56
57/// Get the module for the bytes package.
58pub fn module() -> Result<Module, ContextError> {
59 let mut module = Module::new(&["json"]);
60 module.function(&["from_bytes"], from_bytes)?;
61 module.function(&["from_string"], from_string)?;
62 module.function(&["to_string"], to_string)?;
63 module.function(&["to_bytes"], to_bytes)?;
64 Ok(module)
65}