style: improve use of std api

- replace get(0) by first()
lint message: accessing first element with `objs.get(0)`
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#get_first
- use io::Error::other method available since Rust 1.87
lint message: this can be `std::io::Error::other(_)`
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#io_other_error
- implement From<_> instead of Into<_>
lint message: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
help: `impl From<Local> for Foreign` is allowed by the orphan rules, for more information see
            https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#from_over_into
- use next_back instead of rev + next
lint message: manual backwards iteration
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#manual_next_back
- use saturating_sub instead of manual implement it
lint message: manual arithmetic check found
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#implicit_saturating_sub
- add Default implementation for Checksummer
use derived Default ans use it in new, as new set all value to None
lint message: you should consider adding a `Default` implementation for `Checksummer`
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#new_without_default
- use `any` instead of `find` + `is_some`
lint message: called `is_some()` after searching an `Iterator` with `find`
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#search_is_some
- replace `and_then` + `Some(_)` with `map`
lint message: using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#bind_instead_of_map
- replace `skip_while` + `next` with `find`
lint message: called `skip_while(<p>).next()` on an `Iterator`
help: this is more succinctly expressed by calling `.find(!<p>)` instead
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#skip_while_next
- use `matches!` instead of manual implementation
lint message: match expression looks like `matches!` macro
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#match_like_matches_macro
- use `keys` and `values methods insteads of iterating and ignoring either the keys or values.
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#iter_kv_map
This commit is contained in:
Gwen Lg
2025-12-13 22:56:24 +01:00
parent f2f6669bf0
commit 6dbcdcd784
13 changed files with 31 additions and 68 deletions
+6 -6
View File
@@ -380,9 +380,9 @@ impl From<layout::ZoneRedundancy> for ZoneRedundancy {
} }
} }
impl Into<layout::ZoneRedundancy> for ZoneRedundancy { impl From<ZoneRedundancy> for layout::ZoneRedundancy {
fn into(self) -> layout::ZoneRedundancy { fn from(val: ZoneRedundancy) -> Self {
match self { match val {
ZoneRedundancy::Maximum => layout::ZoneRedundancy::Maximum, ZoneRedundancy::Maximum => layout::ZoneRedundancy::Maximum,
ZoneRedundancy::AtLeast(x) => layout::ZoneRedundancy::AtLeast(x), ZoneRedundancy::AtLeast(x) => layout::ZoneRedundancy::AtLeast(x),
} }
@@ -397,10 +397,10 @@ impl From<layout::LayoutParameters> for LayoutParameters {
} }
} }
impl Into<layout::LayoutParameters> for LayoutParameters { impl From<LayoutParameters> for layout::LayoutParameters {
fn into(self) -> layout::LayoutParameters { fn from(val: LayoutParameters) -> Self {
layout::LayoutParameters { layout::LayoutParameters {
zone_redundancy: self.zone_redundancy.into(), zone_redundancy: val.zone_redundancy.into(),
} }
} }
} }
+2 -8
View File
@@ -63,6 +63,7 @@ pub struct ExpectedChecksums {
pub extra: Option<ChecksumValue>, pub extra: Option<ChecksumValue>,
} }
#[derive(Default)]
pub struct Checksummer { pub struct Checksummer {
pub crc32: Option<CrcDigest>, pub crc32: Option<CrcDigest>,
pub crc32c: Option<CrcDigest>, pub crc32c: Option<CrcDigest>,
@@ -84,14 +85,7 @@ pub struct Checksums {
impl Checksummer { impl Checksummer {
pub fn new() -> Self { pub fn new() -> Self {
Self { Default::default()
crc32: None,
crc32c: None,
crc64nvme: None,
md5: None,
sha1: None,
sha256: None,
}
} }
pub fn init(expected: &ExpectedChecksums, add_md5: bool) -> Self { pub fn init(expected: &ExpectedChecksums, add_md5: bool) -> Self {
+1 -1
View File
@@ -29,7 +29,7 @@ async fn handle_delete_internal(ctx: &ReqCtx, key: &str) -> Result<(Uuid, Uuid),
.iter() .iter()
.rev() .rev()
.find(|v| !matches!(&v.state, ObjectVersionState::Aborted)) .find(|v| !matches!(&v.state, ObjectVersionState::Aborted))
.or_else(|| object.versions().iter().rev().next()); .or_else(|| object.versions().iter().next_back());
let deleted_version = match deleted_version { let deleted_version = match deleted_version {
Some(dv) => dv.uuid, Some(dv) => dv.uuid,
None => { None => {
+3 -10
View File
@@ -94,10 +94,7 @@ impl EncryptionParams {
// data blocks are reused as-is. Since Garage v2, we are using // data blocks are reused as-is. Since Garage v2, we are using
// object-specific encryption keys, so we know that if both source // object-specific encryption keys, so we know that if both source
// and destination are encrypted, it can't be with the same key. // and destination are encrypted, it can't be with the same key.
match (a, b) { matches!((a, b), (Self::Plaintext, Self::Plaintext))
(Self::Plaintext, Self::Plaintext) => true,
_ => false,
}
} }
pub fn new_from_headers( pub fn new_from_headers(
@@ -587,8 +584,7 @@ impl Stream for DecryptStream {
if matches!(this.state, DecryptStreamState::Done) { if matches!(this.state, DecryptStreamState::Done) {
if !this.buf.is_empty() { if !this.buf.is_empty() {
return Poll::Ready(Some(Err(std::io::Error::new( return Poll::Ready(Some(Err(std::io::Error::other(
std::io::ErrorKind::Other,
"Decrypt: unexpected bytes after last encrypted chunk", "Decrypt: unexpected bytes after last encrypted chunk",
)))); ))));
} }
@@ -622,10 +618,7 @@ impl Stream for DecryptStream {
match res { match res {
Ok(bytes) if bytes.is_empty() => Poll::Ready(None), Ok(bytes) if bytes.is_empty() => Poll::Ready(None),
Ok(bytes) => Poll::Ready(Some(Ok(bytes.into()))), Ok(bytes) => Poll::Ready(Some(Ok(bytes.into()))),
Err(_) => Poll::Ready(Some(Err(std::io::Error::new( Err(_) => Poll::Ready(Some(Err(std::io::Error::other("Decryption failed")))),
std::io::ErrorKind::Other,
"Decryption failed",
)))),
} }
} }
} }
+6 -18
View File
@@ -400,15 +400,10 @@ async fn handle_get_full(
overrides: GetObjectOverrides, overrides: GetObjectOverrides,
checksum_mode: ChecksumMode, checksum_mode: ChecksumMode,
) -> Result<Response<ResBody>, Error> { ) -> Result<Response<ResBody>, Error> {
let mut resp_builder = object_headers( let mut resp_builder =
version, object_headers(version, version_meta, meta_inner, encryption, checksum_mode)
version_meta, .header(CONTENT_LENGTH, format!("{}", version_meta.size))
meta_inner, .status(StatusCode::OK);
encryption,
checksum_mode,
)
.header(CONTENT_LENGTH, format!("{}", version_meta.size))
.status(StatusCode::OK);
getobject_override_headers(overrides, &mut resp_builder)?; getobject_override_headers(overrides, &mut resp_builder)?;
let stream = full_object_byte_stream(garage, version, version_data, encryption); let stream = full_object_byte_stream(garage, version, version_data, encryption);
@@ -708,11 +703,7 @@ fn body_from_blocks_range(
Some(None) Some(None)
} else { } else {
// The chunk has an intersection with the requested range // The chunk has an intersection with the requested range
let start_in_chunk = if *chunk_offset > begin { let start_in_chunk = begin.saturating_sub(*chunk_offset);
0
} else {
begin - *chunk_offset
};
let end_in_chunk = if *chunk_offset + chunk_len < end { let end_in_chunk = if *chunk_offset + chunk_len < end {
chunk_len chunk_len
} else { } else {
@@ -773,10 +764,7 @@ fn error_stream_item<E: std::fmt::Display>(e: E) -> ByteStream {
} }
fn std_error_from_read_error<E: std::fmt::Display>(e: E) -> std::io::Error { fn std_error_from_read_error<E: std::fmt::Display>(e: E) -> std::io::Error {
std::io::Error::new( std::io::Error::other(format!("Error while reading object data: {}", e))
std::io::ErrorKind::Other,
format!("Error while reading object data: {}", e),
)
} }
// ---- // ----
+2 -2
View File
@@ -1014,12 +1014,12 @@ mod tests {
query.common.prefix = "a/".to_string(); query.common.prefix = "a/".to_string();
assert_eq!( assert_eq!(
common_prefix(objs.get(0).unwrap(), &query.common), common_prefix(objs.first().unwrap(), &query.common),
Some("a/b/") Some("a/b/")
); );
query.common.prefix = "a/b/".to_string(); query.common.prefix = "a/b/".to_string();
assert_eq!(common_prefix(objs.get(0).unwrap(), &query.common), None); assert_eq!(common_prefix(objs.first().unwrap(), &query.common), None);
} }
#[test] #[test]
+1 -6
View File
@@ -92,12 +92,7 @@ impl Cli {
.await?; .await?;
// CLI-only checks: the bucket must not have other aliases // CLI-only checks: the bucket must not have other aliases
if bucket if bucket.global_aliases.iter().any(|a| *a != opt.name) {
.global_aliases
.iter()
.find(|a| **a != opt.name)
.is_some()
{
return Err(Error::Message(format!("Bucket {} still has other global aliases. Use `bucket unalias` to delete them one by one.", opt.name))); return Err(Error::Message(format!("Bucket {} still has other global aliases. Use `bucket unalias` to delete them one by one.", opt.name)));
} }
+1 -2
View File
@@ -180,8 +180,7 @@ impl ClientConn {
"Too many inflight requests! RequestID collision. Interrupting previous request." "Too many inflight requests! RequestID collision. Interrupting previous request."
); );
let _ = old_ch.send(Box::pin(futures::stream::once(async move { let _ = old_ch.send(Box::pin(futures::stream::once(async move {
Err(std::io::Error::new( Err(std::io::Error::other(
std::io::ErrorKind::Other,
"RequestID collision, too many inflight requests", "RequestID collision, too many inflight requests",
)) ))
}))); })));
+1 -4
View File
@@ -493,10 +493,7 @@ impl RespEnc {
(res_stream, order_tag) (res_stream, order_tag)
} }
Err(err) => { Err(err) => {
let err = std::io::Error::new( let err = std::io::Error::other(format!("netapp error: {}", err));
std::io::ErrorKind::Other,
format!("netapp error: {}", err),
);
( (
Box::pin(futures::stream::once(async move { Err(err) })), Box::pin(futures::stream::once(async move { Err(err) })),
None, None,
+2 -5
View File
@@ -62,7 +62,7 @@ pub(crate) trait RecvLoop: Sync + 'static {
trace!( trace!(
"recv_loop({}): in_progress = {:?}", "recv_loop({}): in_progress = {:?}",
debug_name, debug_name,
streams.iter().map(|(id, _)| id).collect::<Vec<_>>() streams.keys().collect::<Vec<_>>()
); );
let mut header_id = [0u8; RequestID::BITS as usize / 8]; let mut header_id = [0u8; RequestID::BITS as usize / 8];
@@ -79,10 +79,7 @@ pub(crate) trait RecvLoop: Sync + 'static {
if size == CANCEL_REQUEST { if size == CANCEL_REQUEST {
if let Some(mut stream) = streams.remove(&id) { if let Some(mut stream) = streams.remove(&id) {
stream.send(Err(std::io::Error::new( stream.send(Err(std::io::Error::other("netapp: cancel requested")));
std::io::ErrorKind::Other,
"netapp: cancel requested",
)));
stream.end(); stream.end();
} }
self.cancel_handler(id); self.cancel_handler(id);
+3 -3
View File
@@ -264,13 +264,13 @@ impl LayoutHelper {
.versions .versions
.iter() .iter()
.map(|x| x.version) .map(|x| x.version)
.skip_while(|v| { .find(|v| {
self.ack_lock !self
.ack_lock
.get(v) .get(v)
.map(|x| x.load(Ordering::Relaxed) == 0) .map(|x| x.load(Ordering::Relaxed) == 0)
.unwrap_or(true) .unwrap_or(true)
}) })
.next()
.unwrap_or(self.inner().current().version); .unwrap_or(self.inner().current().version);
let changed = self.update(|layout| { let changed = self.update(|layout| {
layout layout
+1 -1
View File
@@ -116,7 +116,7 @@ impl LayoutManager {
pub fn sync_table_until(self: &Arc<Self>, table_name: &'static str, version: u64) { pub fn sync_table_until(self: &Arc<Self>, table_name: &'static str, version: u64) {
let mut table_sync_version = self.table_sync_version.lock().unwrap(); let mut table_sync_version = self.table_sync_version.lock().unwrap();
*table_sync_version.get_mut(table_name).unwrap() = version; *table_sync_version.get_mut(table_name).unwrap() = version;
let sync_until = table_sync_version.iter().map(|(_, v)| *v).min().unwrap(); let sync_until = *table_sync_version.values().min().unwrap();
drop(table_sync_version); drop(table_sync_version);
let mut layout = self.layout.write().unwrap(); let mut layout = self.layout.write().unwrap();
+2 -2
View File
@@ -951,13 +951,13 @@ fn get_rpc_public_addr(config: &Config) -> Option<SocketAddr> {
let filter_subnet: Option<ipnet::IpNet> = config let filter_subnet: Option<ipnet::IpNet> = config
.rpc_public_addr_subnet .rpc_public_addr_subnet
.as_ref() .as_ref()
.and_then(|filter_subnet_str| match filter_subnet_str.parse::<ipnet::IpNet>() { .map(|filter_subnet_str| match filter_subnet_str.parse::<ipnet::IpNet>() {
Ok(filter_subnet) => { Ok(filter_subnet) => {
let filter_subnet_trunc = filter_subnet.trunc(); let filter_subnet_trunc = filter_subnet.trunc();
if filter_subnet_trunc != filter_subnet { if filter_subnet_trunc != filter_subnet {
warn!("`rpc_public_addr_subnet` changed after applying netmask, continuing with {}", filter_subnet.trunc()); warn!("`rpc_public_addr_subnet` changed after applying netmask, continuing with {}", filter_subnet.trunc());
} }
Some(filter_subnet_trunc) filter_subnet_trunc
} }
Err(e) => { Err(e) => {
panic!( panic!(