2024 oct new clippy lints (#9448)

Fixes new lints from `cargo +nightly clippy` (`clippy 0.1.83 (798fb83f
2024-10-16)`)
This commit is contained in:
Conrad Ludgate
2024-10-18 10:27:50 +01:00
committed by GitHub
parent d762ad0883
commit b8304f90d6
45 changed files with 92 additions and 124 deletions

View File

@@ -107,7 +107,7 @@ pub fn get_pg_version(pgbin: &str) -> String {
// pg_config --version returns a (platform specific) human readable string // pg_config --version returns a (platform specific) human readable string
// such as "PostgreSQL 15.4". We parse this to v14/v15/v16 etc. // such as "PostgreSQL 15.4". We parse this to v14/v15/v16 etc.
let human_version = get_pg_config("--version", pgbin); let human_version = get_pg_config("--version", pgbin);
return parse_pg_version(&human_version).to_string(); parse_pg_version(&human_version).to_string()
} }
fn parse_pg_version(human_version: &str) -> &str { fn parse_pg_version(human_version: &str) -> &str {

View File

@@ -16,7 +16,7 @@ impl serde::Serialize for Partitioning {
{ {
pub struct KeySpace<'a>(&'a crate::keyspace::KeySpace); pub struct KeySpace<'a>(&'a crate::keyspace::KeySpace);
impl<'a> serde::Serialize for KeySpace<'a> { impl serde::Serialize for KeySpace<'_> {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,
@@ -44,7 +44,7 @@ impl serde::Serialize for Partitioning {
pub struct WithDisplay<'a, T>(&'a T); pub struct WithDisplay<'a, T>(&'a T);
impl<'a, T: std::fmt::Display> serde::Serialize for WithDisplay<'a, T> { impl<T: std::fmt::Display> serde::Serialize for WithDisplay<'_, T> {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,
@@ -55,7 +55,7 @@ impl<'a, T: std::fmt::Display> serde::Serialize for WithDisplay<'a, T> {
pub struct KeyRange<'a>(&'a std::ops::Range<crate::key::Key>); pub struct KeyRange<'a>(&'a std::ops::Range<crate::key::Key>);
impl<'a> serde::Serialize for KeyRange<'a> { impl serde::Serialize for KeyRange<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,

View File

@@ -921,12 +921,11 @@ impl<IO: AsyncRead + AsyncWrite + Unpin> PostgresBackendReader<IO> {
/// A futures::AsyncWrite implementation that wraps all data written to it in CopyData /// A futures::AsyncWrite implementation that wraps all data written to it in CopyData
/// messages. /// messages.
/// ///
pub struct CopyDataWriter<'a, IO> { pub struct CopyDataWriter<'a, IO> {
pgb: &'a mut PostgresBackend<IO>, pgb: &'a mut PostgresBackend<IO>,
} }
impl<'a, IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for CopyDataWriter<'a, IO> { impl<IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for CopyDataWriter<'_, IO> {
fn poll_write( fn poll_write(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>, cx: &mut std::task::Context<'_>,

View File

@@ -727,7 +727,7 @@ pub const SQLSTATE_INTERNAL_ERROR: &[u8; 5] = b"XX000";
pub const SQLSTATE_ADMIN_SHUTDOWN: &[u8; 5] = b"57P01"; pub const SQLSTATE_ADMIN_SHUTDOWN: &[u8; 5] = b"57P01";
pub const SQLSTATE_SUCCESSFUL_COMPLETION: &[u8; 5] = b"00000"; pub const SQLSTATE_SUCCESSFUL_COMPLETION: &[u8; 5] = b"00000";
impl<'a> BeMessage<'a> { impl BeMessage<'_> {
/// Serialize `message` to the given `buf`. /// Serialize `message` to the given `buf`.
/// Apart from smart memory managemet, BytesMut is good here as msg len /// Apart from smart memory managemet, BytesMut is good here as msg len
/// precedes its body and it is handy to write it down first and then fill /// precedes its body and it is handy to write it down first and then fill

View File

@@ -97,7 +97,7 @@ pub fn draw_svg(
Ok(result) Ok(result)
} }
impl<'a> SvgDraw<'a> { impl SvgDraw<'_> {
fn calculate_svg_layout(&mut self) { fn calculate_svg_layout(&mut self) {
// Find x scale // Find x scale
let segments = &self.storage.segments; let segments = &self.storage.segments;

View File

@@ -82,7 +82,7 @@ where
fn extract_remote_context(headers: &HeaderMap) -> opentelemetry::Context { fn extract_remote_context(headers: &HeaderMap) -> opentelemetry::Context {
struct HeaderExtractor<'a>(&'a HeaderMap); struct HeaderExtractor<'a>(&'a HeaderMap);
impl<'a> opentelemetry::propagation::Extractor for HeaderExtractor<'a> { impl opentelemetry::propagation::Extractor for HeaderExtractor<'_> {
fn get(&self, key: &str) -> Option<&str> { fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).and_then(|value| value.to_str().ok()) self.0.get(key).and_then(|value| value.to_str().ok())
} }

View File

@@ -37,7 +37,7 @@ impl<'de> Deserialize<'de> for Lsn {
is_human_readable_deserializer: bool, is_human_readable_deserializer: bool,
} }
impl<'de> Visitor<'de> for LsnVisitor { impl Visitor<'_> for LsnVisitor {
type Value = Lsn; type Value = Lsn;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

View File

@@ -73,7 +73,7 @@ impl<T> Poison<T> {
/// and subsequent calls to [`Poison::check_and_arm`] will fail with an error. /// and subsequent calls to [`Poison::check_and_arm`] will fail with an error.
pub struct Guard<'a, T>(&'a mut Poison<T>); pub struct Guard<'a, T>(&'a mut Poison<T>);
impl<'a, T> Guard<'a, T> { impl<T> Guard<'_, T> {
pub fn data(&self) -> &T { pub fn data(&self) -> &T {
&self.0.data &self.0.data
} }
@@ -94,7 +94,7 @@ impl<'a, T> Guard<'a, T> {
} }
} }
impl<'a, T> Drop for Guard<'a, T> { impl<T> Drop for Guard<'_, T> {
fn drop(&mut self) { fn drop(&mut self) {
match self.0.state { match self.0.state {
State::Clean => { State::Clean => {

View File

@@ -164,7 +164,7 @@ impl TenantShardId {
} }
} }
impl<'a> std::fmt::Display for ShardSlug<'a> { impl std::fmt::Display for ShardSlug<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!( write!(
f, f,

View File

@@ -152,7 +152,7 @@ pub struct RcuWriteGuard<'a, V> {
inner: RwLockWriteGuard<'a, RcuInner<V>>, inner: RwLockWriteGuard<'a, RcuInner<V>>,
} }
impl<'a, V> Deref for RcuWriteGuard<'a, V> { impl<V> Deref for RcuWriteGuard<'_, V> {
type Target = V; type Target = V;
fn deref(&self) -> &V { fn deref(&self) -> &V {
@@ -160,7 +160,7 @@ impl<'a, V> Deref for RcuWriteGuard<'a, V> {
} }
} }
impl<'a, V> RcuWriteGuard<'a, V> { impl<V> RcuWriteGuard<'_, V> {
/// ///
/// Store a new value. The new value will be written to the Rcu immediately, /// Store a new value. The new value will be written to the Rcu immediately,
/// and will be immediately seen by any `read` calls that start afterwards. /// and will be immediately seen by any `read` calls that start afterwards.

View File

@@ -219,7 +219,7 @@ impl<'a, T> CountWaitingInitializers<'a, T> {
} }
} }
impl<'a, T> Drop for CountWaitingInitializers<'a, T> { impl<T> Drop for CountWaitingInitializers<'_, T> {
fn drop(&mut self) { fn drop(&mut self) {
self.0.initializers.fetch_sub(1, Ordering::Relaxed); self.0.initializers.fetch_sub(1, Ordering::Relaxed);
} }
@@ -250,7 +250,7 @@ impl<T> std::ops::DerefMut for Guard<'_, T> {
} }
} }
impl<'a, T> Guard<'a, T> { impl<T> Guard<'_, T> {
/// Take the current value, and a new permit for it's deinitialization. /// Take the current value, and a new permit for it's deinitialization.
/// ///
/// The permit will be on a semaphore part of the new internal value, and any following /// The permit will be on a semaphore part of the new internal value, and any following

View File

@@ -184,23 +184,23 @@ mod tests {
struct MemoryIdentity<'a>(&'a dyn Extractor); struct MemoryIdentity<'a>(&'a dyn Extractor);
impl<'a> MemoryIdentity<'a> { impl MemoryIdentity<'_> {
fn as_ptr(&self) -> *const () { fn as_ptr(&self) -> *const () {
self.0 as *const _ as *const () self.0 as *const _ as *const ()
} }
} }
impl<'a> PartialEq for MemoryIdentity<'a> { impl PartialEq for MemoryIdentity<'_> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.as_ptr() == other.as_ptr() self.as_ptr() == other.as_ptr()
} }
} }
impl<'a> Eq for MemoryIdentity<'a> {} impl Eq for MemoryIdentity<'_> {}
impl<'a> Hash for MemoryIdentity<'a> { impl Hash for MemoryIdentity<'_> {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.as_ptr().hash(state); self.as_ptr().hash(state);
} }
} }
impl<'a> fmt::Debug for MemoryIdentity<'a> { impl fmt::Debug for MemoryIdentity<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:p}: {}", self.as_ptr(), self.0.id()) write!(f, "{:p}: {}", self.as_ptr(), self.0.id())
} }

