今日已更新 158 条资讯 | 累计 37407 条内容
关于我们

标签:#Rust

找到 450 篇相关文章

AI 资讯

[Advanced Rust] 1.13. Memory Types Pt.1 - Alignment, Layout, and the Repr Attribute

1.13.1. The Basic Responsibility of Types Every Rust value has a type, and the responsibility of that type is to tell you how to interpret the bits in memory. For example, the bit pattern 0b10111101 has no meaning by itself, but: Interpreted as u8 , it becomes the number 189 Interpreted as i8 , it becomes the number -67 When you define a custom type, the compiler decides where each part of that type is placed in memory. 1.13.2. Alignment Alignment determines where a type’s bytes may be stored. Once a type’s representation is determined, you might think it can be stored anywhere in memory. In theory that is possible, but in practice computer hardware places constraints on where a given type can live. The most typical example is a pointer. A pointer points to bytes, not bits; one byte equals 8 bits. In other words, it does not point to an individual bit. So if a value of some type were placed at bit index 4 in memory, you would not be able to address it, because pointers address bytes rather than specific bits. That is why alignment is done at the byte level — that is, at 8-bit boundaries. For this reason, all values, regardless of type, must begin on a byte boundary . All types must be at least byte-aligned. In other words, the storage address must be a multiple of 8 bits. 1.13.3. Stricter Alignment Rules Some types have alignment requirements stricter than byte alignment. In CPU and memory systems, memory is often accessed in blocks larger than a single byte. For example, on a 64-bit CPU, most values are accessed in 8-byte blocks, and each operation begins at an address that is 8-byte aligned . This is also called the CPU word size. Of course, CPUs can also handle reads and writes of smaller values, as well as values that cross block boundaries. But as developers, we should try our best to ensure that hardware operates at its native alignment. For example, if the i64 value you want to read begins in the middle of an 8-byte block, then reading it requires at least tw

2026-07-29 原文 →
AI 资讯

The Bug I Never Wrote: What Testing Failure Taught Me About Solana

100 Days of Solana, Day 100 Where I started I'd built REST APIs for years but had never touched a blockchain, or written a line of Rust. The curiosity how blockchain works, started my curiosity. What I expected I came in with a Web2 instinct: tests exist to prove your code does what it's supposed to do. Write the function, write a test that calls it, watch it pass, move on. A "failing test" was something you fixed, not something you shipped on purpose. What changed my understanding The moment this cracked open was building the capstone: a small Anchor program called proof-of-ship that lets a wallet permanently record, on chain, that it shipped something. The rule is simple — one ship record per wallet, forever. The rule lives entirely in the account's seeds: seeds = [ b"ship" , builder .key () .as_ref ()], bump Each wallet's record lives at one deterministic address. Try to create a second one, and init refuses, because an account already exists there. I wrote two tests. The first proved the happy path: call ship() , fetch the record, confirm the name and builder match. The second test is the one that changed how I think about testing: it ( " only lets each wallet ship once " , async () => { let rejected = false ; try { await program . methods . ship ( " Second try " , " This should never land " ). rpc (); } catch ( _err ) { rejected = true ; } assert . isTrue ( rejected , " second ship should have been rejected " ); }); This test isn't checking for a bug. It's checking that a rule holds. There's no function in my program called preventDuplicateShip() . There's no if statement rejecting the second attempt. The rule "one ship per wallet" isn't enforced by logic I wrote — it's enforced by the Solana runtime itself, because the PDA's address already has data in it. My job wasn't to write the rejection. My job was to prove the rejection actually happens. What I understand now On Web2 systems I controlled the whole stack, so "does it work" mostly meant "does the happy pa

2026-07-28 原文 →
AI 资讯

I Tried Topcoat: Rust’s New Full-Stack Web Framework

