diff options
author | Jared Beller <25756846+jbellerb@users.noreply.github.com> | 2021-02-13 11:56:56 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-02-13 11:56:56 -0500 |
commit | b50691efed482496e241857921b66b65bec61655 (patch) | |
tree | 63acea6b2e2b1ae9ca43585f22800cade8458e27 /core/examples/hello_world.rs | |
parent | af460fc464562566dc1534c0f61f53c2976b9bd7 (diff) |
refactor(core): Strongly typed deserialization of JSON ops (#9423)
This PR makes json_op_sync/async generic to all Deserialize/Serialize types
instead of the loosely-typed serde_json::Value. Since serde_json::Value
implements Deserialize/Serialize, very little existing code needs to be updated,
however as json_op_sync/async are now generic, type inference is broken in some
cases (see cli/build.rs:146). I've found this reduces a good bit of boilerplate,
as seen in the updated deno_core examples.
This change may also reduce serialization and deserialization overhead as serde
has a better idea of what types it is working with. I am currently working on
benchmarks to confirm this and I will update this PR with my findings.
Diffstat (limited to 'core/examples/hello_world.rs')
-rw-r--r-- | core/examples/hello_world.rs | 22 |
1 files changed, 4 insertions, 18 deletions
diff --git a/core/examples/hello_world.rs b/core/examples/hello_world.rs index 1f696a817..c46fc1d98 100644 --- a/core/examples/hello_world.rs +++ b/core/examples/hello_world.rs @@ -50,27 +50,13 @@ fn main() { // The json_op_sync function automatically deserializes // the first ZeroCopyBuf and serializes the return value // to reduce boilerplate - json_op_sync(|_state, json, zero_copy| { - // We check that we only got the JSON value, - // and that it's of the right type. + json_op_sync(|_state, json: Vec<f64>, zero_copy| { + // We check that we only got the JSON value. if !zero_copy.is_empty() { Err(anyhow!("Expected exactly one argument")) - } else if !json.is_array() { - Err(anyhow!("Argument is not of type array")) - } else if !json - .as_array() - .unwrap() - .iter() - .all(|value| value.is_number()) - { - Err(anyhow!("Argument is not array of numbers")) } else { - // And if everything checks out we do our actual task - let sum = json - .as_array() - .unwrap() - .iter() - .fold(0.0, |a, v| a + v.as_f64().unwrap()); + // And if we did, do our actual task + let sum = json.iter().fold(0.0, |a, v| a + v); // Finally we return a JSON value Ok(Value::from(sum)) |