Saturday, July 25, 2020

Why tokio tasks are run-time dependent ?

Tokio and async-std 

I was going through two major crates for async programming in Rust. I believe Tokio and async-std are predominant crates now available for async programming. 

But when I tried to run tokio tasks with async-std run-time, but default it won't allow. I need to change run-time as tokio using #[tokio::main] that's not nice.

But when  I tried to run async-std tasks with tokio run-time, I am able to run.  Looks like async-std is more compatible with other Rust eco-systems.

thread 'main' panicked at 'must be called from the context of Tokio runtime configured with either `basic_scheduler` or `threaded_scheduler

There would be libraries/crates to make it happen, but I think by default this should be available.

Friday, July 24, 2020

Where is the infinite loop in the below Rust Program ?

Have you ever wonder how the below  TcpListener Code run infinitely looking for new connections/clients.

When you run this below program with a Rust compiler or Cargo run, you will see that the program is not ending. How ?

As you noticed , the for loop doesn't have a explicit condition to exit. As far as the Iterator can return values, the "for loop" construct  execute the  statements inside the body. The Iterators can behave like  an infinite loop.But can return "None"(which can be used to exit from "for") , or can return Some values from next method .

Read more to understand how "for loop"  decompose in Rust -

Ok..we understood that there is something called Iterator which can yield for values infinite.

But where is the Iterator here ?

When you look at the TcpListener , it is just a struct. But it has one particular method which implements Iterator trait. 
The connections can be accepted from TcpListener through a  struct called  std::net::Incoming  which is an Iterator.It is hidden(abstracted) behind the method incoming  in this case. As I said earlier  Iterators can yield and ask for values infinite times.

Iterator Trait is implemented on the struct "Incoming"

As you noticed the next method on the Iterator is not going to end. It just keep iterate as far as we are calling incoming method.

Incoming struct accepts connections of TcpListener:

Incoming implementing Iterator trait:

Saturday, July 18, 2020

compiled a Rust program for Wasm target without wasmbind-gen

It was not that hard to write a function and build for wasm target. I was using the #![no_std] without knowing much on it.The Rust compiler was just guiding through errors to fill the code.
I did not use the wasmbind-gen. But I did use wee_alloc

The program is below:

Note: just comment each line and see the error message compiler is giving to you.