2020/05/06

How tokio join macro works

tokio's join macro is pretty amazing

To find out how this join! macro works exactly,  you can do blow to expand the macro to see exact code generated.
rustup toolchain install nightly
cargo install cargo-expand

then in your project
cargo expand
You will find the expanded code like below

// Macro expaned from
// let (first, second) = tokio::join!(do_stuff1(), do_stuff2());
let (first, second) = {
use ::tokio::macros::support::{maybe_done, poll_fn, Future, Pin};
use ::tokio::macros::support::Poll::{Ready, Pending};
let mut futures = (maybe_done(do_stuff1()), maybe_done(do_stuff2()));
poll_fn(move |cx| {
let mut is_pending = false;
let (fut, ..) = &mut futures;
let mut fut = unsafe { Pin::new_unchecked(fut) };
if fut.poll(cx).is_pending() {
is_pending = true;
}
let (_, fut, ..) = &mut futures;
let mut fut = unsafe { Pin::new_unchecked(fut) };
if fut.poll(cx).is_pending() {
is_pending = true;
}
if is_pending {
Pending
} else {
Ready((
{
let (fut, ..) = &mut futures;
let mut fut = unsafe { Pin::new_unchecked(fut) };
fut.take_output().expect("expected completed future")
},
{
let (_, fut, ..) = &mut futures;
let mut fut = unsafe { Pin::new_unchecked(fut) };
fut.take_output().expect("expected completed future")
},
))
}
})
.await
};

2020/05/05

Usage of serde_json


Some sample code shows behavior of serde_json.

I used to write code like

val.as_object().unwrap().get("field_name").unwrap().as_object().unwrap().get_("sub_field_name").as_str().unwrap().

Turns out that using index of serde_json makes code much less verbose.


use serde_json::Value;
fn main() {
let test_json = r#"
{
"a":"a_val",
"b":{
"b_sub" : "b_sub_val"
},
"d":[
{
"d0" : "d0_val"
},
{
"d1" : "d1_val"
}
]
}
"#;
let val: Value = serde_json::from_str(test_json).unwrap();
println!("{}", val["a"]);
println!("{}", val["b"]);
println!("{}", val["b"]["b_sub"]);
println!("{}", val["b"]["b_sub"].to_string());
println!("{}", val["b"]["b_sub"].as_str().unwrap());
println!("{}", val["d"][0]["d0"].as_str().unwrap());
println!("{}", val["no_exist"]["what_will_happen"]);
}
view raw playground.rs hosted with ❤ by GitHub

Post Code on Blogger

Simplest way to post code to blogger for me: <pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black;overflow-x:...