Skip to content

style: fix latest clippy warnings #1254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions codegen/src/sqlstate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ fn make_code(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<Fi
file,
r#"
Inner::E{code} => "{code}","#,
code = code,
)
.unwrap();
}
Expand All @@ -97,8 +96,6 @@ fn make_consts(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<
/// {code}
pub const {name}: SqlState = SqlState(Inner::E{code});
"#,
name = name,
code = code,
)
.unwrap();
}
Expand All @@ -121,8 +118,7 @@ enum Inner {{"#,
write!(
file,
r#"
E{},"#,
code,
E{code},"#,
)
.unwrap();
}
Expand Down
10 changes: 5 additions & 5 deletions codegen/src/type_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,18 +237,18 @@ fn parse_types() -> BTreeMap<u32, Type> {
let doc_name = array_re.replace(&name, "$1[]").to_ascii_uppercase();
let mut doc = doc_name.clone();
if let Some(descr) = raw_type.get("descr") {
write!(doc, " - {}", descr).unwrap();
write!(doc, " - {descr}").unwrap();
}
let doc = Escape::new(doc.as_bytes().iter().cloned()).collect();
let doc = String::from_utf8(doc).unwrap();

if let Some(array_type_oid) = raw_type.get("array_type_oid") {
let array_type_oid = array_type_oid.parse::<u32>().unwrap();

let name = format!("_{}", name);
let variant = format!("{}Array", variant);
let doc = format!("{}&#91;&#93;", doc_name);
let ident = format!("{}_ARRAY", ident);
let name = format!("_{name}");
let variant = format!("{variant}Array");
let doc = format!("{doc_name}&#91;&#93;");
let ident = format!("{ident}_ARRAY");

let type_ = Type {
name,
Expand Down
4 changes: 2 additions & 2 deletions postgres-derive-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ where
let result = conn.query_one(&stmt, &[]).unwrap().get(0);
assert_eq!(val, &result);

let stmt = conn.prepare(&format!("SELECT $1::{}", sql_type)).unwrap();
let stmt = conn.prepare(&format!("SELECT $1::{sql_type}")).unwrap();
let result = conn.query_one(&stmt, &[val]).unwrap().get(0);
assert_eq!(val, &result);
}
Expand All @@ -45,7 +45,7 @@ pub fn test_type_asymmetric<T, F, S, C>(
let result: F = conn.query_one(&stmt, &[]).unwrap().get(0);
assert!(cmp(val, &result));

let stmt = conn.prepare(&format!("SELECT $1::{}", sql_type)).unwrap();
let stmt = conn.prepare(&format!("SELECT $1::{sql_type}")).unwrap();
let result: F = conn.query_one(&stmt, &[val]).unwrap().get(0);
assert!(cmp(val, &result));
}
Expand Down
2 changes: 1 addition & 1 deletion postgres-derive/src/overrides.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl Overrides {
"invalid rename_all rule, expected one of: {}",
RENAME_RULES
.iter()
.map(|rule| format!("\"{}\"", rule))
.map(|rule| format!("\"{rule}\""))
.collect::<Vec<_>>()
.join(", ")
),
Expand Down
2 changes: 1 addition & 1 deletion postgres-derive/src/tosql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ fn composite_body(fields: &[Field]) -> TokenStream {
postgres_types::IsNull::Yes => -1,
postgres_types::IsNull::No => {
let len = buf.len() - base - 4;
if len > i32::max_value() as usize {
if len > i32::MAX as usize {
return std::result::Result::Err(
std::convert::Into::into("value too large to transmit"));
}
Expand Down
2 changes: 1 addition & 1 deletion postgres-protocol/src/authentication/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn md5_hash(username: &[u8], password: &[u8], salt: [u8; 4]) -> String {
md5.update(password);
md5.update(username);
let output = md5.finalize_reset();
md5.update(format!("{:x}", output));
md5.update(format!("{output:x}"));
md5.update(salt);
format!("md5{:x}", md5.finalize())
}
Expand Down
10 changes: 4 additions & 6 deletions postgres-protocol/src/authentication/sasl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ impl ScramSha256 {

let verifier = match parsed {
ServerFinalMessage::Error(e) => {
return Err(io::Error::other(format!("SCRAM error: {}", e)));
return Err(io::Error::other(format!("SCRAM error: {e}")));
}
ServerFinalMessage::Verifier(verifier) => verifier,
};
Expand Down Expand Up @@ -302,10 +302,8 @@ impl<'a> Parser<'a> {
match self.it.next() {
Some((_, c)) if c == target => Ok(()),
Some((i, c)) => {
let m = format!(
"unexpected character at byte {}: expected `{}` but got `{}",
i, target, c
);
let m =
format!("unexpected character at byte {i}: expected `{target}` but got `{c}");
Err(io::Error::new(io::ErrorKind::InvalidInput, m))
}
None => Err(io::Error::new(
Expand Down Expand Up @@ -371,7 +369,7 @@ impl<'a> Parser<'a> {
match self.it.peek() {
Some(&(i, _)) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("unexpected trailing data at byte {}", i),
format!("unexpected trailing data at byte {i}"),
)),
None => Ok(()),
}
Expand Down
4 changes: 2 additions & 2 deletions postgres-protocol/src/message/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ impl Message {
tag => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("unknown authentication tag `{}`", tag),
format!("unknown authentication tag `{tag}`"),
));
}
},
Expand All @@ -262,7 +262,7 @@ impl Message {
tag => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("unknown message tag `{}`", tag),
format!("unknown message tag `{tag}`"),
));
}
};
Expand Down
2 changes: 1 addition & 1 deletion postgres-protocol/src/password/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,5 @@ pub fn md5(password: &[u8], username: &str) -> String {
let mut hash = Md5::new();
hash.update(&salted_password);
let digest = hash.finalize();
format!("md5{:x}", digest)
format!("md5{digest:x}")
}
8 changes: 3 additions & 5 deletions postgres-types/src/chrono_04.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use chrono_04::{
DateTime, Duration, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc,
};
use postgres_protocol::types;
use std::error::Error;
use std::{convert::TryFrom, error::Error};

use crate::{FromSql, IsNull, ToSql, Type};

Expand Down Expand Up @@ -123,11 +123,9 @@ impl<'a> FromSql<'a> for NaiveDate {
impl ToSql for NaiveDate {
fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
let jd = self.signed_duration_since(base().date()).num_days();
if jd > i64::from(i32::max_value()) || jd < i64::from(i32::min_value()) {
return Err("value too large to transmit".into());
}
let jd = i32::try_from(jd).map_err(|_| "value too large to transmit")?;

types::date_to_sql(jd as i32, w);
types::date_to_sql(jd, w);
Ok(IsNull::No)
}

Expand Down
12 changes: 5 additions & 7 deletions postgres-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ impl fmt::Display for Type {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.schema() {
"public" | "pg_catalog" => {}
schema => write!(fmt, "{}.", schema)?,
schema => write!(fmt, "{schema}.")?,
}
fmt.write_str(self.name())
}
Expand Down Expand Up @@ -631,16 +631,14 @@ impl<'a, T: FromSql<'a>, const N: usize> FromSql<'a> for [T; N] {
let v = values
.next()?
.ok_or_else(|| -> Box<dyn Error + Sync + Send> {
format!("too few elements in array (expected {}, got {})", N, i).into()
format!("too few elements in array (expected {N}, got {i})").into()
})?;
T::from_sql_nullable(member_type, v)
})?;
if values.next()?.is_some() {
return Err(format!(
"excess elements in array (expected {}, got more than that)",
N,
)
.into());
return Err(
format!("excess elements in array (expected {N}, got more than that)",).into(),
);
}

Ok(out)
Expand Down
2 changes: 1 addition & 1 deletion postgres-types/src/pg_lsn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl fmt::Display for PgLsn {

impl fmt::Debug for PgLsn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{}", self))
fmt::Display::fmt(self, f)
}
}

Expand Down
6 changes: 2 additions & 4 deletions postgres-types/src/time_02.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,9 @@ impl<'a> FromSql<'a> for Date {
impl ToSql for Date {
fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
let jd = (*self - base().date()).whole_days();
if jd > i64::from(i32::max_value()) || jd < i64::from(i32::min_value()) {
return Err("value too large to transmit".into());
}
let jd = i32::try_from(jd).map_err(|_| "value too large to transmit")?;

types::date_to_sql(jd as i32, w);
types::date_to_sql(jd, w);
Ok(IsNull::No)
}

Expand Down
6 changes: 2 additions & 4 deletions postgres-types/src/time_03.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,9 @@ impl<'a> FromSql<'a> for Date {
impl ToSql for Date {
fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
let jd = (*self - base().date()).whole_days();
if jd > i64::from(i32::max_value()) || jd < i64::from(i32::min_value()) {
return Err("value too large to transmit".into());
}
let jd = i32::try_from(jd).map_err(|_| "value too large to transmit")?;

types::date_to_sql(jd as i32, w);
types::date_to_sql(jd, w);
Ok(IsNull::No)
}

Expand Down
6 changes: 2 additions & 4 deletions tokio-postgres/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,10 +872,8 @@ impl<'a> Parser<'a> {
match self.it.next() {
Some((_, c)) if c == target => Ok(()),
Some((i, c)) => {
let m = format!(
"unexpected character at byte {}: expected `{}` but got `{}`",
i, target, c
);
let m =
format!("unexpected character at byte {i}: expected `{target}` but got `{c}`");
Err(Error::config_parse(m.into()))
}
None => Err(Error::config_parse("unexpected EOF".into())),
Expand Down
2 changes: 1 addition & 1 deletion tokio-postgres/src/connect_socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub(crate) async fn connect_socket(
}
#[cfg(unix)]
Addr::Unix(dir) => {
let path = dir.join(format!(".s.PGSQL.{}", port));
let path = dir.join(format!(".s.PGSQL.{port}"));
let socket = connect_with_timeout(UnixStream::connect(path), connect_timeout).await?;
Ok(Socket::new_unix(socket))
}
Expand Down
12 changes: 6 additions & 6 deletions tokio-postgres/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,10 +312,10 @@ impl fmt::Display for DbError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{}: {}", self.severity, self.message)?;
if let Some(detail) = &self.detail {
write!(fmt, "\nDETAIL: {}", detail)?;
write!(fmt, "\nDETAIL: {detail}")?;
}
if let Some(hint) = &self.hint {
write!(fmt, "\nHINT: {}", hint)?;
write!(fmt, "\nHINT: {hint}")?;
}
Ok(())
}
Expand Down Expand Up @@ -382,9 +382,9 @@ impl fmt::Display for Error {
Kind::Io => fmt.write_str("error communicating with the server")?,
Kind::UnexpectedMessage => fmt.write_str("unexpected message from server")?,
Kind::Tls => fmt.write_str("error performing TLS handshake")?,
Kind::ToSql(idx) => write!(fmt, "error serializing parameter {}", idx)?,
Kind::FromSql(idx) => write!(fmt, "error deserializing column {}", idx)?,
Kind::Column(column) => write!(fmt, "invalid column `{}`", column)?,
Kind::ToSql(idx) => write!(fmt, "error serializing parameter {idx}")?,
Kind::FromSql(idx) => write!(fmt, "error deserializing column {idx}")?,
Kind::Column(column) => write!(fmt, "invalid column `{column}`")?,
Kind::Parameters(real, expected) => {
write!(fmt, "expected {expected} parameters but got {real}")?
}
Expand All @@ -401,7 +401,7 @@ impl fmt::Display for Error {
Kind::Timeout => fmt.write_str("timeout waiting for server")?,
};
if let Some(ref cause) = self.0.cause {
write!(fmt, ": {}", cause)?;
write!(fmt, ": {cause}")?;
}
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions tokio-postgres/src/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,9 @@ fn prepare_rec<'a>(

fn encode(client: &InnerClient, name: &str, query: &str, types: &[Type]) -> Result<Bytes, Error> {
if types.is_empty() {
debug!("preparing query {}: {}", name, query);
debug!("preparing query {name}: {query}");
} else {
debug!("preparing query {} with types {:?}: {}", name, types, query);
debug!("preparing query {name} with types {types:?}: {query}");
}

client.with_buf(|buf| {
Expand Down
4 changes: 2 additions & 2 deletions tokio-postgres/src/simple_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl SimpleColumn {
}

pub async fn simple_query(client: &InnerClient, query: &str) -> Result<SimpleQueryStream, Error> {
debug!("executing simple query: {}", query);
debug!("executing simple query: {query}");

let buf = encode(client, query)?;
let responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
Expand All @@ -46,7 +46,7 @@ pub async fn simple_query(client: &InnerClient, query: &str) -> Result<SimpleQue
}

pub async fn batch_execute(client: &InnerClient, query: &str) -> Result<(), Error> {
debug!("executing statement batch: {}", query);
debug!("executing statement batch: {query}");

let buf = encode(client, query)?;
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
Expand Down
4 changes: 2 additions & 2 deletions tokio-postgres/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,8 @@ impl<'a> Transaction<'a> {

async fn _savepoint(&mut self, name: Option<String>) -> Result<Transaction<'_>, Error> {
let depth = self.savepoint.as_ref().map_or(0, |sp| sp.depth) + 1;
let name = name.unwrap_or_else(|| format!("sp_{}", depth));
let query = format!("SAVEPOINT {}", name);
let name = name.unwrap_or_else(|| format!("sp_{depth}"));
let query = format!("SAVEPOINT {name}");
self.batch_execute(&query).await?;

Ok(Transaction {
Expand Down
6 changes: 3 additions & 3 deletions tokio-postgres/tests/test/binary_copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ async fn write_many_rows() {
for i in 0..10_000i32 {
writer
.as_mut()
.write(&[&i, &format!("the value for {}", i)])
.write(&[&i, &format!("the value for {i}")])
.await
.unwrap();
}
Expand All @@ -69,7 +69,7 @@ async fn write_many_rows() {
.unwrap();
for (i, row) in rows.iter().enumerate() {
assert_eq!(row.get::<_, i32>(0), i as i32);
assert_eq!(row.get::<_, &str>(1), format!("the value for {}", i));
assert_eq!(row.get::<_, &str>(1), format!("the value for {i}"));
}
}

Expand Down Expand Up @@ -164,7 +164,7 @@ async fn read_many_rows() {

for (i, row) in rows.iter().enumerate() {
assert_eq!(row.get::<i32>(0), i as i32);
assert_eq!(row.get::<&str>(1), format!("the value for {}", i));
assert_eq!(row.get::<&str>(1), format!("the value for {i}"));
}
}

Expand Down
6 changes: 3 additions & 3 deletions tokio-postgres/tests/test/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -624,11 +624,11 @@ async fn copy_in_large() {
let a = Bytes::from_static(b"0\tname0\n");
let mut b = BytesMut::new();
for i in 1..5_000 {
writeln!(b, "{0}\tname{0}", i).unwrap();
writeln!(b, "{i}\tname{i}").unwrap();
}
let mut c = BytesMut::new();
for i in 5_000..10_000 {
writeln!(c, "{0}\tname{0}", i).unwrap();
writeln!(c, "{i}\tname{i}").unwrap();
}
let mut stream = stream::iter(
vec![a, b.freeze(), c.freeze()]
Expand Down Expand Up @@ -704,7 +704,7 @@ async fn copy_out() {
async fn notices() {
let long_name = "x".repeat(65);
let (client, mut connection) =
connect_raw(&format!("user=postgres application_name={}", long_name,))
connect_raw(&format!("user=postgres application_name={long_name}",))
.await
.unwrap();

Expand Down
2 changes: 1 addition & 1 deletion tokio-postgres/tests/test/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::time::Duration;
use tokio_postgres::config::{Config, SslNegotiation, TargetSessionAttrs};

fn check(s: &str, config: &Config) {
assert_eq!(s.parse::<Config>().expect(s), *config, "`{}`", s);
assert_eq!(s.parse::<Config>().expect(s), *config, "`{s}`");
}

#[test]
Expand Down
Loading