惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
博客园 - 司徒正美
美团技术团队
Last Week in AI
Last Week in AI
月光博客
月光博客
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
U
Unit 42
T
Tailwind CSS Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
Google DeepMind News
Google DeepMind News
H
Help Net Security
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
Y
Y Combinator Blog
罗磊的独立博客
D
DataBreaches.Net
有赞技术团队
有赞技术团队
MyScale Blog
MyScale Blog
博客园_首页
博客园 - 三生石上(FineUI控件)
G
Google Developers Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
博客园 - Franky
M
MIT News - Artificial intelligence
B
Blog
The Cloudflare Blog
Apple Machine Learning Research
Apple Machine Learning Research
I
InfoQ
S
SegmentFault 最新的问题
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog

The Rust Programming Language Forum - Latest posts

What's everyone working on this week (21/2026)? Rust Function Call with one Param Iced + Canvas + Text: How do I create a style for canvas text "Value dropped while borrowed" as a lifetime mismatch Weird `use of moved value` behaviour Slightly surprising behavior of a while loop Clap: how to disable options after a certain positional argument How do i tell rust-analyzer what kind of bracket to use for a macro? Iterator + Borrow Checker: Work around borrowing already borrowed mutable variable Requesting data via mavlink SKILLS.md for Rust development 🧵 Stringlet UTF-8 Hack Option Niche? Iterator + Map - How do divide every element, including the last element, by the last element Why can't we store returned value of a function in a variable if one of the parameters goes out of scope My first crate :D, floop: A more convenient and less error prone replacement for loop `{ select! { .. }}` Sorting is slow because architectures are wrong — zan-sort redesigns the architecture, not the algorithm Iced Font - Create a custom monospace font to display dollar amounts Is the UnsafePinned RFC wrong about being able to return `&mut T` from `get_mut_unchecked`? Fixing Polars 0.37 compilation errors: Hashbrown 0.17 dependency conflict and decimal parsing Any plans for improving error diagnostic in Rust 2.0? How do I build completely offline? Is `&mut T -> &mut ManuallyDrop<T>` well-defined and sound? Would you use this? — fixtura, declarative fake data injection for tests Foreign trait restrictions on native types make generics hard to use Cargo Exclude Directive Compiler reasoning around a modulo counter Multiple mutable references to elements within one vector Handling non-`Send` data in a `Send` closure Review: Static Multi Pool Allocator Rmquickjs - High-level MicroQuickJS bindings for Rust Iced + Rusqlite + Chrono: Problem with custom error type Why can&#39;t the Rust compiler infer the T type parameter in this BTreeMap::range call? Beginner building a Rust backend framework (AI-assisted) — feedback appreciated C++ to Rust -- Exceptions Re-exporting a trait with a custom derive_macro Gold linker is deprecated Why is using PhantomData valid in this case? Code review for Static Pool Allocator Discussion on Synchronous Crate Concurrency Refactor using Stackful Coroutines Model in Rust Can a future used only by `async fn` assume it won&#39;t be polled again after becoming ready? High-performance `fast-powi` crate Looking for a pool based allocator Why is this legal? What does it mean for Rustc to run "out of TLS keys"? Testing functions that use randomness `cargo-path`: improve coding agents&#39; ability to find Rust documentation Rust task runners Lifetime weird case Windows - USB device not detected A random rustc-ice-[...].txt file appeared Develop rust where the environment is setup in a docker Undefined Behavior: in-bounds pointer arithmetic failed: attempting to offset pointer by 20 bytes, but got alloc238 which is only 1 byte from the end of the allocation Unbug 0.5 - Runtime debug assertions Is there a tiny error in section 6.2 Reference types? Vasya go to (his) Home 🏡 Lifetime woes implementing ratatui::Widget for a reference Rusqlite + Chrono: How do I simplify code to obtain chrono datetime value From OOP to Rust – struggling with code organization and data structure design Way to avoid a self-referential struct Rust RF and audio resources/communities Whyhttp - HTTP mocks that fail where the bug actually is Using tokio channel permits in a tower service Arc::increment_strong_count design question (cross-post) `&T`, `&mut T`, `Pin<&mut T>` and `&Cell<T>`: Ways of Borrowing a `T` Ratatui detect arrow key press and release Feedback about post in medium Debugger not showing/offering variables? nestrs: a NestJS-style framework for Rust built on Axum and Tower Confusion about struct variance with &mut dyn How do I do hmr in rust How to call struct method as function pointer in loop Loops inside loops and mutable reference on Iterator VSCode - rust-analyzer - annoying re-builds due to RUSTC_BOOTSTRAP changed Borsh v1.6.1 example What's everyone working on this week (14/2026)? What's everyone working on this week (17/2026)? RawWakerVTable functions, did I write them correctly? Cargo test's verbose output - can I quiet it? Sem: semantic entity level version control CLI built with tree-sitter How do i get all the words in a string and convert it into a vector? Looking for feedback on my first tokenizer in Rust Frostmirror - (lightweight airgap alternative inspired from panamax and romt) - an offline cargo repository for airgap system that can be deployed through a docker image Does "ill-formed, no diagnostic required" exist in Rust? If a program is built with software floating-point emulation, is it affected by hardware floating-point environment? Rustc-link-lib static library How does crates.io and docs.rs store crates? Basic Object Oriented Programming in Rust Various input in one line error[E0080]: index out of bounds error when trying to install LuaCAD CSV to SQLite - Is it better to write records as they are being read Looking for feedback for a graph-based task scheduler This is my first project. I invented a new algorithm that even AI don't know. It's about bigint. And I'm 15. Thanks for watching. By the way, my crate named `nna` Why Windows rustc uses a different color scheme? Clap completion question Is RMW operation less prone to reading stale values than a pure load? Why are builds of my crate's test not consistent (cargo build vs cargo test vs VSCode-Test-Explorer) Type inference of generic parameters Cyw43 on STM32H723 Reducing code repetition with Vecs and fields Are there any object detection libraries out there for the Arduino?
Using async/await internally with no internal runtime, but exposing a nonblocking poll API — is this a reasonable design?
ybjeon01 · 2026-04-24 · via The Rust Programming Language Forum - Latest posts
I'm designing a database driver in Rust, and I'm exploring a hybrid design where: async/await is used internally to implement protocol logic but the public API is a libpq-style nonblocking poll interface So instead of exposing async functions, the API looks more like: start an operation poll for progress if it would block, report whether the caller should wait for read or write readiness poll again eventually return the result One of my main goals is to expose this library to Python with good async support. I’ve looked at approaches that embed a Rust async runtime (for example via pyo3 + tokio) and then expose that as Python async APIs. However, in my benchmark, this did not perform as well as I expected, likely because two runtimes end up interacting. Because of that, I’m intentionally trying to avoid embedding or depending on any async runtime inside the library. Instead, I want: the Rust library to stay runtime-agnostic no internal executor and the outer environment (for example Python's asyncio) to drive IO readiness This is partly inspired by libpq/psycopg, where libpq's nonblocking API can be integrated into Python async code. Internally, though, I would still like to use async/await, because writing the protocol as a manual FSM is quite verbose and hard to maintain once there are multiple write/read steps. So the design I'm considering is: async/await is used purely as an implementation technique futures are stored internally and manually polled no executor is used; futures are polled directly when IO would block, the code records whether it needs read or write readiness the public poll() API returns that information to the caller Here this example shows the control-flow shape of the design. use std::cell::Cell; use std::future::Future; use std::io::{self, Read, Write}; use std::net::TcpStream; use std::pin::Pin; use std::rc::Rc; use std::task::{Context, Poll, Waker}; // the reason I’m using Tokio’s traits is to leverage tokio-util’s Codec. // I found that tokio-postgres uses Framed and Codec, and they seemed // like very convenient utilities. use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IoInterest { Read, Write, } #[derive(Debug, Clone)] pub struct SocketInterest(Rc<Cell<Option<IoInterest>>>); #[derive(Debug)] pub struct Socket { inner: TcpStream, interest: SocketInterest, } impl Socket { pub fn new(stream: TcpStream) -> io::Result<Self> { stream.set_nonblocking(true)?; Ok(Self { inner: stream, interest: SocketInterest(Rc::new(Cell::new(None))), }) } pub fn interest(&self) -> SocketInterest { self.interest.clone() } } impl AsyncRead for Socket { fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { let this = self.get_mut(); let unfilled = buf.initialize_unfilled(); match this.inner.read(unfilled) { Ok(0) => Poll::Ready(Ok(())), Ok(n) => { buf.advance(n); Poll::Ready(Ok(())) } Err(e) if e.kind() == io::ErrorKind::WouldBlock => { this.interest.0.set(Some(IoInterest::Read)); Poll::Pending } Err(e) => Poll::Ready(Err(e)), } } } impl AsyncWrite for Socket { fn poll_write( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { let this = self.get_mut(); match this.inner.write(buf) { Ok(n) => Poll::Ready(Ok(n)), Err(e) if e.kind() == io::ErrorKind::WouldBlock => { this.interest.0.set(Some(IoInterest::Write)); Poll::Pending } Err(e) => Poll::Ready(Err(e)), } } fn poll_flush( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<io::Result<()>> { let this = self.get_mut(); match this.inner.flush() { Ok(()) => Poll::Ready(Ok(())), Err(e) if e.kind() == io::ErrorKind::WouldBlock => { this.interest.0.set(Some(IoInterest::Write)); Poll::Pending } Err(e) => Poll::Ready(Err(e)), } } fn poll_shutdown( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<io::Result<()>> { Poll::Ready(self.get_mut().inner.shutdown(std::net::Shutdown::Write)) } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClientResponse { CommandComplete { rows_affected: u64 }, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClientPoll { Idle, Pending(IoInterest), Ready(ClientResponse), } type ClientFuture = Pin<Box<dyn Future<Output = io::Result<(Socket, ClientResponse)>>>>; enum ClientState { Idle(Socket), Executing(ClientFuture, SocketInterest), Transitioning, } pub struct Client { state: ClientState, } async fn do_execute(mut socket: Socket) -> io::Result<(Socket, ClientResponse)> { // toy protocol: // // client -> server: // [b'Q'][len: u8][query bytes...] // // server -> client: // [b'C'][rows_affected: u64 big-endian] let query = b"SELECT 1"; let query_len = u8::try_from(query.len()) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "query too long"))?; socket.write_all(&[b'Q', query_len]).await?; socket.write_all(query).await?; socket.flush().await?; let mut tag = [0u8; 1]; socket.read_exact(&mut tag).await?; if tag[0] != b'C' { return Err(io::Error::new( io::ErrorKind::InvalidData, "unexpected response tag", )); } let mut rows_buf = [0u8; 8]; socket.read_exact(&mut rows_buf).await?; let rows_affected = u64::from_be_bytes(rows_buf); Ok(( socket, ClientResponse::CommandComplete { rows_affected }, )) } impl Client { pub fn new(socket: Socket) -> Self { Self { state: ClientState::Idle(socket), } } pub fn start_execute(&mut self) -> io::Result<()> { let old_state = std::mem::replace(&mut self.state, ClientState::Transitioning); match old_state { ClientState::Idle(socket) => { let sensor = socket.interest(); let fut = Box::pin(do_execute(socket)); self.state = ClientState::Executing(fut, sensor); Ok(()) } other => { self.state = other; Err(io::Error::new(io::ErrorKind::Other, "client is busy")) } } } pub fn poll(&mut self) -> io::Result<ClientPoll> { let ClientState::Executing(fut, sensor) = &mut self.state else { return Ok(ClientPoll::Idle); }; // no executor: the caller explicitly drives progress let waker = Waker::noop(); let mut cx = Context::from_waker(waker); match fut.as_mut().poll(&mut cx) { Poll::Ready(result) => { let (socket, response) = result?; self.state = ClientState::Idle(socket); Ok(ClientPoll::Ready(response)) } Poll::Pending => { let interest = sensor.0.take().unwrap_or(IoInterest::Read); Ok(ClientPoll::Pending(interest)) } } } } My questions are: Does this seem like a reasonable architecture? (async/await internally, nonblocking poll API externally, no runtime) What kinds of subtle issues might I be missing? In practice, would it be better to implement the protocol as a manual FSM? Are there existing projects using a similar approach? Any advice would be greatly appreciated. 1 post - 1 participant Read full topic