AI 资讯
[Rust Guide] 13.4. Capturing the Environment With Closures
13.4.0 Before We Begin During its design, Rust drew inspiration from many languages, and functional programming had a particularly strong influence on Rust. Functional programming often includes passing functions as values to parameters, returning them from other functions, assigning them to variables for later execution, and so on. In this chapter, we will discuss some Rust features that are similar to what many languages call functional features: Closures (this article) Iterators Improving the I/O Project with Closures and Iterators Performance of Closures and Iterators If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series. 13.4.1 Closures Can Capture Their Environment Closures have a capability that functions do not: a closure can access variables in the scope where it is defined. Take a look at an example: fn main () { let x = 4 ; let equal_to_x = | z | z == x ; let y = 4 ; assert! ( equal_to_x ( y )); } The closure part is: let equal_to_x = | z | z == x ; Some people may find it hard to distinguish the roles of = and == here, so let’s rewrite it another way: let equal_to_x = | z | { z == x ; } In other words, the closure takes z as its parameter, compares it with x (which is 4, because x = 4 was defined above), and returns a boolean. If they are equal, the result is true ; otherwise it is false . Here the closure directly accesses the variable x in the same scope, which functions cannot do. But this feature has a cost: it introduces memory overhead . In most cases we do not need a closure to capture its environment, and we do not want the extra overhead either. That is why functions are not allowed to capture variables from the environment, and defining and using a function never introduces this kind of overhead. 13.4.2 How Closures Capture Values From Their Environment Closures capture values from the environment in three ways, just like functions receive parameters in three ways: Taking ownership, whose trait
开源项目
🔥 base / base - All components used to run Base
GitHub热门项目 | All components used to run Base | Stars: 703 | 10 stars today | 语言: Rust
开源项目
🔥 jely2002 / youtube-dl-gui - Open Video Downloader - A cross-platform GUI for youtube-dl
GitHub热门项目 | Open Video Downloader - A cross-platform GUI for youtube-dl made in Rust with Tauri and Vue + Typescript. | Stars: 8,609 | 66 stars today | 语言: Rust
AI 资讯
lopdf vs pdfium in Rust — What I Learned Building a PDF App
All tests run on an 8-year-old MacBook Air. All results from shipping 7 Mac apps as a solo developer. No sponsored opinion. I built Hiyoko PDF Vault — a macOS PDF tool — in Rust. Choosing the right PDF library was the first real decision. lopdf or pdfium. Here's what I found. lopdf: pure Rust, no dependencies lopdf is pure Rust. No C bindings, no system libraries, no bundling headaches. What it does well: Merge, split, rotate pages Read and write PDF structure Metadata manipulation Bates numbering Works well for structural PDF operations What it struggles with: Rendering PDFs to images (not its job) Complex font handling Malformed PDFs — lopdf is strict; real-world PDFs often aren't For a tool that manipulates PDF structure without rendering — merge, split, encrypt, add watermarks, strip metadata — lopdf is the right choice. Pure Rust means easy cross-compilation and universal binaries with no extra work. pdfium: full rendering, C dependency pdfium is Google's PDF engine (from Chromium). The pdfium-render crate wraps it for Rust. What it does well: Accurate PDF rendering to images Handles malformed PDFs that lopdf rejects Text extraction from complex layouts Full PDF spec compliance What it requires: Bundling the pdfium binary with your app (~20MB) Architecture-specific binaries (x86_64 and aarch64 for universal binary) More complex build setup For a tool that needs to display PDFs or extract text from complex documents, pdfium is the right choice. You pay for it in bundle size and build complexity. What I actually use lopdf for structural operations: merge, split, encrypt, watermark, metadata, Bates numbering. Apple Vision Framework (via Tauri shell commands) for OCR — it's already on the user's Mac and handles Japanese text better than anything I could bundle. I avoided pdfium because the bundle size increase wasn't worth it for my use case. If I needed accurate rendering, that calculation would change. The honest recommendation Start with lopdf. It covers most PD
AI 资讯
How I Built a Counter Program in Anchor and Learned to Trust My Tests
I spent a week building a counter program in Anchor — the Rust framework for writing Solana programs. By the end I had two instructions, one authorization constraint, and a test suite I could actually trust. Here is what I built, how I tested it, and the moment I proved the tests were real. Start Here: The Accounts Struct If you come from Web2, this is the part that looks the strangest: #[derive(Accounts)] pub struct Initialize { #[account( init, payer = authority, space = 8 + Counter::INIT_SPACE, )] pub counter : Account , #[account(mut)] pub authority : Signer , pub system_program : Program , } In a Web2 backend, your handler receives a request object and talks to a database. On Solana, there is no database; there are accounts. Every account your instruction needs to read or write must be declared upfront, before the handler runs. Anchor validates them before your code ever executes. Here is what each field does: counter — the account being created. The init constraint tells Anchor to make a CPI to the System Program, allocate 8 + Counter::INIT_SPACE bytes, and fund it from authority . The 8 is for the discriminator Anchor stamps on every account so the program can later verify "this is mine." authority — the wallet signing and paying for the transaction. mut because its SOL balance is decreasing to fund the new account. system_program — required any time you create accounts. Anchor checks that the address matches the real System Program. The accounts struct is the schema. The handler is the logic. The Handlers pub fn initialize ( ctx : Context ) -> Result { let counter = & mut ctx .accounts.counter ; counter .authority = ctx .accounts.authority .key (); counter .count = 0 ; Ok (()) } ctx.accounts gives you typed access to every account declared in the struct. The handler is short because Anchor already did the hard work: allocating the account, checking the signer, paying the rent. Your code just sets the initial values. pub fn increment ( ctx : Context ) -> Resu
开源项目
🔥 astral-sh / uv - An extremely fast Python package and project manager, writte
GitHub热门项目 | An extremely fast Python package and project manager, written in Rust. | Stars: 86,594 | 33 stars today | 语言: Rust
开源项目
🔥 tursodatabase / turso - Turso is an in-process SQL database, compatible with SQLite.
GitHub热门项目 | Turso is an in-process SQL database, compatible with SQLite. | Stars: 20,044 | 774 stars today | 语言: Rust
AI 资讯
SQLite riscritta in Rust? Perché qualcuno sta provando a toccare il codice “più affidabile” che abbiamo
Dalla libreria embedded che ha invaso ogni dispositivo a un’implementazione moderna con concorrenza, async I/O e vector search: cosa cambia davvero per chi sviluppa app. Nel frontend e nel full‑stack capita spesso di parlare di database come servizi: Postgres gestito, cluster, repliche, connessioni, pooling, credenziali e una lunga lista di “cose che possono rompersi”. Ma esiste un’altra filosofia, più vicina all’idea di “dipendenza” che di “infrastruttura”: un motore SQL che vive dentro l’applicazione. Questa è la ragione per cui SQLite è ovunque. È una libreria, non un server. Legge e scrive su un singolo file su disco. Riduce drasticamente configurazione, porte, processi separati e complessità operativa. Ed è proprio questa semplicità a renderla una delle fondamenta silenziose dell’informatica moderna: la usi in browser, smartphone, desktop app, tool CLI, IoT… spesso senza nemmeno accorgertene. Ora immagina di riscrivere tutto da capo, in Rust, cercando di essere compatibile al 100% e allo stesso tempo più “moderna”. Sembra un’idea folle per definizione—finché non inizi a guardare ai limiti pratici che oggi emergono in molte applicazioni. Perché toccare SQLite, se funziona così bene? SQLite non è “il problema”. Anzi: è considerata estremamente robusta perché è conservativa, minimalista, e custodita con un rigore quasi maniacale. Il punto è un altro: il suo modello di sviluppo e manutenzione è atipico rispetto a quello che molti intendono per open source collaborativo . Il codice è disponibile e utilizzabile liberamente, ma l’evoluzione è guidata da pochissime persone e—di fatto—non segue la dinamica classica delle contribution esterne. Questa scelta ha un effetto collaterale positivo: riduce il rischio di regressioni introdotte da cambiamenti non coerenti con la visione del progetto. Ma ha anche un costo: se la tua azienda o il tuo prodotto hanno esigenze nuove (concorrenza più spinta, I/O non bloccante, funzionalità specifiche), “aspettare che arrivi upstream” n
AI 资讯
Event-Handling-Basics
Event Handling Basics in euv Project Code: https://github.com/euv-dev/euv euv is a Rust + WASM frontend UI framework that enables developers to build interactive web applications using the power of reactive signals and the html! macro. One of the most critical aspects of any UI framework is how it handles user interactions. In this article, we will take a deep dive into euv's event handling system — from inline closures to native event handlers, from input events to form changes, and from the comprehensive list of supported event names to utility functions that simplify common patterns. Table of Contents Inline Closure Events NativeEventHandler Input Events Form Change Events Supported Event Names Accessing Event Data Utility Functions for Event Handling Putting It All Together Inline Closure Events The most straightforward way to handle events in euv is through inline closures. You define the event handler directly within the html! macro using the move |event: Event| { ... } syntax. html! { button { onclick : move | event : Event | { } "Click me" } } This pattern is ideal for simple, self-contained event handlers that don't need to be reused across multiple components. The move keyword ensures that any captured variables (like signals) are moved into the closure, which is essential for the Rust ownership model. Inline closures work with any event type — not just onclick . You can use them for keyboard events, focus events, mouse events, and more. The closure receives an Event object that you can inspect to extract relevant data. NativeEventHandler For more complex scenarios where you need reusable event handlers or want to define handlers outside the html! macro, euv provides the NativeEventHandler type. This allows you to create named, parameterized event handler functions. pub fn counter_on_increment ( counter : Signal < i32 > ) -> NativeEventHandler { NativeEventHandler :: create ( "click" , move | _event : Event | { let current : i32 = counter .get (); counter
开源项目
🔥 Michael-A-Kuykendall / shimmy - ⚡ Pure-Rust WebGPU inference engine — OpenAI-API compatible,
GitHub热门项目 | ⚡ Pure-Rust WebGPU inference engine — OpenAI-API compatible, GGUF native, runs on any GPU. No Python. No llama.cpp. Single binary. | Stars: 5,511 | 29 stars today | 语言: Rust
开源项目
🔥 1jehuang / jcode - Coding Agent Harness
GitHub热门项目 | Coding Agent Harness | Stars: 7,204 | 52 stars today | 语言: Rust
开源项目
🔥 MystenLabs / sui - Sui, a next-generation smart contract platform with high thr
GitHub热门项目 | Sui, a next-generation smart contract platform with high throughput, low latency, and an asset-oriented programming model powered by the Move programming language | Stars: 7,714 | 2 stars today | 语言: Rust
AI 资讯
Article: Designing Continuous Authorization for Sensitive Cloud Systems
Most cloud systems make one authorization decision at login. Everything after runs on trust established at authentication time. For systems handling regulated data, that gap is where breaches happen. This article presents a continuous authorization architecture covering risk-tiered evaluation, behavioral baselines, privacy-preserving audit trails, and a phased and incremental rollout. By Venkata Nedunoori
AI 资讯
How to Build a Multi-Step Agent Stress Test: Adversity Sandboxes and Oracle Checks
Building a prototype of an AI agent is fun. Building a production-ready agent is a nightmare. In a perfect world, your agent always gets the perfect context, the API never fails, and the model never gets "lazy." But in the real world, transient errors are a constant, and models love to take shortcuts. If you aren't testing your agent against the messy reality of production, you’re setting yourself up for failure. This is where our Agent Profiler comes in. We’ve designed it to be an "adversity sandbox." It doesn’t just ask your agent a question; it challenges it. We inject transient runtime errors, introduce "lazy-agent traps" that force the model to stay focused, and validate structural AST matches to ensure the agent is actually outputting what it claims to output. It’s an active testing loop designed to stress-test your agent’s self-recovery mechanics. If your agent can’t handle a little chaos in the test suite, it certainly won’t survive your users.
开源项目
🔥 Start9Labs / start-os - A graphical server OS optimized for self-hosting
GitHub热门项目 | A graphical server OS optimized for self-hosting | Stars: 1,916 | 26 stars today | 语言: Rust
开源项目
🔥 microsoft / windows-rs - Rust for Windows
GitHub热门项目 | Rust for Windows | Stars: 12,425 | 2 stars today | 语言: Rust
AI 资讯
My Polymarket Trading Bot in Rust After TypeScript Kept Missing Fills
A trader I was talking to recently said something that stuck with me: "I've blown accounts just from slow fills or missed order cancellations." He was talking about CEX perpetuals. But the problem is identical on Polymarket's CLOB - just measured in seconds instead of milliseconds. My TypeScript bot was averaging 340ms from signal detection to order placement on Polymarket's Central Limit Order Book. On a 5-minute market with a ~2.7-second mispricing window, that's 12% of the entire opportunity window consumed before a single byte hits Polymarket's servers. I was consistently entering at 74¢ when I'd detected the signal at 70¢. The market had already repriced against me. So I rewrote it in Rust. This article documents exactly what I found, what changed, and - critically - what didn't. Background: What My Bot Was Doing If you've read my earlier posts in this series ( architecture , Kelly Criterion sizing , last-60-seconds capture ), you know the context. But the short version: The bot targets Polymarket's 5-minute and 15-minute crypto up/down binary markets (BTC, ETH, XRP, SOL, DOGE, BNB). The strategy is simple: find markets that are briefly mispriced relative to real-time spot momentum, enter at a discount to fair value, hold to resolution. A 5-minute "XRP Up" market priced at 70¢ when spot momentum suggests 82% probability = +12¢ edge per dollar wagered. Do that 50 times a day with disciplined sizing and the math works - if you can actually get filled at the price you detected. The problem: by the time my TypeScript code detected the signal, formatted the order, opened an HTTP connection to Polymarket's CLOB API, waited for TLS handshake, serialized the payload, and received confirmation, the market had often moved to 74-76¢. I was paying for an edge I wasn't capturing. Profiling the TypeScript Bot: Where Was the 340ms Going? Before rewriting anything, I instrumented every stage of the order path. Here's what I found across 500 sampled trades: Stage Average time %
AI 资讯
The Quantization Audit: Why Leaderboard Scores Lie About Local Agent Capabilities
There is a dangerous trap in the local AI world: picking the smallest quantization that fits into your VRAM just because it "runs." We see developers doing this all the time, completely unaware that they’ve crippled their agent's ability to reason. It’s easy to look at a leaderboard, see a model rank high, and assume it’s good to go. But leaderboard scores are a poor proxy for real-world agent behavior. A model might pass a static benchmark at a lower quantization, but when you put it in an agentic loop, its tool-calling accuracy can fall off a cliff. We built the "Quant Audit" feature in QuantaMind because we were tired of this silent failure. It systematically measures the performance drop-off as you move through different compression levels. The goal shouldn’t be to find the smallest quant that loads; it should be to identify the largest quant that actually retains the reasoning integrity your app requires. Stop guessing, start measuring, and stop letting leaderboard hype dictate your architecture.
AI 资讯
Epic Games Open-Sourced Lore — A Version Control System Built for Massive Game Assets
Epic Games just dropped something that could reshape how game studios handle code and assets. They've open-sourced Lore — a centralized version control system built from the ground up to solve one painful problem: managing enormous binary files alongside source code. This isn't another Git wrapper. It's a completely new VCS, written in Rust, MIT-licensed, and battle-tested behind Fortnite's UEFN (Unreal Editor for Fortnite) toolkit. Why Does the World Need Another VCS? Git is brilliant for text-based code. But game development isn't just text. It's 4K textures, uncompressed audio, rigged 3D models, animation sequences, and massive world maps. These files can be hundreds of megabytes each. Git wasn't designed for this. Git LFS (Large File Storage) helps, but it's a patch on top of a fundamentally text-oriented system. Perforce Helix Core has been the industry standard for game studios for decades — but it's proprietary, expensive, and closed-source. Epic Games looked at this landscape and said: we can do better. What Is Lore? Lore is a centralized, content-addressed version control system optimized for: Large binary assets — textures, meshes, audio, video Massive teams — hundreds of developers working simultaneously Hybrid projects — code + binaries in the same repository Sparse checkouts — developers only download what they need Think of it as Perforce's philosophy (centralized, binary-friendly) combined with Git's content-addressed storage model, wrapped in Rust's performance guarantees. How It Works Under the Hood Lore's architecture is built around a few key technical decisions: Content-Addressed Storage Every piece of data is stored and referenced by its content hash. This means: Automatic deduplication — identical content is stored once Integrity verification — any tampering changes the hash Efficient caching — content can be cached anywhere in the pipeline Merkle Trees & Immutable Revision Chain Revision hashes are cryptographically derived from parent hashes
开源项目
🔥 voidzero-dev / vite-plus - Vite+ is the unified toolchain and entry point for web devel
GitHub热门项目 | Vite+ is the unified toolchain and entry point for web development. It manages your runtime, package manager, and frontend toolchain in one place. | Stars: 5,011 | 19 stars today | 语言: Rust