Rust web development just got more interesting. If you prefer a video version: A few days ago, I spoke with Carl Lerche and Julien Scholz about Topcoat , a new batteries-included framework for building full-stack reactive web applications with Rust. Now I have finally tried it myself. Topcoat comes from the ecosystem behind Tokio and Axum, but it aims to provide a very different experience: routing, server-side rendering, reactive components, UI tooling, asset bundling, and hot reload in one framework. A simple Topcoat application This is what a basic application looks like: use topcoat ::{ Result , router ::{ Router , RouterBuilderDiscoverExt , page }, view ::{ component , view }, }; #[tokio::main] async fn main () { topcoat :: start ( Router :: builder () .discover () .build ()) .await .unwrap (); } #[page( "/" )] async fn home () -> Result { view! { <! DOCTYPE html > < html > < body > hello ( name : "World" ) </ body > </ html > } } #[component] async fn hello ( name : & str ) -> Result { view! { < h1 > "Hello, " ( name ) "!" </ h1 > } } The syntax feels surprisingly familiar if you have used server-rendered frameworks before. Pages and components are written in Rust, while the view! macro keeps the HTML structure easy to understand. What surprised me My first experience was better than expected. The setup was simple, the basic example was actually basic, and the development server provided working hot reload. That last part may sound normal to JavaScript developers, but it makes a huge difference for the Rust developer experience. Topcoat includes or plans to support: Server-side rendering Reactive components Module-based routing Tailwind integration Reusable UI components Asset bundling Fonts and icons Cookies and sessions Database integrations The experience feels closer to frameworks such as Laravel, Django, Rails, or Next.js, while allowing developers to build the application in Rust. Is Topcoat ready for production? Topcoat is still at an early stage. Break

2026-07-28 原文 →
AI 资讯

[Advanced Rust] 1.12. Lifetimes (Advanced) Pt.2 - Lifetime Variance, Covariance, Invariance, Contravariance

1.12.1. Lifetime Variance Variance is a concept in Rust’s type system. It describes how generic parameters — especially lifetime parameters — relate to one another in the type hierarchy. We can think of it simply as variance describes which types are “subtypes” of other types , where “subtype” is somewhat similar to the concept used in Java and C#. In addition, variance also cares about when a “subtype” can replace a “supertype” and vice versa . In general, if A is a subtype of B, then A is at least as useful as B. Here is a Rust example: if a function takes &'a str , then &'static str can be passed in. Because 'static is a subtype of 'a , 'static lives at least as long as any 'a (and 'static can remain valid for the entire program). 1.12.2. Three Kinds of Lifetime Variance All types have variance. The variance associated with each type defines which similar types can be used in that type’s position. Note: the following content is fairly difficult. It is recommended that you first recall the ideas of sufficient conditions and necessary conditions from high school math. 1. Covariant Covariant means that a type can be replaced only by a “subtype.” Covariance means: if A <: B (A is a subtype of B), then F<A> <: F<B> (F<A> is also a subtype of F<B>) This is a transitive inheritance relationship from smaller to larger , similar to reasoning from a sufficient condition : if A holds, then B must also hold (A is a sufficient condition for B). For example, &'static T can replace &'a T , because &T is covariant over the lifetime 'a , so 'a can be replaced by one of its subtypes, such as 'static . 2. Invariant Invariant means that you must provide the exact specified type. Invariance means: A <: B cannot imply F<A> <: F<B>, and F<B> <: F<A> also cannot be inferred This means there is not enough relationship between F<A> and F<B> to derive one from the other, so they are neither sufficient conditions nor necessary conditions ; they are independent. For example, the mutable refe

2026-07-28 原文 →
AI 资讯

[Advanced Rust] 1.11. Lifetimes (Advanced) Pt.1 - Review, Borrow Checker, Generic Lifetimes

