[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D27GRK37K6K7B3ZXVRHEPF":3,"skill-same:01M6D27GRK37K6K7B3ZXVRHEPF":74},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":50,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M6D27GRK37K6K7B3ZXVRHEPF","systems-rust",null,"Rust done well: ownership and borrowing idioms, error handling with thiserror and anyhow, traits, generics or trait objects, lifetimes, iterators, unsafe with SAFETY proofs and Miri, async with tokio (Send bounds, cancellation, blocking work), shared state and channels, performance habits, clippy and rustfmt, features and MSRV, choosing crates, and cross-compiling. Read when writing or reviewing Rust.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fsystems-rust\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"rust","systems rust","writing","performance","error handling","state","compiling","Safety","work","read","idioms","async","clippy","objects","done","shared","2026-11-10 10:12:30",false,"---\nname: systems-rust\ndescription: \"Rust done well: ownership and borrowing idioms, error handling with thiserror and anyhow, traits, generics or trait objects, lifetimes, iterators, unsafe with SAFETY proofs and Miri, async with tokio (Send bounds, cancellation, blocking work), shared state and channels, performance habits, clippy and rustfmt, features and MSRV, choosing crates, and cross-compiling. Read when writing or reviewing Rust.\"\n---\n\n# Rust, idiomatic and sound\n\nRust on autopilot calls `.clone()` until the borrow checker goes quiet,\n`unwrap()`s every `Result`, returns `Box\u003Cdyn Error>` from a library, wraps\neverything in `Arc\u003CMutex\u003C_>>`, sleeps a thread inside an async task, and\nreaches for `unsafe` to get past a lifetime error. This is the Rust a\nsenior reviewer expects: borrowing by default, typed errors, unsafe with\nproofs, async that cancels cleanly, and the tooling that keeps it so.\nGeneral rules in `systems`, threads and atomics in `systems-concurrency`,\na web service in `backend-stack-rust`.\n\n## 1. Ownership and API shape\n\n- Parameters borrow: `&str` not `&String`, `&[T]` not `&Vec\u003CT>`,\n  `impl AsRef\u003CPath>` for paths. Take `String` or `Vec\u003CT>` only when the\n  function keeps it. Return owned values, or a borrow of `self` for a\n  view; `Cow\u003C'_, str>` when the input usually comes back unchanged.\n- Clone on purpose: an `Arc` or a small `Copy` value is cheap; cloning a\n  `Vec` to satisfy the borrow checker means the data flow is wrong (split\n  the borrow, restructure the loop, use indices).\n- Newtypes carry invariants and units: `UserId(u64)`, `Millis(u64)`,\n  `Name(String)` with a validating `TryFrom`, a private field, no\n  `DerefMut`. `NonZeroU32` gives `Option` a free niche.\n- Builders past three or four optional settings; `#[must_use]` where a\n  result must not be dropped; `#[non_exhaustive]` on public types that\n  will grow; `Debug` always (by hand when a field is secret).\n\n## 2. Errors\n\nLibraries: an error enum per crate or module with `thiserror` 2, variants\na caller can match, sources kept. Binaries: `anyhow` (or `eyre` with\n`color-eyre`), with context on every `?` that crosses a boundary.\n\n```rust\n#[derive(Debug, thiserror::Error)]\n#[non_exhaustive]\npub enum LoadError {\n    #[error(\"reading {path}\")]\n    Io { path: PathBuf, source: std::io::Error },\n    #[error(\"header truncated: need {need} bytes, have {have}\")]\n    Truncated { need: usize, have: usize },\n    #[error(\"unsupported version {0}\")]\n    Version(u16),\n}\n\n\u002F\u002F In the binary, with `use anyhow::Context;`\nlet cfg = load(&path).with_context(|| format!(\"loading config {}\", path.display()))?;\n```\n\n- Messages lowercase, no trailing period, the source's text not repeated:\n  the chain prints it (`{:#}` with anyhow; `{:?}` adds the backtrace\n  under `RUST_BACKTRACE=1`).\n- No `unwrap()` outside tests and invariants proven on the line above;\n  `expect` states the proof (`.expect(\"regex literal is valid\")`);\n  `lock().expect(\"state lock poisoned\")` passes on an earlier panic.\n- Panics are for bugs, never for input; no `Result\u003CT, String>` in a\n  library API; `main` returns `anyhow::Result\u003C()>` or `ExitCode`.\n\n## 3. Traits, generics, trait objects\n\n| Need | Use |\n|---|---|\n| One concrete type per call site, speed matters | `fn run\u003CR: Read>(r: R)` or `fn run(r: impl Read)` |\n| Mixed collection, plug-in chosen at run time | `Box\u003Cdyn Trait>`, `Arc\u003Cdyn Trait + Send + Sync>` |\n| Hide a long return type | `-> impl Iterator\u003CItem = T> + '_` |\n| Only your crate may implement it | sealed: `pub trait Codec: private::Sealed` |\n\n- Generics monomorphise: fast code, bigger binary, slower builds. Keep the\n  generic layer thin over a non-generic inner function\n  (`open(p: impl AsRef\u003CPath>)` calling `open_inner(p.as_ref())`).\n- `dyn` needs a dyn-compatible trait: no generic methods, no `Self` by\n  value, no `async fn` (native `async fn` in traits is for static\n  dispatch; for `dyn`, `async-trait` or a boxed future).\n\n## 4. Lifetimes and iterators\n\n- Trust elision. A struct with a lifetime (`Parser\u003C'a>`) is a short-lived\n  view; types that live long own their data. `T: 'static` means \"owns its\n  data\", not \"lives forever\": for `spawn`, move owned data or an `Arc` in,\n  or borrow with `std::thread::scope`.\n- No self-referential structs: keep the buffer plus `Range\u003Cusize>`\n  indices (`self_cell` if that fails, never hand-written `unsafe`).\n  Graphs: `Vec\u003CNode>` with `u32` or `slotmap` keys, or `Rc` down, `Weak` up.\n- Iterators are lazy and collect once, at the end;\n  `collect::\u003CResult\u003CVec\u003C_>, _>>()` stops at the first error; `retain`,\n  `drain` and `extend` work in place; `zip`, `chunks_exact` and `windows`\n  avoid the bounds checks indexing pays.\n\n## 5. Unsafe\n\n- Justified by FFI, a measured hot path where the compiler cannot prove a\n  bound, or a structure std lacks; never by a lifetime error. One\n  operation per block with a `\u002F\u002F SAFETY:` proof, a `# Safety` section on\n  each `pub unsafe fn`, a safe wrapper around it (`systems`, section 5).\n- The rules that bite: a `&mut T` is unique for its whole life; a\n  reference to uninitialised memory is UB even unread (`MaybeUninit\u003CT>`\n  and `&raw mut` instead); `slice::from_raw_parts` needs a non-null\n  aligned pointer even for length 0; `transmute` between types without a\n  defined layout is UB; `static mut` references are denied in edition 2024.\n\n```sh\nrustup +nightly component add miri\ncargo +nightly miri test\nMIRIFLAGS=\"-Zmiri-strict-provenance\" cargo +nightly miri test\nMIRIFLAGS=\"-Zmiri-many-seeds\" cargo +nightly miri test   # other schedules and addresses\ncargo +nightly careful test                               # std with its debug checks\nRUSTFLAGS=\"-Zsanitizer=address\" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu\n```\n\nMiri is slow and does not run foreign C code: small inputs, and\n`#[cfg_attr(miri, ignore)]` on the tests it cannot run.\n\n## 6. Async with tokio\n\n- `#[tokio::main]` (a worker per core) for servers, `flavor =\n  \"current_thread\"` for CLIs; one runtime, never `block_on` inside it.\n- `tokio::spawn` needs `Send + 'static`. A `std::sync::MutexGuard` or `Rc`\n  alive across `.await` makes the future `!Send`: drop it in a block first\n  (clippy `await_holding_lock`); `tokio::sync::Mutex` only when a lock must\n  be held across an await.\n- Blocking off the workers: CPU work over about 100 microseconds,\n  `std::fs`, blocking C calls and compression go to `spawn_blocking` (or\n  rayon, answering on a `oneshot`). Never `std::thread::sleep`.\n- Cancellation drops the future at its pending `.await`; the rest never\n  runs. `select!` branches must be cancel safe: `mpsc::Receiver::recv`,\n  `TcpListener::accept` and `CancellationToken::cancelled` are;\n  `read_exact`, `read_line` and `write_all` are not.\n- A timeout on every external call (`tokio::time::timeout`); bounded\n  channels (`mpsc::channel(1024)`), `Semaphore` or `buffer_unordered(n)`\n  to cap concurrency. `JoinSet` aborts its tasks on drop; a dropped\n  `JoinHandle` detaches, it does not cancel.\n\nStructured shutdown with `tokio-util` (feature `rt`):\n\n```rust\nlet token = CancellationToken::new();\nlet tracker = TaskTracker::new();\nlet worker_token = token.clone();\ntracker.spawn(async move {\n    loop {\n        tokio::select! {\n            () = worker_token.cancelled() => break,\n            job = rx.recv() => match job {\n                Some(job) => handle(job).await,\n                None => break, \u002F\u002F every sender is gone\n            },\n        }\n    }\n});\ntracker.close();\nshutdown_signal().await; \u002F\u002F Ctrl-C or SIGTERM (`systems-os`)\ntoken.cancel();\nif tokio::time::timeout(Duration::from_secs(20), tracker.wait()).await.is_err() {\n    eprintln!(\"tasks still running after 20s, exiting anyway\");\n}\n```\n\n## 7. Shared state and channels\n\n- Channels first: `std::sync::mpsc::sync_channel(n)` or\n  `crossbeam-channel` between threads; tokio's `mpsc`, `oneshot`, `watch`\n  (latest value) and `broadcast` between tasks.\n- `Arc\u003CMutex\u003CT>>` with short critical sections; `RwLock` only when reads\n  dominate and the mutex measurably contends; `parking_lot` for locks\n  without poisoning; `arc-swap` for read-mostly data replaced whole.\n- Globals: `static CONFIG: OnceLock\u003CConfig>` set once at startup;\n  `static RE: LazyLock\u003CRegex> = LazyLock::new(|| Regex::new(r\"^\\d+$\").expect(\"valid regex\"));`\n  (`once_cell` and `lazy_static` are no longer needed). rayon\n  (`par_iter`, `par_chunks`) for data parallelism.\n\n## 8. Performance habits\n\nMeasure first (`systems`, section 7). What costs nothing:\n\n- No allocation in hot loops: hoist buffers and `clear()` them (capacity\n  stays), `with_capacity(n)`, `write!` into a reused `String` instead of\n  `format!` per item. `SmallVec\u003C[T; N]>` for collections usually under N;\n  `Box\u003Cstr>` or `Arc\u003Cstr>` for strings that never grow.\n- std's SipHash resists hash flooding (keep it for keys an attacker\n  picks); `rustc-hash` or `foldhash` for trusted keys in hot maps.\n- `memchr`, `bytes::Bytes`, `sort_unstable`; `#[inline]` only on small\n  functions called across crates.\n\n```toml\n[profile.release]\nlto = \"fat\"         # or \"thin\" when link time hurts; measure both\ncodegen-units = 1\npanic = \"abort\"     # only when nothing catches panics (not FFI libraries)\n```\n\nProfile a `[profile.profiling]` (`inherits = \"release\"`, `debug =\n\"line-tables-only\"`) with `samply record` or `cargo flamegraph`; count\nallocations with `dhat`; benchmark with criterion (`harness = false`,\ninputs through `std::hint::black_box`). `-C target-cpu=native` only for\nbinaries run where they are built.\n\n## 9. Tooling, lints and crates\n\n```toml\n[lints.rust]\nunsafe_op_in_unsafe_fn = \"deny\"\nunexpected_cfgs = { level = \"warn\", check-cfg = [\"cfg(loom)\"] }\n\n[lints.clippy]\npedantic = { level = \"warn\", priority = -1 }\nmissing_errors_doc = \"allow\"\nundocumented_unsafe_blocks = \"warn\"\n```\n\n- Pedantic on, the lints the team rejects allowed in one place\n  (`[workspace.lints]`, `lints.workspace = true` in members); a local\n  exception says why:\n  `#[expect(clippy::cast_possible_truncation, reason = \"len \u003C 2^16, checked above\")]`.\n- `cargo deny check` (advisories, licences, bans, duplicates, sources)\n  with a committed `deny.toml`; `cargo machete` or `cargo +nightly udeps`\n  for unused dependencies; `cargo nextest run` plus `cargo test --doc`\n  (nextest skips doctests); `cargo semver-checks` before a library release.\n- A new crate earns its place: recent releases and answered issues,\n  reverse dependencies, how much `unsafe` and why, its own tree\n  (`cargo tree -e normal -i \u003Ccrate>`), MSRV, licence. Defaults: `serde`,\n  `postcard`, `thiserror`, `anyhow`, `clap`, `tracing`, `tokio`, `reqwest`,\n  `rustls`, `blake3`, `rayon`, `crossbeam-channel`, `parking_lot`,\n  `bytes`, `memchr`, `winnow`, `proptest`, `insta`, `criterion`.\n\n## 10. Features, MSRV, edition\n\n- Features are additive: enabling one never removes an API or changes\n  behaviour another crate relies on (Cargo unifies them across the graph).\n  Optional dependencies via `dep:`; `cargo hack --feature-powerset check`\n  tests the combinations.\n- MSRV in `rust-version = \"1.85\"`, checked in CI with that toolchain;\n  resolver 3 (default in edition 2024) prefers dependency versions that\n  support it. Raise it on purpose, in a minor release, and say so.\n- Edition 2024 for new crates (`cargo fix --edition`). What needs thought:\n  `unsafe extern` blocks, `#[unsafe(no_mangle)]`, `std::env::set_var` is\n  `unsafe`, return-position `impl Trait` captures every lifetime in scope.\n\n## 11. Cross-compiling and no_std\n\n```sh\nrustup target add aarch64-unknown-linux-gnu x86_64-unknown-linux-musl\ncargo zigbuild --release --target aarch64-unknown-linux-gnu.2.17   # zig links; glibc 2.17 floor\ncross build --release --target aarch64-unknown-linux-gnu           # container toolchain; cross test too\ncargo xwin build --release --target x86_64-pc-windows-msvc          # MSVC target from Linux or macOS\n```\n\n- A bare `cargo build --target` fails on C dependencies (`-sys` crates,\n  `cc`) that need the target's C toolchain; these tools bring it. musl is\n  static but its allocator is slow under threads: add `mimalloc`.\n- `no_std`: `#![cfg_attr(not(feature = \"std\"), no_std)]` with a default\n  `std` feature, `extern crate alloc;` for `Vec` and `String`,\n  `core::error::Error` (stable since 1.81), `#[panic_handler]` in binaries.\n\n## Check it\n\n```sh\ncargo fmt --all --check\ncargo clippy --workspace --all-targets --all-features -- -D warnings\ncargo test --workspace --all-features       # or cargo nextest run, then cargo test --doc\ncargo +nightly miri test                    # unsafe changed\n```\n\nRead the warnings, not only the exit code; every new `#[allow]` or\n`#[expect]` has a reason. Say which of these could not run here.\n\n## Avoid\n\n`clone()` to quiet the borrow checker; `&String` and `&Vec\u003CT>` parameters;\n`unwrap` in library code; `Box\u003Cdyn Error>` or `String` errors from a\nlibrary; lifetimes on long-lived structs; self-referential structs with\n`unsafe`; `unsafe` without `SAFETY`; `static mut`; a std mutex guard across\n`.await`; blocking or `sleep` on the runtime; unbounded channels; external\ncalls without timeouts; tasks nobody owns; features that remove things;\n`target-cpu=native` in distributed builds; a crate for ten lines of code.\n","# Rust, idiomatic and sound\n\nRust on autopilot calls `.clone()` until the borrow checker goes quiet,\n`unwrap()`s every `Result`, returns `Box\u003Cdyn Error>` from a library, wraps\neverything in `Arc\u003CMutex\u003C_>>`, sleeps a thread inside an async task, and\nreaches for `unsafe` to get past a lifetime error. This is the Rust a\nsenior reviewer expects: borrowing by default, typed errors, unsafe with\nproofs, async that cancels cleanly, and the tooling that keeps it so.\nGeneral rules in `systems`, threads and atomics in `systems-concurrency`,\na web service in `backend-stack-rust`.\n\n## 1. Ownership and API shape\n\n- Parameters borrow: `&str` not `&String`, `&[T]` not `&Vec\u003CT>`,\n  `impl AsRef\u003CPath>` for paths. Take `String` or `Vec\u003CT>` only when the\n  function keeps it. Return owned values, or a borrow of `self` for a\n  view; `Cow\u003C'_, str>` when the input usually comes back unchanged.\n- Clone on purpose: an `Arc` or a small `Copy` value is cheap; cloning a\n  `Vec` to satisfy the borrow checker means the data flow is wrong (split\n  the borrow, restructure the loop, use indices).\n- Newtypes carry invariants and units: `UserId(u64)`, `Millis(u64)`,\n  `Name(String)` with a validating `TryFrom`, a private field, no\n  `DerefMut`. `NonZeroU32` gives `Option` a free niche.\n- Builders past three or four optional settings; `#[must_use]` where a\n  result must not be dropped; `#[non_exhaustive]` on public types that\n  will grow; `Debug` always (by hand when a field is secret).\n\n## 2. Errors\n\nLibraries: an error enum per crate or module with `thiserror` 2, variants\na caller can match, sources kept. Binaries: `anyhow` (or `eyre` with\n`color-eyre`), with context on every `?` that crosses a boundary.\n\n```rust\n#[derive(Debug, thiserror::Error)]\n#[non_exhaustive]\npub enum LoadError {\n    #[error(\"reading {path}\")]\n    Io { path: PathBuf, source: std::io::Error },\n    #[error(\"header truncated: need {need} bytes, have {have}\")]\n    Truncated { need: usize, have: usize },\n    #[error(\"unsupported version {0}\")]\n    Version(u16),\n}\n\n\u002F\u002F In the binary, with `use anyhow::Context;`\nlet cfg = load(&path).with_context(|| format!(\"loading config {}\", path.display()))?;\n```\n\n- Messages lowercase, no trailing period, the source's text not repeated:\n  the chain prints it (`{:#}` with anyhow; `{:?}` adds the backtrace\n  under `RUST_BACKTRACE=1`).\n- No `unwrap()` outside tests and invariants proven on the line above;\n  `expect` states the proof (`.expect(\"regex literal is valid\")`);\n  `lock().expect(\"state lock poisoned\")` passes on an earlier panic.\n- Panics are for bugs, never for input; no `Result\u003CT, String>` in a\n  library API; `main` returns `anyhow::Result\u003C()>` or `ExitCode`.\n\n## 3. Traits, generics, trait objects\n\n| Need | Use |\n|---|---|\n| One concrete type per call site, speed matters | `fn run\u003CR: Read>(r: R)` or `fn run(r: impl Read)` |\n| Mixed collection, plug-in chosen at run time | `Box\u003Cdyn Trait>`, `Arc\u003Cdyn Trait + Send + Sync>` |\n| Hide a long return type | `-> impl Iterator\u003CItem = T> + '_` |\n| Only your crate may implement it | sealed: `pub trait Codec: private::Sealed` |\n\n- Generics monomorphise: fast code, bigger binary, slower builds. Keep the\n  generic layer thin over a non-generic inner function\n  (`open(p: impl AsRef\u003CPath>)` calling `open_inner(p.as_ref())`).\n- `dyn` needs a dyn-compatible trait: no generic methods, no `Self` by\n  value, no `async fn` (native `async fn` in traits is for static\n  dispatch; for `dyn`, `async-trait` or a boxed future).\n\n## 4. Lifetimes and iterators\n\n- Trust elision. A struct with a lifetime (`Parser\u003C'a>`) is a short-lived\n  view; types that live long own their data. `T: 'static` means \"owns its\n  data\", not \"lives forever\": for `spawn`, move owned data or an `Arc` in,\n  or borrow with `std::thread::scope`.\n- No self-referential structs: keep the buffer plus `Range\u003Cusize>`\n  indices (`self_cell` if that fails, never hand-written `unsafe`).\n  Graphs: `Vec\u003CNode>` with `u32` or `slotmap` keys, or `Rc` down, `Weak` up.\n- Iterators are lazy and collect once, at the end;\n  `collect::\u003CResult\u003CVec\u003C_>, _>>()` stops at the first error; `retain`,\n  `drain` and `extend` work in place; `zip`, `chunks_exact` and `windows`\n  avoid the bounds checks indexing pays.\n\n## 5. Unsafe\n\n- Justified by FFI, a measured hot path where the compiler cannot prove a\n  bound, or a structure std lacks; never by a lifetime error. One\n  operation per block with a `\u002F\u002F SAFETY:` proof, a `# Safety` section on\n  each `pub unsafe fn`, a safe wrapper around it (`systems`, section 5).\n- The rules that bite: a `&mut T` is unique for its whole life; a\n  reference to uninitialised memory is UB even unread (`MaybeUninit\u003CT>`\n  and `&raw mut` instead); `slice::from_raw_parts` needs a non-null\n  aligned pointer even for length 0; `transmute` between types without a\n  defined layout is UB; `static mut` references are denied in edition 2024.\n\n```sh\nrustup +nightly component add miri\ncargo +nightly miri test\nMIRIFLAGS=\"-Zmiri-strict-provenance\" cargo +nightly miri test\nMIRIFLAGS=\"-Zmiri-many-seeds\" cargo +nightly miri test   # other schedules and addresses\ncargo +nightly careful test                               # std with its debug checks\nRUSTFLAGS=\"-Zsanitizer=address\" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu\n```\n\nMiri is slow and does not run foreign C code: small inputs, and\n`#[cfg_attr(miri, ignore)]` on the tests it cannot run.\n\n## 6. Async with tokio\n\n- `#[tokio::main]` (a worker per core) for servers, `flavor =\n  \"current_thread\"` for CLIs; one runtime, never `block_on` inside it.\n- `tokio::spawn` needs `Send + 'static`. A `std::sync::MutexGuard` or `Rc`\n  alive across `.await` makes the future `!Send`: drop it in a block first\n  (clippy `await_holding_lock`); `tokio::sync::Mutex` only when a lock must\n  be held across an await.\n- Blocking off the workers: CPU work over about 100 microseconds,\n  `std::fs`, blocking C calls and compression go to `spawn_blocking` (or\n  rayon, answering on a `oneshot`). Never `std::thread::sleep`.\n- Cancellation drops the future at its pending `.await`; the rest never\n  runs. `select!` branches must be cancel safe: `mpsc::Receiver::recv`,\n  `TcpListener::accept` and `CancellationToken::cancelled` are;\n  `read_exact`, `read_line` and `write_all` are not.\n- A timeout on every external call (`tokio::time::timeout`); bounded\n  channels (`mpsc::channel(1024)`), `Semaphore` or `buffer_unordered(n)`\n  to cap concurrency. `JoinSet` aborts its tasks on drop; a dropped\n  `JoinHandle` detaches, it does not cancel.\n\nStructured shutdown with `tokio-util` (feature `rt`):\n\n```rust\nlet token = CancellationToken::new();\nlet tracker = TaskTracker::new();\nlet worker_token = token.clone();\ntracker.spawn(async move {\n    loop {\n        tokio::select! {\n            () = worker_token.cancelled() => break,\n            job = rx.recv() => match job {\n                Some(job) => handle(job).await,\n                None => break, \u002F\u002F every sender is gone\n            },\n        }\n    }\n});\ntracker.close();\nshutdown_signal().await; \u002F\u002F Ctrl-C or SIGTERM (`systems-os`)\ntoken.cancel();\nif tokio::time::timeout(Duration::from_secs(20), tracker.wait()).await.is_err() {\n    eprintln!(\"tasks still running after 20s, exiting anyway\");\n}\n```\n\n## 7. Shared state and channels\n\n- Channels first: `std::sync::mpsc::sync_channel(n)` or\n  `crossbeam-channel` between threads; tokio's `mpsc`, `oneshot`, `watch`\n  (latest value) and `broadcast` between tasks.\n- `Arc\u003CMutex\u003CT>>` with short critical sections; `RwLock` only when reads\n  dominate and the mutex measurably contends; `parking_lot` for locks\n  without poisoning; `arc-swap` for read-mostly data replaced whole.\n- Globals: `static CONFIG: OnceLock\u003CConfig>` set once at startup;\n  `static RE: LazyLock\u003CRegex> = LazyLock::new(|| Regex::new(r\"^\\d+$\").expect(\"valid regex\"));`\n  (`once_cell` and `lazy_static` are no longer needed). rayon\n  (`par_iter`, `par_chunks`) for data parallelism.\n\n## 8. Performance habits\n\nMeasure first (`systems`, section 7). What costs nothing:\n\n- No allocation in hot loops: hoist buffers and `clear()` them (capacity\n  stays), `with_capacity(n)`, `write!` into a reused `String` instead of\n  `format!` per item. `SmallVec\u003C[T; N]>` for collections usually under N;\n  `Box\u003Cstr>` or `Arc\u003Cstr>` for strings that never grow.\n- std's SipHash resists hash flooding (keep it for keys an attacker\n  picks); `rustc-hash` or `foldhash` for trusted keys in hot maps.\n- `memchr`, `bytes::Bytes`, `sort_unstable`; `#[inline]` only on small\n  functions called across crates.\n\n```toml\n[profile.release]\nlto = \"fat\"         # or \"thin\" when link time hurts; measure both\ncodegen-units = 1\npanic = \"abort\"     # only when nothing catches panics (not FFI libraries)\n```\n\nProfile a `[profile.profiling]` (`inherits = \"release\"`, `debug =\n\"line-tables-only\"`) with `samply record` or `cargo flamegraph`; count\nallocations with `dhat`; benchmark with criterion (`harness = false`,\ninputs through `std::hint::black_box`). `-C target-cpu=native` only for\nbinaries run where they are built.\n\n## 9. Tooling, lints and crates\n\n```toml\n[lints.rust]\nunsafe_op_in_unsafe_fn = \"deny\"\nunexpected_cfgs = { level = \"warn\", check-cfg = [\"cfg(loom)\"] }\n\n[lints.clippy]\npedantic = { level = \"warn\", priority = -1 }\nmissing_errors_doc = \"allow\"\nundocumented_unsafe_blocks = \"warn\"\n```\n\n- Pedantic on, the lints the team rejects allowed in one place\n  (`[workspace.lints]`, `lints.workspace = true` in members); a local\n  exception says why:\n  `#[expect(clippy::cast_possible_truncation, reason = \"len \u003C 2^16, checked above\")]`.\n- `cargo deny check` (advisories, licences, bans, duplicates, sources)\n  with a committed `deny.toml`; `cargo machete` or `cargo +nightly udeps`\n  for unused dependencies; `cargo nextest run` plus `cargo test --doc`\n  (nextest skips doctests); `cargo semver-checks` before a library release.\n- A new crate earns its place: recent releases and answered issues,\n  reverse dependencies, how much `unsafe` and why, its own tree\n  (`cargo tree -e normal -i \u003Ccrate>`), MSRV, licence. Defaults: `serde`,\n  `postcard`, `thiserror`, `anyhow`, `clap`, `tracing`, `tokio`, `reqwest`,\n  `rustls`, `blake3`, `rayon`, `crossbeam-channel`, `parking_lot`,\n  `bytes`, `memchr`, `winnow`, `proptest`, `insta`, `criterion`.\n\n## 10. Features, MSRV, edition\n\n- Features are additive: enabling one never removes an API or changes\n  behaviour another crate relies on (Cargo unifies them across the graph).\n  Optional dependencies via `dep:`; `cargo hack --feature-powerset check`\n  tests the combinations.\n- MSRV in `rust-version = \"1.85\"`, checked in CI with that toolchain;\n  resolver 3 (default in edition 2024) prefers dependency versions that\n  support it. Raise it on purpose, in a minor release, and say so.\n- Edition 2024 for new crates (`cargo fix --edition`). What needs thought:\n  `unsafe extern` blocks, `#[unsafe(no_mangle)]`, `std::env::set_var` is\n  `unsafe`, return-position `impl Trait` captures every lifetime in scope.\n\n## 11. Cross-compiling and no_std\n\n```sh\nrustup target add aarch64-unknown-linux-gnu x86_64-unknown-linux-musl\ncargo zigbuild --release --target aarch64-unknown-linux-gnu.2.17   # zig links; glibc 2.17 floor\ncross build --release --target aarch64-unknown-linux-gnu           # container toolchain; cross test too\ncargo xwin build --release --target x86_64-pc-windows-msvc          # MSVC target from Linux or macOS\n```\n\n- A bare `cargo build --target` fails on C dependencies (`-sys` crates,\n  `cc`) that need the target's C toolchain; these tools bring it. musl is\n  static but its allocator is slow under threads: add `mimalloc`.\n- `no_std`: `#![cfg_attr(not(feature = \"std\"), no_std)]` with a default\n  `std` feature, `extern crate alloc;` for `Vec` and `String`,\n  `core::error::Error` (stable since 1.81), `#[panic_handler]` in binaries.\n\n## Check it\n\n```sh\ncargo fmt --all --check\ncargo clippy --workspace --all-targets --all-features -- -D warnings\ncargo test --workspace --all-features       # or cargo nextest run, then cargo test --doc\ncargo +nightly miri test                    # unsafe changed\n```\n\nRead the warnings, not only the exit code; every new `#[allow]` or\n`#[expect]` has a reason. Say which of these could not run here.\n\n## Avoid\n\n`clone()` to quiet the borrow checker; `&String` and `&Vec\u003CT>` parameters;\n`unwrap` in library code; `Box\u003Cdyn Error>` or `String` errors from a\nlibrary; lifetimes on long-lived structs; self-referential structs with\n`unsafe`; `unsafe` without `SAFETY`; `static mut`; a std mutex guard across\n`.await`; blocking or `sleep` on the runtime; unbounded channels; external\ncalls without timeouts; tasks nobody owns; features that remove things;\n`target-cpu=native` in distributed builds; a crate for ten lines of code.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Fsystems-rust",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add enowdev\u002Fenowxcli --skill systems-rust",{"tool":60,"command":61},"bunx","bunx skills add enowdev\u002Fenowxcli --skill systems-rust",{"tool":63,"command":64},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill systems-rust","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fsystems-rust\u002FSKILL.md",true,[68],{"path":69,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":73},"scripts\u002Fvalidate-force-link.js","SCRIPT","脚本",2818,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fpower-pages\u002Fskills\u002Fforce-link-environment\u002Fscripts\u002Fvalidate-force-link.js",[75,91,113,129,154,176],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":86,"publishedAt":40},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[81],{"categoryNo":82,"categoryName":83,"taxonomyType":84,"taxonomyTypeDesc":85},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[87,88,89,90,33],"demo skill","demo","tests","project",{"skillNo":92,"name":26,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":102,"publishedAt":40},"01M6D2HM0GCPM0TM2HPG9HHR2R","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[96,99],{"categoryNo":97,"categoryName":98,"taxonomyType":84,"taxonomyTypeDesc":85},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":100,"categoryName":101,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000036","内容创作者",[26,103,104,105,106,107,33,108,109,110,111,112],"text","emails","empty","drop","document","page","voice","notifications","documentation","translate",{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":122,"publishedAt":40},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[119],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000032","设计师",[115,123,124,125,126,108,127,33,128],"icons","components","SET","responsive","layout","before building",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":139,"publishedAt":40},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[135,138],{"categoryNo":136,"categoryName":137,"taxonomyType":84,"taxonomyTypeDesc":85},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[115,140,141,142,143,144,145,146,147,33,128,148,108,149,150,151,123,152,153],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","code","Charts","content","screenshots","logo",{"skillNo":155,"name":156,"nameZh":6,"description":157,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":158,"categories":159,"keywords":163,"publishedAt":40},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[160,161,162],{"categoryNo":97,"categoryName":98,"taxonomyType":84,"taxonomyTypeDesc":85},{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":100,"categoryName":101,"taxonomyType":21,"taxonomyTypeDesc":22},[164,115,165,124,166,167,149,168,169,170,127,143,171,172,173,33,128,108,174,175],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":177,"name":178,"nameZh":6,"description":179,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":180,"categories":181,"keywords":189,"publishedAt":40},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[182,185,188],{"categoryNo":183,"categoryName":184,"taxonomyType":84,"taxonomyTypeDesc":85},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":186,"categoryName":187,"taxonomyType":84,"taxonomyTypeDesc":85},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},[115,190,191,192,193,194,195,196,127,90,197,198,33,199,200,201,202,203,204,205],"vue","stack","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","config","directory","testing"]