You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
chore: replace unwrap calls with safer alternatives
This replaces calls to `unwrap()` across the crate with safer alternatives.
Some patterns observed + updated include:
1. Replacing `is_some() + unwrap()` with `if let Some()`.
```
// Before:
if bios.usb_boot.is_some() {
let val = bios.usb_boot.unwrap();
// Do something with val.
}
// After:
if let Some(val) = bios.usb_boot {
// Do something with val.
}
```
2. Replacing `is_some() + `clone().unwrap() == "value"` with `as_deref() == Some("value")`.
```
// Before:
if bios.usb_boot.is_some() && bios.usb_boot.clone().unwrap() == "Disabled"
// After (note we can also drop the clone):
if bios.usb_boot.as_deref() == Some("Disabled")
```
3. Replacing `partial_cmp().unwrap()` with `cmp()`.
Since `Option<String>` implements `Ord`, we can use `cmp()` and not need `partial_cmp().unwrap()`.
```
// Before:
devices.sort_unstable_by(|a, b| a.manufacturer.partial_cmp(&b.manufacturer).unwrap());
// After:
devices.sort_unstable_by(|a, b| a.manufacturer.cmp(&b.manufacturer));
```
4. Improving `unwrap()` operations that are fallible.
We had a number of places where we were just unwrapping options without
any error checking at all. This now returns an error with a useful error
message in said cases.
```
// Before:
let system_id = systems.first().unwrap();
// After:
let system_id = systems.first().ok_or_else(|| RedfishError::GenericError {
error: "No systems found in service root".to_string(),
})?;
```
5. Improving `unwrap()` operations that are considered infallible.
So even for operations we'd consider infallible, like setting the MIME type
on an HTTP request, or having our statically compiled regex, we should
still properly have an error check in there instead of blindly unwrapping.
```
// Before:
.mime_str("application/json").unwrap()
// After:
.mime_str("application/json")
.map_err(|e| RedfishError::GenericError {
error: format!("Invalid MIME type 'application/json': {}", e),
})?
```
0 commit comments