1.11.1. Review In the beginner tutorial, we mentioned that every reference in Rust has a lifetime. A lifetime is the scope in which the reference remains valid, and in most cases it is implicit and inferred by the compiler. When you take a reference to a variable, the lifetime begins. When the variable is moved or goes out of scope, the lifetime ends. In other words, for a reference, a lifetime is the name of the code region in which it must remain valid. Lifetimes usually overlap with scopes, but not always. 1.11.2. Borrow Checker Whenever a reference with some lifetime 'a is used, the borrow checker checks whether 'a is still alive. The process is: Trace the path back to where 'a began — that is, where the reference was obtained From there, check whether there are conflicts along that path Ensure that the reference points to a value that can be accessed safely This example uses the rand crate. Add the following dependency to Cargo.toml : [dependencies] rand = "0.8" Consider this example: use rand :: random ; fn main () { let mut x = Box :: new ( 42 ); let r = & x ; if random :: < f32 > () > 0.5 { * x = 84 ; } else { println! ( "{}" , r ); } } x is of type Box<i32> Declaring r as a reference to x means the reference’s lifetime begins on that line (line 5) On line 7, the value of x is modified through dereferencing. That requires a mutable reference to x . At this point, the borrow checker looks for a mutable reference to x and checks whether its use conflicts with anything else. In this example there is no conflict, so the code is valid You may ask: line 7 is inside the scope of r . Since *x needs a mutable reference to x , shouldn’t having both the immutable reference r and the mutable reference *x in the same scope violate the borrowing rules and produce an error? In fact, Rust is smart enough to know that if the if branch is taken, the else branch cannot be taken. r is never used in the if branch at all, so using the mutable reference *x in the if branch is fine

2026-07-28 原文 →
AI 资讯

How to achieve zero-copy streaming from hyper and h3-quinn into a Wasmtime Wasm component via wasi:http?