View File

@@ -133,7 +133,7 @@ enum LazyLoadLayer<'a, E: CompactionJobExecutor> {
Loaded(VecDeque<<E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>), Loaded(VecDeque<<E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>),
Unloaded(&'a E::DeltaLayer), Unloaded(&'a E::DeltaLayer),
} }
impl<'a, E: CompactionJobExecutor> LazyLoadLayer<'a, E> { impl<E: CompactionJobExecutor> LazyLoadLayer<'_, E> {
fn min_key(&self) -> E::Key { fn min_key(&self) -> E::Key {
match self { match self {
Self::Loaded(entries) => entries.front().unwrap().key(), Self::Loaded(entries) => entries.front().unwrap().key(),
@@ -147,23 +147,23 @@ impl<'a, E: CompactionJobExecutor> LazyLoadLayer<'a, E> {
} }
} }
} }
impl<'a, E: CompactionJobExecutor> PartialOrd for LazyLoadLayer<'a, E> { impl<E: CompactionJobExecutor> PartialOrd for LazyLoadLayer<'_, E> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other)) Some(self.cmp(other))
} }
} }
impl<'a, E: CompactionJobExecutor> Ord for LazyLoadLayer<'a, E> { impl<E: CompactionJobExecutor> Ord for LazyLoadLayer<'_, E> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering { fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// reverse order so that we get a min-heap // reverse order so that we get a min-heap
(other.min_key(), other.min_lsn()).cmp(&(self.min_key(), self.min_lsn())) (other.min_key(), other.min_lsn()).cmp(&(self.min_key(), self.min_lsn()))
} }
} }
impl<'a, E: CompactionJobExecutor> PartialEq for LazyLoadLayer<'a, E> { impl<E: CompactionJobExecutor> PartialEq for LazyLoadLayer<'_, E> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal self.cmp(other) == std::cmp::Ordering::Equal
} }
} }
impl<'a, E: CompactionJobExecutor> Eq for LazyLoadLayer<'a, E> {} impl<E: CompactionJobExecutor> Eq for LazyLoadLayer<'_, E> {}
type LoadFuture<'a, E> = BoxFuture<'a, anyhow::Result<Vec<E>>>; type LoadFuture<'a, E> = BoxFuture<'a, anyhow::Result<Vec<E>>>;

