Skip to main content

multi/
multi.rs

1// Copyright (C) 2026 Kan-Ru Chen <kanru@kanru.info>
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5use scoped_error::{Many, expect_error_fn};
6use std::{error::Error, thread};
7
8fn fetch_all(urls: Vec<String>) -> Result<Vec<String>, Many> {
9    let handles: Vec<_> = urls
10        .into_iter()
11        .map(|url| thread::spawn(move || fetch(&url)))
12        .collect();
13
14    let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
15
16    Many::from_results("failed to fetch URLs", results)
17}
18
19fn fetch(url: &str) -> Result<String, scoped_error::Error> {
20    let err = || scoped_error::Error::new(format!("failed to fetch {}", url));
21
22    expect_error_fn(err, || {
23        connect(url)?;
24        Ok("connected".into())
25    })
26}
27
28fn connect(url: &str) -> Result<String, scoped_error::Error> {
29    let err = || scoped_error::Error::new(format!("failed to connect to {}", url));
30
31    expect_error_fn(err, || Err("no network connection")?)
32}
33
34fn main() -> Result<(), Box<dyn Error>> {
35    fetch_all(vec![
36        "https://example.com".to_string(),
37        "https://example.org".to_string(),
38    ])?;
39    Ok(())
40}