#![feature(async_await, async_closure)]
// [dependencies]
// tokio = "0.1.19"
// futures-preview = { version = "0.3.0-alpha.17", features = ["compat"] }
use futures::prelude::*;
pub type Handler<A> = dyn FnMut(Context<A>) + Send + 'static;
pub trait Address {}
impl<T> Address for T {}
pub struct Router<A> {
route: Option<Box<Handler<A>>>,
}
pub struct Context<A>(A);
pub type Caller<A> = Context<A>;
#[derive(Clone)]
pub struct Driver;
impl<A> Router<A>
where
A: Address,
{
fn set_sync_boxed<F>(&mut self, handler: Box<F>)
where
F: FnMut(Context<A>) + Send + 'static,
{
self.route = Some(handler);
}
pub fn set_boxed<F, T>(&mut self, mut handler: Box<F>)
where
F: (FnMut(Context<A>) -> T) + Send + 'static,
T: std::future::Future<Output = ()> + Send + 'static,
{
let handler = move |ctx| {
let fut = handler(ctx).unit_error().boxed().compat();
tokio::spawn(fut);
};
self.set_sync_boxed(Box::new(handler))
}
}
pub async fn info<A>(_ctx: Context<A>, _driver: Driver)
where
A: Address + 'static
{
unimplemented!()
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn it_works() {
let router: Router<u8> = Router {route: None};
let driver_inner = Driver{};
let handler = async move |ctx| {
info(ctx, driver_inner.clone()).await;
};
let handler = Box::new(handler);
router.set_boxed(handler);
assert_eq!(2 + 2, 4);
}
}
// [dependencies]
// tokio = "0.1.19"
// futures-preview = { version = "0.3.0-alpha.17", features = ["compat"] }
use futures::prelude::*;
pub type Handler<A> = dyn FnMut(Context<A>) + Send + 'static;
pub trait Address {}
impl<T> Address for T {}
pub struct Router<A> {
route: Option<Box<Handler<A>>>,
}
pub struct Context<A>(A);
pub type Caller<A> = Context<A>;
#[derive(Clone)]
pub struct Driver;
impl<A> Router<A>
where
A: Address,
{
fn set_sync_boxed<F>(&mut self, handler: Box<F>)
where
F: FnMut(Context<A>) + Send + 'static,
{
self.route = Some(handler);
}
pub fn set_boxed<F, T>(&mut self, mut handler: Box<F>)
where
F: (FnMut(Context<A>) -> T) + Send + 'static,
T: std::future::Future<Output = ()> + Send + 'static,
{
let handler = move |ctx| {
let fut = handler(ctx).unit_error().boxed().compat();
tokio::spawn(fut);
};
self.set_sync_boxed(Box::new(handler))
}
}
pub async fn info<A>(_ctx: Context<A>, _driver: Driver)
where
A: Address + 'static
{
unimplemented!()
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn it_works() {
let router: Router<u8> = Router {route: None};
let driver_inner = Driver{};
let handler = async move |ctx| {
info(ctx, driver_inner.clone()).await;
};
let handler = Box::new(handler);
router.set_boxed(handler);
assert_eq!(2 + 2, 4);
}
}
Возвращаясь к теме, что в расте запрещена рекурсия async-функций. Написал простейший web-scrapper на космическом языке dart :)) - выкачивает ссылки до определенной глубины, отсекая дубли, и замеряя время. И рекурсия асинхронной функции тут работает влет, а ведь dart умеет компилять в машинный код, то есть такое возможно в принципе сделать - стейтмашину с динамическим стеком, жду когда растишка до такого дорастет !
https://gist.github.com/epishman/703006571d273532619096412165a7bf
https://gist.github.com/epishman/703006571d273532619096412165a7bf
Gist
Recursion of async function "do_query()"
Recursion of async function "do_query()". GitHub Gist: instantly share code, notes, and snippets.
Конвертация замыкания к FnMut
fn check(_: impl FnMut()) {}
fn main() {
let f = || {};
check(f);
}
fn check(_: impl FnMut()) {}
fn main() {
let f = || {};
check(f);
}
Forwarded from Nikita Melkozerov
В линухе уже все есть:
/usr/bin/numactl -m 0 -N 0 ./hello-world
/usr/bin/numactl -m 0 -N 0 ./hello-world
Forwarded from Слава
Скорее уж вот это
https://unix.stackexchange.com/questions/326579/how-to-ensure-exclusive-cpu-availability-for-a-running-process
https://unix.stackexchange.com/questions/326579/how-to-ensure-exclusive-cpu-availability-for-a-running-process
Unix & Linux Stack Exchange
How to ensure exclusive CPU availability for a running process?
At first, the question seems to be a little bit silly/confusing as the OS does the job of managing process execution.
However, I want to measure how much some processes are CPU/IO-bound and I feel...
However, I want to measure how much some processes are CPU/IO-bound and I feel...
Forwarded from Tihran Katolikian
До С++17 да, означал, что ретурн будет ->.
После с++17 можно просто писать auto
После с++17 можно просто писать auto
Forwarded from Mikola Summer Duck
Если кто не знает есть активный проект компилятора подмножества раста в SPIR-V
Forwarded from Jack
Кстати, насчет no_std async/await: https://github.com/Nemo157/embrio-rs/blob/master/embrio-async/tests/smoke.rs
GitHub
Nemo157/embrio-rs
Contribute to Nemo157/embrio-rs development by creating an account on GitHub.
Forwarded from Adv0cat
Кстати о новичках...)) есть классная ссылка с основными для новичков штуками https://www.breakdown-notes.com/make/load/rust_cs_canvas/true
Но этим не сильно удобно пользоваться... Я бы даже сказал вааще не удобно 😊
Но этим не сильно удобно пользоваться... Я бы даже сказал вааще не удобно 😊
Breakdown-Notes
Breakdown Notes
Breakdown notes: Make mindmaps and notes online for free
Forwarded from 71 6Ö5 [GMT +3]
комрады - вопрос, раст динамичное число агрументов не поддерживает - можно ли как-то сделать
a = Struct::new(arg1);
b = Struct::new(arg1, arg2);
Forwarded from SkyCoffee
можно, но костыльно и в nightly https://crates.io/crates/overloadable
Forwarded from Zygohistomorphic Prepromorphism🇺🇦
да если честно лучше это прочитать, чем абрамовщину
https://www.humblespark.com/blog/extensible-effects-in-node-part-1
https://www.humblespark.com/blog/extensible-effects-in-node-part-1
HumbleSpark
Extensible Effects in Node.js, Part 1 | HumbleSpark
Forwarded from Zygohistomorphic Prepromorphism🇺🇦
ну тут у тебя как бы фриер монада в жс))) адт через прототайп
Forwarded from Leonid 🦇 Onokhov
Поганое солнце стояло в зените,
Поганые люди сидели вокруг,
Автобусом правил поганый водитель,
И очень погано смеялся мой друг.
Поганые люди сидели вокруг,
Автобусом правил поганый водитель,
И очень погано смеялся мой друг.