View File

@@ -198,7 +198,7 @@ fn serialize_in_chunks<'a>(
} }
} }
impl<'a> ExactSizeIterator for Iter<'a> {} impl ExactSizeIterator for Iter<'_> {}
let buffer = bytes::BytesMut::new(); let buffer = bytes::BytesMut::new();
let inner = input.chunks(chunk_size); let inner = input.chunks(chunk_size);

View File

@@ -654,7 +654,7 @@ impl std::fmt::Debug for EvictionCandidate {
let ts = chrono::DateTime::<chrono::Utc>::from(self.last_activity_ts); let ts = chrono::DateTime::<chrono::Utc>::from(self.last_activity_ts);
let ts = ts.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true); let ts = ts.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true);
struct DisplayIsDebug<'a, T>(&'a T); struct DisplayIsDebug<'a, T>(&'a T);
impl<'a, T: std::fmt::Display> std::fmt::Debug for DisplayIsDebug<'a, T> { impl<T: std::fmt::Display> std::fmt::Debug for DisplayIsDebug<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0) write!(f, "{}", self.0)
} }

View File

@@ -1189,7 +1189,7 @@ struct GlobalAndPerTimelineHistogramTimer<'a, 'c> {
op: SmgrQueryType, op: SmgrQueryType,
} }
impl<'a, 'c> Drop for GlobalAndPerTimelineHistogramTimer<'a, 'c> { impl Drop for GlobalAndPerTimelineHistogramTimer<'_, '_> {
fn drop(&mut self) { fn drop(&mut self) {
let elapsed = self.start.elapsed(); let elapsed = self.start.elapsed();
let ex_throttled = self let ex_throttled = self
@@ -1560,7 +1560,7 @@ impl BasebackupQueryTime {
} }
} }
impl<'a, 'c> BasebackupQueryTimeOngoingRecording<'a, 'c> { impl BasebackupQueryTimeOngoingRecording<'_, '_> {
pub(crate) fn observe<T>(self, res: &Result<T, QueryError>) { pub(crate) fn observe<T>(self, res: &Result<T, QueryError>) {
let elapsed = self.start.elapsed(); let elapsed = self.start.elapsed();
let ex_throttled = self let ex_throttled = self

View File

@@ -90,7 +90,7 @@ pub mod mock {
let used_bytes = walk_dir_disk_usage(tenants_dir, name_filter.as_deref()).unwrap(); let used_bytes = walk_dir_disk_usage(tenants_dir, name_filter.as_deref()).unwrap();
// round it up to the nearest block multiple // round it up to the nearest block multiple
let used_blocks = (used_bytes + (blocksize - 1)) / blocksize; let used_blocks = used_bytes.div_ceil(*blocksize);
if used_blocks > *total_blocks { if used_blocks > *total_blocks {
panic!( panic!(

View File

@@ -50,13 +50,13 @@ impl From<PageReadGuard<'static>> for BlockLease<'static> {
} }
#[cfg(test)] #[cfg(test)]
impl<'a> From<std::sync::Arc<[u8; PAGE_SZ]>> for BlockLease<'a> { impl From<std::sync::Arc<[u8; PAGE_SZ]>> for BlockLease<'_> {
fn from(value: std::sync::Arc<[u8; PAGE_SZ]>) -> Self { fn from(value: std::sync::Arc<[u8; PAGE_SZ]>) -> Self {
BlockLease::Arc(value) BlockLease::Arc(value)
} }
} }
impl<'a> Deref for BlockLease<'a> { impl Deref for BlockLease<'_> {
type Target = [u8; PAGE_SZ]; type Target = [u8; PAGE_SZ];
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {

View File

@@ -131,7 +131,7 @@ struct OnDiskNode<'a, const L: usize> {
values: &'a [u8], values: &'a [u8],
} }
impl<'a, const L: usize> OnDiskNode<'a, L> { impl<const L: usize> OnDiskNode<'_, L> {
/// ///
/// Interpret a PAGE_SZ page as a node. /// Interpret a PAGE_SZ page as a node.
/// ///

View File

@@ -2182,7 +2182,7 @@ pub(crate) struct UploadQueueAccessor<'a> {
inner: std::sync::MutexGuard<'a, UploadQueue>, inner: std::sync::MutexGuard<'a, UploadQueue>,
} }
impl<'a> UploadQueueAccessor<'a> { impl UploadQueueAccessor<'_> {
pub(crate) fn latest_uploaded_index_part(&self) -> &IndexPart { pub(crate) fn latest_uploaded_index_part(&self) -> &IndexPart {
match &*self.inner { match &*self.inner {
UploadQueue::Initialized(x) => &x.clean.0, UploadQueue::Initialized(x) => &x.clean.0,

View File

@@ -108,7 +108,6 @@ impl scheduler::Completion for WriteComplete {
/// when we last did a write. We only populate this after doing at least one /// when we last did a write. We only populate this after doing at least one
/// write for a tenant -- this avoids holding state for tenants that have /// write for a tenant -- this avoids holding state for tenants that have
/// uploads disabled. /// uploads disabled.
struct UploaderTenantState { struct UploaderTenantState {
// This Weak only exists to enable culling idle instances of this type // This Weak only exists to enable culling idle instances of this type
// when the Tenant has been deallocated. // when the Tenant has been deallocated.

View File

@@ -705,7 +705,7 @@ pub mod tests {
/// Useful with `Key`, which has too verbose `{:?}` for printing multiple layers. /// Useful with `Key`, which has too verbose `{:?}` for printing multiple layers.
struct RangeDisplayDebug<'a, T: std::fmt::Display>(&'a Range<T>); struct RangeDisplayDebug<'a, T: std::fmt::Display>(&'a Range<T>);
impl<'a, T: std::fmt::Display> std::fmt::Debug for RangeDisplayDebug<'a, T> { impl<T: std::fmt::Display> std::fmt::Debug for RangeDisplayDebug<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.0.start, self.0.end) write!(f, "{}..{}", self.0.start, self.0.end)
} }

View File

@@ -529,8 +529,7 @@ impl DeltaLayerWriterInner {
key_end: Key, key_end: Key,
ctx: &RequestContext, ctx: &RequestContext,
) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> { ) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> {
let index_start_blk = let index_start_blk = self.blob_writer.size().div_ceil(PAGE_SZ as u64) as u32;
((self.blob_writer.size() + PAGE_SZ as u64 - 1) / PAGE_SZ as u64) as u32;
let mut file = self.blob_writer.into_inner(ctx).await?; let mut file = self.blob_writer.into_inner(ctx).await?;

View File

@@ -828,8 +828,7 @@ impl ImageLayerWriterInner {
ctx: &RequestContext, ctx: &RequestContext,
end_key: Option<Key>, end_key: Option<Key>,
) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> { ) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> {
let index_start_blk = let index_start_blk = self.blob_writer.size().div_ceil(PAGE_SZ as u64) as u32;
((self.blob_writer.size() + PAGE_SZ as u64 - 1) / PAGE_SZ as u64) as u32;
// Calculate compression ratio // Calculate compression ratio
let compressed_size = self.blob_writer.size() - PAGE_SZ as u64; // Subtract PAGE_SZ for header let compressed_size = self.blob_writer.size() - PAGE_SZ as u64; // Subtract PAGE_SZ for header

View File

@@ -978,7 +978,7 @@ impl LayerInner {
let timeline = self let timeline = self
.timeline .timeline
.upgrade() .upgrade()
.ok_or_else(|| DownloadError::TimelineShutdown)?; .ok_or(DownloadError::TimelineShutdown)?;
// count cancellations, which currently remain largely unexpected // count cancellations, which currently remain largely unexpected
let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled()); let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());

View File

@@ -339,7 +339,7 @@ impl<'de> serde::Deserialize<'de> for LayerName {
struct LayerNameVisitor; struct LayerNameVisitor;
impl<'de> serde::de::Visitor<'de> for LayerNameVisitor { impl serde::de::Visitor<'_> for LayerNameVisitor {
type Value = LayerName; type Value = LayerName;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

View File

@@ -99,21 +99,21 @@ impl<'a> PeekableLayerIterRef<'a> {
} }
} }
impl<'a> std::cmp::PartialEq for IteratorWrapper<'a> { impl std::cmp::PartialEq for IteratorWrapper<'_> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal self.cmp(other) == Ordering::Equal
} }
} }
impl<'a> std::cmp::Eq for IteratorWrapper<'a> {} impl std::cmp::Eq for IteratorWrapper<'_> {}
impl<'a> std::cmp::PartialOrd for IteratorWrapper<'a> { impl std::cmp::PartialOrd for IteratorWrapper<'_> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other)) Some(self.cmp(other))
} }
} }
impl<'a> std::cmp::Ord for IteratorWrapper<'a> { impl std::cmp::Ord for IteratorWrapper<'_> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering { fn cmp(&self, other: &Self) -> std::cmp::Ordering {
use std::cmp::Ordering; use std::cmp::Ordering;
let a = self.peek_next_key_lsn_value(); let a = self.peek_next_key_lsn_value();

View File

@@ -73,7 +73,7 @@ impl<'a> BufView<'a> {
} }
} }
impl<'a> Deref for BufView<'a> { impl Deref for BufView<'_> {
type Target = [u8]; type Target = [u8];
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -84,7 +84,7 @@ impl<'a> Deref for BufView<'a> {
} }
} }
impl<'a> AsRef<[u8]> for BufView<'a> { impl AsRef<[u8]> for BufView<'_> {
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
match self { match self {
BufView::Slice(slice) => slice, BufView::Slice(slice) => slice,
@@ -196,11 +196,6 @@ pub(crate) struct ChunkedVectoredReadBuilder {
max_read_size: Option<usize>, max_read_size: Option<usize>,
} }
/// Computes x / d rounded up.
fn div_round_up(x: usize, d: usize) -> usize {
(x + (d - 1)) / d
}
impl ChunkedVectoredReadBuilder { impl ChunkedVectoredReadBuilder {
const CHUNK_SIZE: usize = virtual_file::get_io_buffer_alignment(); const CHUNK_SIZE: usize = virtual_file::get_io_buffer_alignment();
/// Start building a new vectored read. /// Start building a new vectored read.
@@ -220,7 +215,7 @@ impl ChunkedVectoredReadBuilder {
.expect("First insertion always succeeds"); .expect("First insertion always succeeds");
let start_blk_no = start_offset as usize / Self::CHUNK_SIZE; let start_blk_no = start_offset as usize / Self::CHUNK_SIZE;
let end_blk_no = div_round_up(end_offset as usize, Self::CHUNK_SIZE); let end_blk_no = (end_offset as usize).div_ceil(Self::CHUNK_SIZE);
Self { Self {
start_blk_no, start_blk_no,
end_blk_no, end_blk_no,
@@ -248,7 +243,7 @@ impl ChunkedVectoredReadBuilder {
pub(crate) fn extend(&mut self, start: u64, end: u64, meta: BlobMeta) -> VectoredReadExtended { pub(crate) fn extend(&mut self, start: u64, end: u64, meta: BlobMeta) -> VectoredReadExtended {
tracing::trace!(start, end, "trying to extend"); tracing::trace!(start, end, "trying to extend");
let start_blk_no = start as usize / Self::CHUNK_SIZE; let start_blk_no = start as usize / Self::CHUNK_SIZE;
let end_blk_no = div_round_up(end as usize, Self::CHUNK_SIZE); let end_blk_no = (end as usize).div_ceil(Self::CHUNK_SIZE);
let not_limited_by_max_read_size = { let not_limited_by_max_read_size = {
if let Some(max_read_size) = self.max_read_size { if let Some(max_read_size) = self.max_read_size {
@@ -975,12 +970,4 @@ mod tests {
round_trip_test_compressed(&blobs, true).await?; round_trip_test_compressed(&blobs, true).await?;
Ok(()) Ok(())
} }
#[test]
fn test_div_round_up() {
const CHUNK_SIZE: usize = 512;
assert_eq!(1, div_round_up(200, CHUNK_SIZE));
assert_eq!(1, div_round_up(CHUNK_SIZE, CHUNK_SIZE));
assert_eq!(2, div_round_up(CHUNK_SIZE + 1, CHUNK_SIZE));
}
} }

View File

@@ -724,9 +724,9 @@ impl VirtualFileInner {
*handle_guard = handle; *handle_guard = handle;
return Ok(FileGuard { Ok(FileGuard {
slot_guard: slot_guard.downgrade(), slot_guard: slot_guard.downgrade(),
}); })
} }
pub fn remove(self) { pub fn remove(self) {

View File

@@ -193,7 +193,7 @@ impl<'de> serde::de::Deserialize<'de> for IpPattern {
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
{ {
struct StrVisitor; struct StrVisitor;
impl<'de> serde::de::Visitor<'de> for StrVisitor { impl serde::de::Visitor<'_> for StrVisitor {
type Value = IpPattern; type Value = IpPattern;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {

View File

@@ -558,7 +558,7 @@ pub struct RetryConfig {
} }
impl RetryConfig { impl RetryConfig {
/// Default options for RetryConfig. // Default options for RetryConfig.
/// Total delay for 5 retries with 200ms base delay and 2 backoff factor is about 6s. /// Total delay for 5 retries with 200ms base delay and 2 backoff factor is about 6s.
pub const CONNECT_TO_COMPUTE_DEFAULT_VALUES: &'static str = pub const CONNECT_TO_COMPUTE_DEFAULT_VALUES: &'static str =

View File

@@ -104,7 +104,7 @@ struct Options<'a> {
options: &'a StartupMessageParams, options: &'a StartupMessageParams,
} }
impl<'a> serde::Serialize for Options<'a> { impl serde::Serialize for Options<'_> {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,

View File

@@ -55,7 +55,7 @@ impl<Id: InternId> std::ops::Deref for InternedString<Id> {
impl<'de, Id: InternId> serde::de::Deserialize<'de> for InternedString<Id> { impl<'de, Id: InternId> serde::de::Deserialize<'de> for InternedString<Id> {
fn deserialize<D: serde::de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { fn deserialize<D: serde::de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Visitor<Id>(PhantomData<Id>); struct Visitor<Id>(PhantomData<Id>);
impl<'de, Id: InternId> serde::de::Visitor<'de> for Visitor<Id> { impl<Id: InternId> serde::de::Visitor<'_> for Visitor<Id> {
type Value = InternedString<Id>; type Value = InternedString<Id>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {

View File

@@ -76,11 +76,7 @@
) )
)] )]
// List of temporarily allowed lints to unblock beta/nightly. // List of temporarily allowed lints to unblock beta/nightly.
#![allow( #![allow(unknown_lints)]
unknown_lints,
// TODO: 1.82: Add `use<T>` where necessary and remove from this list.
impl_trait_overcaptures,
)]
use std::convert::Infallible; use std::convert::Infallible;

View File

@@ -73,11 +73,11 @@ impl ClientConfig<'_> {
self, self,
) -> anyhow::Result< ) -> anyhow::Result<
impl tokio_postgres::tls::TlsConnect< impl tokio_postgres::tls::TlsConnect<
S, S,
Error = impl std::fmt::Debug, Error = impl std::fmt::Debug + use<S>,
Future = impl Send, Future = impl Send + use<S>,
Stream = RustlsStream<S>, Stream = RustlsStream<S>,
>, > + use<S>,
> { > {
let mut mk = MakeRustlsConnect::new(self.config); let mut mk = MakeRustlsConnect::new(self.config);
let tls = MakeTlsConnect::<S>::make_tls_connect(&mut mk, self.hostname)?; let tls = MakeTlsConnect::<S>::make_tls_connect(&mut mk, self.hostname)?;

View File

@@ -218,16 +218,12 @@ impl sasl::Mechanism for Exchange<'_> {
self.state = ExchangeState::SaltSent(sent); self.state = ExchangeState::SaltSent(sent);
Ok(Step::Continue(self, msg)) Ok(Step::Continue(self, msg))
} }
#[allow(unreachable_patterns)] // TODO: 1.82: simply drop this match
Step::Success(x, _) => match x {},
Step::Failure(msg) => Ok(Step::Failure(msg)), Step::Failure(msg) => Ok(Step::Failure(msg)),
} }
} }
ExchangeState::SaltSent(sent) => { ExchangeState::SaltSent(sent) => {
match sent.transition(self.secret, &self.tls_server_end_point, input)? { match sent.transition(self.secret, &self.tls_server_end_point, input)? {
Step::Success(keys, msg) => Ok(Step::Success(keys, msg)), Step::Success(keys, msg) => Ok(Step::Success(keys, msg)),
#[allow(unreachable_patterns)] // TODO: 1.82: simply drop this match
Step::Continue(x, _) => match x {},
Step::Failure(msg) => Ok(Step::Failure(msg)), Step::Failure(msg) => Ok(Step::Failure(msg)),
} }
} }

View File

@@ -11,13 +11,6 @@ use tokio_postgres::tls::NoTlsStream;
use tokio_postgres::{AsyncMessage, Socket}; use tokio_postgres::{AsyncMessage, Socket};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use tracing::{error, info, info_span, warn, Instrument}; use tracing::{error, info, info_span, warn, Instrument};
use crate::context::RequestMonitoring;
use crate::control_plane::messages::MetricsAuxInfo;
use crate::metrics::Metrics;
use super::conn_pool_lib::{Client, ClientInnerExt, ConnInfo, GlobalConnPool};
#[cfg(test)] #[cfg(test)]
use { use {
super::conn_pool_lib::GlobalConnPoolOptions, super::conn_pool_lib::GlobalConnPoolOptions,
@@ -25,6 +18,11 @@ use {
std::{sync::atomic, time::Duration}, std::{sync::atomic, time::Duration},
}; };
use super::conn_pool_lib::{Client, ClientInnerExt, ConnInfo, GlobalConnPool};
use crate::context::RequestMonitoring;
use crate::control_plane::messages::MetricsAuxInfo;
use crate::metrics::Metrics;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub(crate) struct ConnInfoWithAuth { pub(crate) struct ConnInfoWithAuth {
pub(crate) conn_info: ConnInfo, pub(crate) conn_info: ConnInfo,

View File

@@ -1,25 +1,23 @@
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::atomic::{self, AtomicUsize};
use std::sync::{Arc, Weak};
use std::time::Duration;
use dashmap::DashMap; use dashmap::DashMap;
use parking_lot::RwLock; use parking_lot::RwLock;
use rand::Rng; use rand::Rng;
use std::{collections::HashMap, sync::Arc, sync::Weak, time::Duration};
use std::{
ops::Deref,
sync::atomic::{self, AtomicUsize},
};
use tokio_postgres::ReadyForQueryStatus; use tokio_postgres::ReadyForQueryStatus;
use tracing::{debug, info, Span};
use super::backend::HttpConnError;
use super::conn_pool::ClientInnerRemote;
use crate::auth::backend::ComputeUserInfo;
use crate::context::RequestMonitoring;
use crate::control_plane::messages::ColdStartInfo; use crate::control_plane::messages::ColdStartInfo;
use crate::metrics::{HttpEndpointPoolsGuard, Metrics}; use crate::metrics::{HttpEndpointPoolsGuard, Metrics};
use crate::usage_metrics::{Ids, MetricCounter, USAGE_METRICS}; use crate::usage_metrics::{Ids, MetricCounter, USAGE_METRICS};
use crate::{ use crate::{DbName, EndpointCacheKey, RoleName};
auth::backend::ComputeUserInfo, context::RequestMonitoring, DbName, EndpointCacheKey, RoleName,
};
use super::conn_pool::ClientInnerRemote;
use tracing::info;
use tracing::{debug, Span};
use super::backend::HttpConnError;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub(crate) struct ConnInfo { pub(crate) struct ConnInfo {
@@ -482,7 +480,7 @@ impl<C: ClientInnerExt> Client<C> {
}) })
} }
pub(crate) fn do_drop(&mut self) -> Option<impl FnOnce()> { pub(crate) fn do_drop(&mut self) -> Option<impl FnOnce() + use<C>> {
let conn_info = self.conn_info.clone(); let conn_info = self.conn_info.clone();
let client = self let client = self
.inner .inner

View File

@@ -10,12 +10,11 @@ use rand::Rng;
use tokio::net::TcpStream; use tokio::net::TcpStream;
use tracing::{debug, error, info, info_span, Instrument}; use tracing::{debug, error, info, info_span, Instrument};
use super::conn_pool_lib::{ClientInnerExt, ConnInfo};
use crate::context::RequestMonitoring; use crate::context::RequestMonitoring;
use crate::control_plane::messages::{ColdStartInfo, MetricsAuxInfo}; use crate::control_plane::messages::{ColdStartInfo, MetricsAuxInfo};
use crate::metrics::{HttpEndpointPoolsGuard, Metrics}; use crate::metrics::{HttpEndpointPoolsGuard, Metrics};
use crate::usage_metrics::{Ids, MetricCounter, USAGE_METRICS}; use crate::usage_metrics::{Ids, MetricCounter, USAGE_METRICS};
use super::conn_pool_lib::{ClientInnerExt, ConnInfo};
use crate::EndpointCacheKey; use crate::EndpointCacheKey;
pub(crate) type Send = http2::SendRequest<hyper::body::Incoming>; pub(crate) type Send = http2::SendRequest<hyper::body::Incoming>;

View File

@@ -155,10 +155,10 @@ fn pg_text_to_json(pg_value: Option<&str>, pg_type: &Type) -> Result<Value, Json
// dimensions, we just return them as is. // dimensions, we just return them as is.
// //
fn pg_array_parse(pg_array: &str, elem_type: &Type) -> Result<Value, JsonConversionError> { fn pg_array_parse(pg_array: &str, elem_type: &Type) -> Result<Value, JsonConversionError> {
_pg_array_parse(pg_array, elem_type, false).map(|(v, _)| v) pg_array_parse_inner(pg_array, elem_type, false).map(|(v, _)| v)
} }
fn _pg_array_parse( fn pg_array_parse_inner(
pg_array: &str, pg_array: &str,
elem_type: &Type, elem_type: &Type,
nested: bool, nested: bool,
@@ -211,7 +211,7 @@ fn _pg_array_parse(
'{' if !quote => { '{' if !quote => {
level += 1; level += 1;
if level > 1 { if level > 1 {
let (res, off) = _pg_array_parse(&pg_array[i..], elem_type, true)?; let (res, off) = pg_array_parse_inner(&pg_array[i..], elem_type, true)?;
entries.push(res); entries.push(res);
for _ in 0..off - 1 { for _ in 0..off - 1 {
pg_array_chr.next(); pg_array_chr.next();

View File

@@ -25,7 +25,6 @@ use crate::context::RequestMonitoring;
use crate::control_plane::messages::{ColdStartInfo, MetricsAuxInfo}; use crate::control_plane::messages::{ColdStartInfo, MetricsAuxInfo};
use crate::metrics::Metrics; use crate::metrics::Metrics;
use crate::usage_metrics::{Ids, MetricCounter, USAGE_METRICS}; use crate::usage_metrics::{Ids, MetricCounter, USAGE_METRICS};
use crate::{DbName, RoleName}; use crate::{DbName, RoleName};
struct ConnPoolEntry<C: ClientInnerExt> { struct ConnPoolEntry<C: ClientInnerExt> {
@@ -530,7 +529,7 @@ impl<C: ClientInnerExt> LocalClient<C> {
}) })
} }
fn do_drop(&mut self) -> Option<impl FnOnce()> { fn do_drop(&mut self) -> Option<impl FnOnce() + use<C>> {
let conn_info = self.conn_info.clone(); let conn_info = self.conn_info.clone();
let client = self let client = self
.inner .inner

View File

@@ -38,7 +38,6 @@ use crate::error::{ErrorKind, ReportableError, UserFacingError};
use crate::metrics::{HttpDirection, Metrics}; use crate::metrics::{HttpDirection, Metrics};
use crate::proxy::{run_until_cancelled, NeonOptions}; use crate::proxy::{run_until_cancelled, NeonOptions};
use crate::serverless::backend::HttpConnError; use crate::serverless::backend::HttpConnError;
use crate::usage_metrics::{MetricCounter, MetricCounterRecorder}; use crate::usage_metrics::{MetricCounter, MetricCounterRecorder};
use crate::{DbName, RoleName}; use crate::{DbName, RoleName};

View File

@@ -375,7 +375,7 @@ pub async fn task_backup(
let now = Utc::now(); let now = Utc::now();
collect_metrics_backup_iteration( collect_metrics_backup_iteration(
&USAGE_METRICS.backup_endpoints, &USAGE_METRICS.backup_endpoints,
&storage, storage.as_ref(),
&hostname, &hostname,
prev, prev,
now, now,
@@ -395,7 +395,7 @@ pub async fn task_backup(
#[instrument(skip_all)] #[instrument(skip_all)]
async fn collect_metrics_backup_iteration( async fn collect_metrics_backup_iteration(
endpoints: &DashMap<Ids, Arc<MetricBackupCounter>, FastHasher>, endpoints: &DashMap<Ids, Arc<MetricBackupCounter>, FastHasher>,
storage: &Option<GenericRemoteStorage>, storage: Option<&GenericRemoteStorage>,
hostname: &str, hostname: &str,
prev: DateTime<Utc>, prev: DateTime<Utc>,
now: DateTime<Utc>, now: DateTime<Utc>,
@@ -446,7 +446,7 @@ async fn collect_metrics_backup_iteration(
} }
async fn upload_events_chunk( async fn upload_events_chunk(
storage: &Option<GenericRemoteStorage>, storage: Option<&GenericRemoteStorage>,
chunk: EventChunk<'_, Event<Ids, &'static str>>, chunk: EventChunk<'_, Event<Ids, &'static str>>,
remote_path: &RemotePath, remote_path: &RemotePath,
cancel: &CancellationToken, cancel: &CancellationToken,
@@ -577,10 +577,10 @@ mod tests {
// counter is unregistered // counter is unregistered
assert!(metrics.endpoints.is_empty()); assert!(metrics.endpoints.is_empty());
collect_metrics_backup_iteration(&metrics.backup_endpoints, &None, "foo", now, now, 1000) collect_metrics_backup_iteration(&metrics.backup_endpoints, None, "foo", now, now, 1000)
.await; .await;
assert!(!metrics.backup_endpoints.is_empty()); assert!(!metrics.backup_endpoints.is_empty());
collect_metrics_backup_iteration(&metrics.backup_endpoints, &None, "foo", now, now, 1000) collect_metrics_backup_iteration(&metrics.backup_endpoints, None, "foo", now, now, 1000)
.await; .await;
// backup counter is unregistered after the second iteration // backup counter is unregistered after the second iteration
assert!(metrics.backup_endpoints.is_empty()); assert!(metrics.backup_endpoints.is_empty());

View File

@@ -73,7 +73,7 @@ struct DropKey<'a, T> {
registry: &'a Waiters<T>, registry: &'a Waiters<T>,
} }
impl<'a, T> Drop for DropKey<'a, T> { impl<T> Drop for DropKey<'_, T> {
fn drop(&mut self) { fn drop(&mut self) {
self.registry.0.lock().remove(&self.key); self.registry.0.lock().remove(&self.key);
} }

View File

@@ -122,7 +122,7 @@ impl<'a> WriteGuardSharedState<'a> {
} }
} }
impl<'a> Deref for WriteGuardSharedState<'a> { impl Deref for WriteGuardSharedState<'_> {
type Target = SharedState; type Target = SharedState;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -130,13 +130,13 @@ impl<'a> Deref for WriteGuardSharedState<'a> {
} }
} }
impl<'a> DerefMut for WriteGuardSharedState<'a> { impl DerefMut for WriteGuardSharedState<'_> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.guard &mut self.guard
} }
} }
impl<'a> Drop for WriteGuardSharedState<'a> { impl Drop for WriteGuardSharedState<'_> {
fn drop(&mut self) { fn drop(&mut self) {
let term_flush_lsn = let term_flush_lsn =
TermLsn::from((self.guard.sk.last_log_term(), self.guard.sk.flush_lsn())); TermLsn::from((self.guard.sk.last_log_term(), self.guard.sk.flush_lsn()));