QueryIteratorExt.matching
Lazily yield candidates accepted by matcher.
Source and package
- Qualified name
-
libtmux::query:: Query Iterator Ext:: matching - Module
- query
- Declared in
QueryIteratorExt- Package
- libtmux
- Source
- crates/libtmux/src/query.rs
-
Examples
use libtmux::query::{Matcher, QueryIteratorExt};struct IsEven;impl Matcher<i32> for IsEven {fn matches(&self, candidate: &i32) -> bool {candidate % 2 == 0}}let values = [1, 2, 3, 4];let selected = values.iter().matching(IsEven).copied().collect::<Vec<_>>();assert_eq!(selected, [2, 4]);Filter snapshots with typed fields. Match a session name prefix without changing the source snapshot. Use Rust 1.85 or newer with Cargo, and tmux 3.3a or newer, on a Unix system. In an empty directory, create a project and add the published crates:
Terminal window $ cargo init --name libtmux-api-example &&cargo add libtmux@0.1.2 tempfile@3.20 &&cargo add tokio@1.40 --features macros,rt,timeReplace
src/main.rswith this complete program. It owns a private tmux socket, applies a ten-second task deadline, and reports both task and cleanup errors.Server::kill()stops its daemon;Server::shutdown()closes its client executor. Successful cleanup removes the temporary directory even when the task fails. View sourcesrc/main.rsComplete program //! Filter native snapshots with typed field expressions.use std::error::Error;use std::time::Duration;use libtmux::query::{Filterable as _, QueryIteratorExt as _};use libtmux::{NewSessionOptions, Server, Session};type ExampleError = Box<dyn Error>;fn check(condition: bool, message: &str) -> Result<(), ExampleError> {if condition {Ok(())} else {Err(message.into())}}async fn demonstrate(server: &Server) -> Result<(), ExampleError> {server.new_session(NewSessionOptions::new("prod-api").command("cat")).await?;server.new_session(NewSessionOptions::new("dev-api").command("cat")).await?;let sessions = server.sessions().await?;let fields = Session::filter_fields();let production = fields.session_name.starts_with("prod-");let selected = sessions.iter().matching(&production).exactly_one()?;check(selected.name().as_bytes() == b"prod-api","wrong filtered session",)?;check(sessions.len() == 2, "filtering changed the source snapshot")?;println!("query: prod-api");Ok(())}#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), ExampleError> {let root = std::path::Path::new("/tmp/libtmux-rs-dev");std::fs::create_dir_all(root)?;let directory = tempfile::Builder::new().prefix("api-query-").tempdir_in(root)?;std::fs::write(directory.path().join("owner"),std::process::id().to_string(),)?;let server = Server::builder().socket_path(directory.path().join("tmux.sock")).config_file("/dev/null").default_timeout(Duration::from_secs(5)).build()?;let outcome = tokio::time::timeout(Duration::from_secs(10), demonstrate(&server)).await;// Stop the owned daemon before closing the client executor.let killed = server.kill().await;let closed = server.shutdown().await;let cleanup_failed = killed.is_err() || closed.is_err();let mut failures = Vec::new();match outcome {Ok(Ok(())) => {}Ok(Err(error)) => failures.push(format!("example failed: {error}")),Err(error) => failures.push(format!("example deadline: {error}")),}if let Err(error) = killed {failures.push(format!("daemon cleanup: {error}"));}if let Err(error) = closed {failures.push(format!("executor cleanup: {error}"));}if cleanup_failed {let retained = directory.keep();failures.push(format!("inspect retained directory {}", retained.display()));} else if let Err(error) = directory.close() {failures.push(format!("directory cleanup: {error}"));}if failures.is_empty() {Ok(())} else {Err(failures.join("; ").into())}}Run the consumer. Success exits with status 0; setup, operation, deadline or cleanup failures exit unsuccessfully and print diagnostics to stderr:
Terminal window $ cargo run --quietExpected output:
query: prod-api
Same owner
containment 1 of 4 shownOther members of query.QueryIteratorExt whose names share matching. They sit on the same type; that does not make them behave alike.
Recorded calls
source callsThe Rust reference records declarations, not calls, so this page shows no callers or callees. That is a limit of the extracted data, not a statement that nothing calls query.QueryIteratorExt.matching.
Guides
task materialPages that discuss matching.