Hello everyone, I am currently building a high-performance API gateway that integrates business logic components—implemented via WASI and running within Wasmtime—as HTTP/TCP/QUIC handlers. I am exploring the best design approach to achieve a zero-copy data path from the upstream network layer—specifically hyper for HTTP/1.x and HTTP/2, and h3-quinn (based on Quinn) for HTTP/3—to the wasi:http guest environment. Given that: hyper and h3-quinn each manage their own internal buffer pools (e.g., bytes::Bytes ), asynchronous read/write streams, and frame decoders. Wasmtime's wasmtime-wasi-http implements the wasi:http (WASIp2) specification, which relies on resource types such as InputStream and OutputStream . I aim to minimize memory copying and CPU overhead when passing large request bodies or streaming responses across the sandbox boundary. For those experienced with bridging I/O between the host and guest in Wasmtime, I have a few architectural questions: Buffer ownership and memory mapping: How can host-side bytes::Bytes (from hyper or h3-quinn ) be mapped or bridged into Wasm linear memory (and vice versa) without requiring a CPU-based memcpy ? Does Wasmtime's resource streaming support direct memory views, or are we essentially limited to copying data chunks via guest memory pointers? Adapting stream abstractions: hyper uses http_body_util::combinators / http_body::Body , h3 uses its own stream primitives, while wasi:http uses wasi:io/streams . What is the idiomatic way to efficiently adapt these asynchronous streams on the host side (i.e., within the wasmtime-wasi-http handler implementation) without blocking the tokio runtime? Backpressure propagation: How can backpressure signals be correctly propagated from the Wasm guest (e.g., when the guest's InputStream is consuming data slowly) all the way back to the Quinn congestion controller or Hyper connection pool, thereby avoiding unbounded buffering on the host side? If anyone has built similar high-performance ga

2026-07-27 原文 →
AI 资讯

Building a browser game with client-side Groth16 proofs

A smart contract can't tell whether a submitted score came from a valid game or was simply made up. Dario Dash handles that by proving the run itself. I have been building Dario Dash , a small endless runner on Dusk. The game runs in the browser and does not require a wallet to play. After a ranked run, the browser can generate a Groth16 proof locally and submit the score to a smart contract. The contract does not trust the submitted score. It accepts it only after verifying the proof, binding it to the transaction sender and checking that the run seed has not already been used. The source is available on GitHub . What actually needs to be proven? A score by itself says almost nothing. A client could simply submit any number it wants. For Dario Dash, a valid run includes much more than the final score: the player movement and jump timing the seed-derived obstacle schedule obstacle clearance and collision windows item pickups damage and game-over conditions fireball kills transitions between Regular, Super, Fire and Cape forms the number of ticks played the resulting score The proof must establish that these rules were followed from the initial state until the claimed final state. It also needs to bind the run to the account submitting it, otherwise somebody could copy another player's proof. The architecture The repository is split into a few layers: dash_zk contains the deterministic game simulation used by the browser proving path. dash_core contains a separate 60 Hz simulation used by the RISC Zero path. dash_web exposes the Rust simulation to the browser through WebAssembly. zk_browser contains the Circom circuit and the JavaScript proof conversion code. contract verifies the proof and maintains the leaderboard on Dusk. web contains the playable Vite application. The important boundary is that the game logic is deterministic and integer-only. Floating point physics would be a mess to reproduce consistently across JavaScript, WebAssembly, the proof circuit and th

2026-07-27 原文 →
AI 资讯

AgentOS: a Rust runtime for AI agents with deterministic time-travel replay

Most agent frameworks help you build a workflow. The harder part starts after that: the workflow has to run as a long-lived process, fail clearly, restart carefully, and be inspectable after the fact. That's the gap I'm building AgentOS for — an open-source, Rust-first runtime layer that sits underneath frameworks like LangGraph, AutoGen or CrewAI instead of replacing them. What one process gives you cargo run -p agentos-cli -- run --agent examples/simple_agent.toml That single command brings up a supervised agent, a health endpoint, a gRPC message bus, a live SSE event stream, and a recorded trace you can replay later. No API key is needed just to bring the runtime up. Time-travel debugging Your agent does something weird on step 7. Reproducing it costs real API calls, and it never behaves the same way twice. AgentOS journals every LLM exchange and tool result at the provider boundary, so any run can be replayed deterministically — and forked into alternate timelines: agentOS run --agent my_agent.toml # every step journaled automatically agentOS replay --session agent_123 # offline re-run, no API cost, drift-checked agentOS fork --from ckpt_4 --prompt "try the other path" The dashboard's Recordings view turns those journals into a scrubbable timeline: step through the prompt, each exchange, tool calls and their results, with per-exchange checkpoints as fork anchors. What's inside crates/kernel — lifecycle, agent handles, supervisor crates/bus — in-memory, gRPC, SSE and WebSocket messaging crates/trace — recording, replay, diff, checkpoint model crates/vault — secret isolation, encryption, scopes, audit crates/memory , crates/registry , crates/llm , crates/cli , crates/sdk dashboard/ — React debugging surface Where it honestly stands Stable enough for local use: the run / ps / logs / trace / replay CLI flows, local state inspection, export and import, and the core crates with workspace checks and tests. Still experimental: the dashboard, the WASM plugin runtime, Doc

2026-07-27 原文 →
AI 资讯

Building a desktop client for an AI coding agent

Lessons from wrapping grok-build — the architecture, the traps, and why we picked Tauri over Electron. TL;DR grok-build is xAI's open-source Rust coding agent. It ships as a TUI. We wrote a native desktop client for it — Tauri 2 (~8 MB binary), React frontend, Rust runtime that spawns the CLI as a child process and talks to it over ACP/JSON-RPC 2.0. This post is the architecture deep-dive: how the pieces fit together, what surprised us, and the parts we'd build differently next time. The full source is at github.com/timexingxin/grok-gui . MIT-licensed. Demo GIF in the README. The problem grok-build is genuinely good at code work — comparable to Claude Code for my workflow. But it ships as a Rust TUI. After six months of cmd+tab between the terminal and my browser tabs, I wanted a real desktop UX without losing what makes the CLI good. The naive options all had problems: Wrap it as a tmux session in a webview. Doesn't help — you're still reading scrollback. Use a community-built web wrapper. They all wrap the OpenAI Chat Completions API directly. They don't talk to the actual agent runtime, so they miss tool calls, plan updates, permission requests, and the streaming event surface that makes coding agents feel responsive. Write a desktop GUI from scratch. Means re-implementing the agent loop, the model integration, the tool calling. Six months of work, plus the resulting client would always lag the upstream. The right answer was staring at me: grok-build already has a JSON-RPC 2.0 over stdio interface called the Agent Client Protocol (ACP). That's the protocol I should be a client of. My job is just to write the client. What is ACP? ACP is a JSON-RPC 2.0 protocol that coding-agent CLIs expose over their stdin/stdout. The agent emits notifications (text deltas, tool calls, plan updates, permission requests, session lifecycle); the client sends requests (user prompts, permission responses, model switches, session loads). If your agent speaks ACP, you can write a client

2026-07-26 原文 →
AI 资讯

Creating my own shell for unix

Building Astra: A Modern Shell in Rust I've been working on a personal project called Astra , an interactive shell written in Rust. The goal isn't to replace every existing shell overnight. Instead, I'm building a clean, modular foundation that's easy to understand, extend, and contribute to. Some of the features currently in development include: Interactive shell loop Customizable prompt system TOML-based configuration Built-in themes Git-aware prompt Command history Tab completion Alias support Plugin framework (early development) Alongside the shell itself, I'm also putting together the surrounding ecosystem—documentation, packaging, examples, tests, and GitHub automation—so contributors have a solid starting point. This project has been a chance to learn more about Rust, shell design, and how larger open-source projects are organized. It's still early, but it's reached the point where the foundation is in place and I'm beginning to focus on expanding features, improving reliability, and increasing test coverage. Check out the project here: astra-shell / astra-shell A custom shell for mac OS! █████████████░░░░░░░░ 65% Astra Shell A modern shell built in Rust for Unix-like systems, with macOS as the primary development platform. Astra is an interactive command-line environment focused on a clean interface, customization, and a better terminal experience. It combines the power of traditional Unix shells with a modern prompt system, configuration, and extensibility. Warning Astra Shell has not gone through extensive testing yet. Wait until the first stable release before using it as your primary shell. Table of Contents Features Screenshots Installation Requirements Usage Themes Why Astra? Contributing License Status Features Interactive Rust shell Configurable prompt engine Multiple built-in themes Git-aware prompt information Command history Tab completion Alias support TOML configuration Built-in shell commands Modular architecture Plugin framework (in developmen

2026-07-26 原文 →
AI 资讯

Two coding agents editing the same issue, no merge conflict. Here is how git refs make that work

Run two AI coding agents on the same repo and the first thing that breaks is not the code. It is coordination. Agent A starts refactoring auth. Agent B, running in parallel, has no idea and starts the same thing. Neither remembers what it did last session, because each one boots fresh with an empty context window. The usual fixes are worse than the problem: a state file in the repo pollutes every diff and conflicts on merge, and an external issue tracker means API tokens, rate limits, and a hard dependency on the network for something that should be local. So I built grite : an issue tracker that lives inside your git repository as an append-only event log, with deterministic CRDT merging so two writers never conflict. No server. No database. No merge conflicts. Just git. The core idea: issues are events, git refs are the log Grite does not store issues as files in your working tree. It stores them as an append-only write-ahead log inside a git ref, refs/grite/wal . Every action, a create, a comment, a label change, is one immutable CBOR-encoded event appended to that log. Your working tree stays completely clean. The only tracked file grite ever writes is AGENTS.md , and that is on purpose, so agents discover the tool automatically. Because the state lives in a git ref, it travels with your code. It branches when you branch. It merges when you merge. It syncs when you git push . If you can push to a remote, you can sync issues. There is no new account, no new infrastructure, no new protocol to learn. How it works Three layers, cleanly separated. The git WAL is the source of truth. Events are appended as CBOR chunks, each identified by a content-addressed EventId that is a BLAKE2b hash of the event body. Content addressing is what makes the log tamper-evident: change one byte of an event and its ID no longer matches, which breaks the chain. Signing is optional Ed25519 per event, so you can prove which actor created what. The materialized view is a sled embedded key-

2026-07-25 原文 →