I've got the following code
pub fn list_devices(&self) -> Result<Vec<MyDevice>, MyError> {
let mut results = Vec::new();
for driver in &self.drivers {
let serial_numbers = driver.list_serial_numbers()?;
for serial in serial_numbers {
results.push(MyDevice::new(driver.clone(), &serial)?);
}
}
Ok(results)
}
However, both driver.list_serial_numbers() and MyDevice::new() can take seconds to return and doing all this long-running work in sequence can take a long time. I'd like to take advantage of rayons par_iter to do both iterations in parallel, but as per the above code, I'd like to return an error if any result in failure.
So far, I've come up with the following code which works but does not handle errors correctly. I need to remove the usages of unwrap and I know that flatten() is also ignoring errors so that needs replacing with something else too...
pub fn list_devices(&self) -> Result<Vec<MyDevice, MyError>> {
Ok(self
.drivers
.par_iter()
.map(|driver| -> Vec<MyDevice> {
driver
.list_serial_numbers()
.unwrap()
.par_iter()
.map(|serial| MyDevice::new(driver.clone(), serial).unwrap())
.collect()
})
.flatten()
.collect())
}