From 87513af7dd42348f69e36d041fec76ad8659bfc2 Mon Sep 17 00:00:00 2001 From: Yotam Ofek Date: Fri, 18 Oct 2024 20:57:50 +0000 Subject: [PATCH 1/5] [lib] fix clippy warnings --- lib/examples/features.rs | 33 +++++++++++++++++---------------- lib/examples/live_location.rs | 5 ++--- lib/examples/poll.rs | 23 ++++++++++++----------- lib/src/api.rs | 15 +++++++-------- lib/src/connector/hyper.rs | 6 +++--- lib/src/stream.rs | 7 ++++--- lib/src/util/messages.rs | 28 ++++++++++++---------------- 7 files changed, 57 insertions(+), 60 deletions(-) diff --git a/lib/examples/features.rs b/lib/examples/features.rs index b9e38b200a..4dae3b5ffb 100644 --- a/lib/examples/features.rs +++ b/lib/examples/features.rs @@ -104,24 +104,25 @@ async fn test_leave(api: Api, message: Message) -> Result<(), Error> { } async fn test(api: Api, message: Message) -> Result<(), Error> { - match message.kind { - MessageKind::Text { ref data, .. } => match data.as_str() { - "/message" => test_message(api, message).await?, - "/preview" => test_preview(api, message).await?, - "/reply" => test_reply(api, message).await?, - "/forward" => test_forward(api, message).await?, - "/edit-message" => test_edit_message(api, message).await?, - "/get_chat" => test_get_chat(api, message).await?, - "/get_chat_administrators" => test_get_chat_administrators(api, message).await?, - "/get_chat_members_count" => test_get_chat_members_count(api, message).await?, - "/get_chat_member" => test_get_chat_member(api, message).await?, - "/get_user_profile_photos" => test_get_user_profile_photos(api, message).await?, - "/leave" => test_leave(api, message).await?, - _ => (), - }, - _ => (), + let MessageKind::Text { ref data, .. } = message.kind else { + return Ok(()); }; + match data.as_str() { + "/message" => test_message(api, message).await?, + "/preview" => test_preview(api, message).await?, + "/reply" => test_reply(api, message).await?, + "/forward" => test_forward(api, message).await?, + "/edit-message" => test_edit_message(api, message).await?, + "/get_chat" => test_get_chat(api, message).await?, + "/get_chat_administrators" => test_get_chat_administrators(api, message).await?, + "/get_chat_members_count" => test_get_chat_members_count(api, message).await?, + "/get_chat_member" => test_get_chat_member(api, message).await?, + "/get_user_profile_photos" => test_get_user_profile_photos(api, message).await?, + "/leave" => test_leave(api, message).await?, + _ => {} + } + Ok(()) } diff --git a/lib/examples/live_location.rs b/lib/examples/live_location.rs index f8748b03c5..24d9b1cb67 100644 --- a/lib/examples/live_location.rs +++ b/lib/examples/live_location.rs @@ -35,9 +35,8 @@ async fn main() -> Result<(), Error> { let update = update?; if let UpdateKind::Message(message) = update.kind { if let MessageKind::Text { ref data, .. } = message.kind { - match data.as_str() { - "/livelocation" => test(api.clone(), message.clone()).await?, - _ => (), + if data.as_str() == "/livelocation" { + test(api.clone(), message).await? } } } diff --git a/lib/examples/poll.rs b/lib/examples/poll.rs index 139aa08298..b57395b99f 100644 --- a/lib/examples/poll.rs +++ b/lib/examples/poll.rs @@ -72,17 +72,18 @@ async fn main() -> Result<(), Error> { let update = update?; match update.kind { - UpdateKind::Message(message) => match message.kind { - MessageKind::Text { ref data, .. } => match data.as_str() { - "/poll" => test_anonymous_poll(api.clone(), message).await?, - "/quiz" => test_quiz_poll(api.clone(), message).await?, - "/public" => test_public_poll(api.clone(), message).await?, - "/multiple" => test_multiple_answers(api.clone(), message).await?, - "/closed" => test_closed_poll(api.clone(), message).await?, - _ => (), - }, - _ => (), - }, + UpdateKind::Message(message) => { + if let MessageKind::Text { ref data, .. } = message.kind { + match data.as_str() { + "/poll" => test_anonymous_poll(api.clone(), message).await?, + "/quiz" => test_quiz_poll(api.clone(), message).await?, + "/public" => test_public_poll(api.clone(), message).await?, + "/multiple" => test_multiple_answers(api.clone(), message).await?, + "/closed" => test_closed_poll(api.clone(), message).await?, + _ => {} + } + } + } UpdateKind::Poll(Poll { total_voter_count, id, diff --git a/lib/src/api.rs b/lib/src/api.rs index 07c2207664..5916536a5f 100644 --- a/lib/src/api.rs +++ b/lib/src/api.rs @@ -70,7 +70,7 @@ impl Api { /// # } /// ``` pub fn stream(&self) -> UpdatesStream { - UpdatesStream::new(&self) + UpdatesStream::new(self) } /// Send a request to the Telegram server and do not wait for a response. @@ -180,13 +180,12 @@ impl Api { tracing::trace!(name = %request.name(), body = %request.body, "sending request"); let http_response = self.0.connector.request(&self.0.token, request).await?; tracing::trace!( - response = %match http_response.body { - Some(ref vec) => match std::str::from_utf8(vec) { - Ok(str) => str, - Err(_) => "" - }, - None => "", - }, "response received" + response = %http_response + .body + .as_deref() + .map(|body| std::str::from_utf8(body).unwrap_or("")) + .unwrap_or(""), + "response received" ); let response = Resp::deserialize(http_response).map_err(ErrorKind::from)?; diff --git a/lib/src/connector/hyper.rs b/lib/src/connector/hyper.rs index f6d82ef8f3..11d417d737 100644 --- a/lib/src/connector/hyper.rs +++ b/lib/src/connector/hyper.rs @@ -128,9 +128,9 @@ impl Connector for .parse() .map_err(HttpError::from) .map_err(ErrorKind::from)?; - http_request.headers_mut().map(move |headers| { + if let Some(headers) = http_request.headers_mut() { headers.insert(CONTENT_TYPE, content_type); - }); + } let mut bytes = Vec::new(); prepared.read_to_end(&mut bytes).map_err(ErrorKind::from)?; @@ -146,7 +146,7 @@ impl Connector for let body = whole_chunk .iter() .fold(vec![], |mut acc, chunk| -> Vec { - acc.extend_from_slice(&chunk); + acc.extend_from_slice(chunk); acc }); diff --git a/lib/src/stream.rs b/lib/src/stream.rs index e3ab709609..26cee99fb7 100644 --- a/lib/src/stream.rs +++ b/lib/src/stream.rs @@ -17,6 +17,8 @@ const TELEGRAM_LONG_POLL_TIMEOUT_SECONDS: u64 = 5; const TELEGRAM_LONG_POLL_LIMIT_MESSAGES: Integer = 100; const TELEGRAM_LONG_POLL_ERROR_DELAY_MILLISECONDS: u64 = 500; +type Request = Pin>, Error>> + Send>>; + /// This type represents stream of Telegram API updates and uses /// long polling method under the hood. #[must_use = "streams do nothing unless polled"] @@ -24,8 +26,7 @@ pub struct UpdatesStream { api: Api, last_update: Integer, buffer: VecDeque, - current_request: - Option>, Error>> + Send>>>, + current_request: Option, timeout: Duration, allowed_updates: Vec, limit: Integer, @@ -103,7 +104,7 @@ impl Stream for UpdatesStream { let request = ref_mut.api.send_timeout(get_updates, timeout); ref_mut.current_request = Some(Box::pin(request)); - return Poll::Ready(Some(Err(err))); + Poll::Ready(Some(Err(err))) } Ok(false) => { let timeout = ref_mut.timeout + Duration::from_secs(1); diff --git a/lib/src/util/messages.rs b/lib/src/util/messages.rs index 14fa6d3c8e..cc23d1562a 100644 --- a/lib/src/util/messages.rs +++ b/lib/src/util/messages.rs @@ -12,11 +12,11 @@ use crate::types::{ /// For example, this will return the text from text messages, or the caption of a photo. pub trait MessageText { /// Obtain text from a message if available. - fn text<'a>(&'a self) -> Option; + fn text(&self) -> Option; } impl MessageText for MessageOrChannelPost { - fn text<'a>(&'a self) -> Option { + fn text(&self) -> Option { match self { MessageOrChannelPost::Message(msg) => msg.text(), MessageOrChannelPost::ChannelPost(post) => post.text(), @@ -25,13 +25,13 @@ impl MessageText for MessageOrChannelPost { } impl MessageText for Message { - fn text<'a>(&'a self) -> Option { + fn text(&self) -> Option { self.kind.text() } } impl MessageText for MessageKind { - fn text<'a>(&'a self) -> Option { + fn text(&self) -> Option { match self { MessageKind::Text { data, .. } => Some(data.to_owned()), MessageKind::Audio { data } => data.title.to_owned(), @@ -64,7 +64,7 @@ impl MessageText for MessageKind { } impl MessageText for ChannelPost { - fn text<'a>(&'a self) -> Option { + fn text(&self) -> Option { self.kind.text() } } @@ -76,11 +76,11 @@ impl MessageText for ChannelPost { /// A video, video note or document returns any thumbnail as well. pub trait MessageGetFiles { /// Obtain files from a message if available. - fn get_files<'a>(&'a self) -> Option>; + fn get_files(&self) -> Option>; } impl MessageGetFiles for MessageOrChannelPost { - fn get_files<'a>(&'a self) -> Option> { + fn get_files(&self) -> Option> { match self { MessageOrChannelPost::Message(msg) => msg.get_files(), MessageOrChannelPost::ChannelPost(post) => post.get_files(), @@ -89,13 +89,13 @@ impl MessageGetFiles for MessageOrChannelPost { } impl MessageGetFiles for Message { - fn get_files<'a>(&'a self) -> Option> { + fn get_files(&self) -> Option> { self.kind.get_files() } } impl MessageGetFiles for MessageKind { - fn get_files<'a>(&'a self) -> Option> { + fn get_files(&self) -> Option> { match self { MessageKind::Text { .. } => None, MessageKind::Audio { data } => Some(vec![data.get_file()]), @@ -106,9 +106,7 @@ impl MessageGetFiles for MessageKind { } Some(files) } - MessageKind::Photo { data, .. } => { - Some(data.into_iter().map(|f| f.get_file()).collect()) - } + MessageKind::Photo { data, .. } => Some(data.iter().map(|f| f.get_file()).collect()), MessageKind::Sticker { data } => Some(vec![data.get_file()]), MessageKind::Video { data, .. } => { let mut files = vec![data.get_file()]; @@ -132,9 +130,7 @@ impl MessageGetFiles for MessageKind { MessageKind::NewChatMembers { .. } => None, MessageKind::LeftChatMember { .. } => None, MessageKind::NewChatTitle { .. } => None, - MessageKind::NewChatPhoto { data } => { - Some(data.into_iter().map(|f| f.get_file()).collect()) - } + MessageKind::NewChatPhoto { data } => Some(data.iter().map(|f| f.get_file()).collect()), MessageKind::DeleteChatPhoto => None, MessageKind::GroupChatCreated => None, MessageKind::SupergroupChatCreated => None, @@ -148,7 +144,7 @@ impl MessageGetFiles for MessageKind { } impl MessageGetFiles for ChannelPost { - fn get_files<'a>(&'a self) -> Option> { + fn get_files(&self) -> Option> { self.kind.get_files() } } From 0559ecfda5d545fb60f446571b7885e4cc84c21d Mon Sep 17 00:00:00 2001 From: Yotam Ofek Date: Sat, 19 Oct 2024 11:24:07 +0000 Subject: [PATCH 2/5] [lib] small cleanup that's a weird use of `Result`'s being an iterator --- lib/src/connector/hyper.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/src/connector/hyper.rs b/lib/src/connector/hyper.rs index 11d417d737..905aebf0a5 100644 --- a/lib/src/connector/hyper.rs +++ b/lib/src/connector/hyper.rs @@ -4,7 +4,7 @@ use std::pin::Pin; use std::str::FromStr; use bytes::Bytes; -use futures::{Future, FutureExt}; +use futures::{Future, FutureExt, TryFutureExt}; use hyper::{ body::to_bytes, client::{connect::Connect, Client}, @@ -141,14 +141,10 @@ impl Connector for .map_err(ErrorKind::from)?; let response = client.request(request).await.map_err(ErrorKind::from)?; - let whole_chunk = to_bytes(response.into_body()).await; - - let body = whole_chunk - .iter() - .fold(vec![], |mut acc, chunk| -> Vec { - acc.extend_from_slice(chunk); - acc - }); + let body = to_bytes(response.into_body()) + .await + .unwrap_or_default() + .to_vec(); Ok::(HttpResponse { body: Some(body) }) }; From a896b64668bdc99cce35c740b2fed232d606f2ea Mon Sep 17 00:00:00 2001 From: Yotam Ofek Date: Mon, 21 Oct 2024 12:46:26 +0000 Subject: [PATCH 3/5] [raw] fix clippy warnings --- raw/src/requests/_base/_base.rs | 2 +- raw/src/requests/_base/errors.rs | 10 +- .../requests/_base/request_types/detached.rs | 4 +- raw/src/requests/_base/request_types/json.rs | 2 +- .../requests/_base/request_types/multipart.rs | 2 +- raw/src/requests/_base/response_types/json.rs | 4 +- raw/src/requests/answer_callback_query.rs | 6 +- .../requests/edit_message_live_location.rs | 4 +- raw/src/requests/get_file.rs | 2 +- raw/src/requests/get_updates.rs | 9 +- raw/src/requests/get_user_profile_photos.rs | 2 +- raw/src/requests/send_chat_action.rs | 2 +- raw/src/requests/send_contact.rs | 12 +- raw/src/requests/send_location.rs | 4 +- raw/src/requests/send_message.rs | 2 +- raw/src/requests/send_venue.rs | 4 +- raw/src/types/inline_query.rs | 6 +- raw/src/types/message.rs | 109 +++++++++--------- raw/src/types/primitive.rs | 2 +- raw/src/types/refs.rs | 16 +-- raw/src/types/reply_markup.rs | 29 ++--- raw/src/types/response_parameters.rs | 4 +- raw/tests/update.rs | 40 +++---- 23 files changed, 126 insertions(+), 151 deletions(-) diff --git a/raw/src/requests/_base/_base.rs b/raw/src/requests/_base/_base.rs index 769afe7a5d..a97c646d62 100644 --- a/raw/src/requests/_base/_base.rs +++ b/raw/src/requests/_base/_base.rs @@ -56,7 +56,7 @@ impl Request for DetachedRequest { type Response = Resp; fn serialize(&self) -> Result { - Ok(Self::Type::serialize((), &self.http_request)?) + Self::Type::serialize((), &self.http_request) } } diff --git a/raw/src/requests/_base/errors.rs b/raw/src/requests/_base/errors.rs index a0db331a80..61f8b9ca4f 100644 --- a/raw/src/requests/_base/errors.rs +++ b/raw/src/requests/_base/errors.rs @@ -37,19 +37,19 @@ impl fmt::Display for Error { description, parameters, } => { - f.write_str(&description)?; + f.write_str(description)?; if let Some(parameters) = parameters { if let Some(chat_id) = parameters.migrate_to_chat_id { - write!(f, ", migrate to chat id: {}", chat_id)?; + write!(f, ", migrate to chat id: {chat_id}")?; } if let Some(seconds) = parameters.retry_after { - write!(f, ", retry after: {}", seconds)?; + write!(f, ", retry after: {seconds}")?; } } Ok(()) } - ErrorKind::DetachedError(s) => f.write_str(&s), - ErrorKind::Json(error) => write!(f, "{}", error), + ErrorKind::DetachedError(s) => f.write_str(s), + ErrorKind::Json(error) => write!(f, "{error}"), } } } diff --git a/raw/src/requests/_base/request_types/detached.rs b/raw/src/requests/_base/request_types/detached.rs index c72fc5f4ed..d79adbf4ba 100644 --- a/raw/src/requests/_base/request_types/detached.rs +++ b/raw/src/requests/_base/request_types/detached.rs @@ -9,8 +9,8 @@ impl RequestType for DetachedRequestType { fn serialize(_options: Self::Options, request: &Self::Request) -> Result { match request { - &Ok(ref req) => Ok(req.clone()), - &Err(ref err) => Err(ErrorKind::DetachedError(err.to_string()).into()), + Ok(req) => Ok(req.clone()), + Err(err) => Err(ErrorKind::DetachedError(err.to_string()).into()), } } } diff --git a/raw/src/requests/_base/request_types/json.rs b/raw/src/requests/_base/request_types/json.rs index 60c11e9334..1390c46051 100644 --- a/raw/src/requests/_base/request_types/json.rs +++ b/raw/src/requests/_base/request_types/json.rs @@ -14,7 +14,7 @@ impl RequestType for JsonRequestType { fn serialize(url: Self::Options, request: &Self::Request) -> Result { let body = serde_json::to_string(&request).map_err(ErrorKind::from)?; Ok(HttpRequest { - url: url, + url, method: Method::Post, body: Body::Json(body), }) diff --git a/raw/src/requests/_base/request_types/multipart.rs b/raw/src/requests/_base/request_types/multipart.rs index 97b2a601ae..6e04cd3347 100644 --- a/raw/src/requests/_base/request_types/multipart.rs +++ b/raw/src/requests/_base/request_types/multipart.rs @@ -21,7 +21,7 @@ impl RequestType for MultipartRequestType { let multipart = request.to_multipart()?; Ok(HttpRequest { - url: url, + url, method: Method::Post, body: Body::Multipart(multipart), }) diff --git a/raw/src/requests/_base/response_types/json.rs b/raw/src/requests/_base/response_types/json.rs index 9e7656073b..2a56ee4ece 100644 --- a/raw/src/requests/_base/response_types/json.rs +++ b/raw/src/requests/_base/response_types/json.rs @@ -29,9 +29,7 @@ impl JsonResponse for JsonTrueToUnitResponse { type Raw = True; type Type = (); - fn map(_: Self::Raw) -> Self::Type { - () - } + fn map(_: Self::Raw) -> Self::Type {} } impl ResponseType for Resp diff --git a/raw/src/requests/answer_callback_query.rs b/raw/src/requests/answer_callback_query.rs index 47ae66bd45..8eca298d1b 100644 --- a/raw/src/requests/answer_callback_query.rs +++ b/raw/src/requests/answer_callback_query.rs @@ -21,7 +21,7 @@ pub struct AnswerCallbackQuery<'t> { cache_time: Option, } -impl<'i, 't> Request for AnswerCallbackQuery<'t> { +impl<'t> Request for AnswerCallbackQuery<'t> { type Type = JsonRequestType; type Response = JsonTrueToUnitResponse; @@ -104,9 +104,9 @@ where where T: Into>, { - AnswerCallbackQuery::new(&self, text) + AnswerCallbackQuery::new(self, text) } fn acknowledge<'t>(&self) -> AnswerCallbackQuery<'t> { - AnswerCallbackQuery::acknowledge(&self) + AnswerCallbackQuery::acknowledge(self) } } diff --git a/raw/src/requests/edit_message_live_location.rs b/raw/src/requests/edit_message_live_location.rs index 3642c2b910..36abb1a358 100644 --- a/raw/src/requests/edit_message_live_location.rs +++ b/raw/src/requests/edit_message_live_location.rs @@ -33,8 +33,8 @@ impl EditMessageLiveLocation { EditMessageLiveLocation { chat_id: chat.to_chat_ref(), message_id: message_id.to_message_id(), - latitude: latitude, - longitude: longitude, + latitude, + longitude, reply_markup: None, } } diff --git a/raw/src/requests/get_file.rs b/raw/src/requests/get_file.rs index d8048b7eca..b9613a7944 100644 --- a/raw/src/requests/get_file.rs +++ b/raw/src/requests/get_file.rs @@ -9,7 +9,7 @@ pub struct GetFile { file_id: FileRef, } -impl<'s> Request for GetFile { +impl Request for GetFile { type Type = JsonRequestType; type Response = JsonIdResponse; diff --git a/raw/src/requests/get_updates.rs b/raw/src/requests/get_updates.rs index bbdeda1f24..8258b706c4 100644 --- a/raw/src/requests/get_updates.rs +++ b/raw/src/requests/get_updates.rs @@ -2,7 +2,7 @@ use crate::requests::*; use crate::types::*; /// Use this method to receive incoming updates using long polling. -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] +#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Serialize)] #[must_use = "requests do nothing unless sent"] pub struct GetUpdates { #[serde(skip_serializing_if = "Option::is_none")] @@ -25,12 +25,7 @@ impl Request for GetUpdates { impl GetUpdates { pub fn new() -> Self { - GetUpdates { - offset: None, - limit: None, - timeout: None, - allowed_updates: Vec::new(), - } + Self::default() } pub fn offset(&mut self, offset: Integer) -> &mut Self { diff --git a/raw/src/requests/get_user_profile_photos.rs b/raw/src/requests/get_user_profile_photos.rs index 3417e12dcc..80ff631e55 100644 --- a/raw/src/requests/get_user_profile_photos.rs +++ b/raw/src/requests/get_user_profile_photos.rs @@ -47,7 +47,7 @@ pub trait CanGetUserProfilePhotos { fn get_user_profile_photos(&self) -> GetUserProfilePhotos; } -impl<'b, U> CanGetUserProfilePhotos for U +impl CanGetUserProfilePhotos for U where U: ToUserId, { diff --git a/raw/src/requests/send_chat_action.rs b/raw/src/requests/send_chat_action.rs index 76ed419528..d279ea5a63 100644 --- a/raw/src/requests/send_chat_action.rs +++ b/raw/src/requests/send_chat_action.rs @@ -49,7 +49,7 @@ impl SendChatAction { { SendChatAction { chat_id: chat.to_chat_ref(), - action: action, + action, } } } diff --git a/raw/src/requests/send_contact.rs b/raw/src/requests/send_contact.rs index 4cc5f7eb34..411bf66db3 100644 --- a/raw/src/requests/send_contact.rs +++ b/raw/src/requests/send_contact.rs @@ -101,28 +101,28 @@ where /// Reply with phone contact. pub trait CanReplySendContact { - fn contact_reply<'p, 'f, 'l, P: 'p, F: 'f>( + fn contact_reply<'p, 'f, 'l, P, F>( &self, phone_number: P, first_name: F, ) -> SendContact<'p, 'f, 'l> where - P: Into>, - F: Into>; + P: Into> + 'p, + F: Into> + 'f; } impl CanReplySendContact for M where M: ToMessageId + ToSourceChat, { - fn contact_reply<'p, 'f, 'l, P: 'p, F: 'f>( + fn contact_reply<'p, 'f, 'l, P, F>( &self, phone_number: P, first_name: F, ) -> SendContact<'p, 'f, 'l> where - P: Into>, - F: Into>, + P: Into> + 'p, + F: Into> + 'f, { let mut rq = self.to_source_chat().contact(phone_number, first_name); rq.reply_to(self.to_message_id()); diff --git a/raw/src/requests/send_location.rs b/raw/src/requests/send_location.rs index ce66339638..164517b3f5 100644 --- a/raw/src/requests/send_location.rs +++ b/raw/src/requests/send_location.rs @@ -36,8 +36,8 @@ impl SendLocation { { SendLocation { chat_id: chat.to_chat_ref(), - latitude: latitude, - longitude: longitude, + latitude, + longitude, live_period: None, disable_notification: false, reply_to_message_id: None, diff --git a/raw/src/requests/send_message.rs b/raw/src/requests/send_message.rs index 5aca4663cd..7691b81d2c 100644 --- a/raw/src/requests/send_message.rs +++ b/raw/src/requests/send_message.rs @@ -22,7 +22,7 @@ pub struct SendMessage<'s> { reply_markup: Option, } -impl<'c, 's> Request for SendMessage<'s> { +impl<'s> Request for SendMessage<'s> { type Type = JsonRequestType; type Response = JsonIdResponse; diff --git a/raw/src/requests/send_venue.rs b/raw/src/requests/send_venue.rs index 4d2e82b688..ff4ff259f6 100644 --- a/raw/src/requests/send_venue.rs +++ b/raw/src/requests/send_venue.rs @@ -41,8 +41,8 @@ impl<'t, 'a, 'f> SendVenue<'t, 'a, 'f> { { SendVenue { chat_id: chat.to_chat_ref(), - latitude: latitude, - longitude: longitude, + latitude, + longitude, title: title.into(), address: address.into(), disable_notification: false, diff --git a/raw/src/types/inline_query.rs b/raw/src/types/inline_query.rs index 7a5a3c2c75..9748ad3047 100644 --- a/raw/src/types/inline_query.rs +++ b/raw/src/types/inline_query.rs @@ -10,8 +10,8 @@ pub struct InlineQuery { pub offset: String, } -impl Into for InlineQuery { - fn into(self) -> InlineQueryId { - self.id +impl From for InlineQueryId { + fn from(val: InlineQuery) -> Self { + val.id } } diff --git a/raw/src/types/message.rs b/raw/src/types/message.rs index 19178afb47..d48322ecb8 100644 --- a/raw/src/types/message.rs +++ b/raw/src/types/message.rs @@ -223,7 +223,7 @@ impl Message { let id = raw.message_id; let from = match raw.from.clone() { Some(from) => from, - None => return Err(format!("Missing `from` field for Message")), + None => return Err("Missing `from` field for Message".to_string()), }; let date = raw.date; let chat = match raw.chat.clone() { @@ -231,7 +231,7 @@ impl Message { Chat::Group(x) => MessageChat::Group(x), Chat::Supergroup(x) => MessageChat::Supergroup(x), Chat::Unknown(x) => MessageChat::Unknown(x), - Chat::Channel(_) => return Err(format!("Channel chat in Message")), + Chat::Channel(_) => return Err("Channel chat in Message".to_string()), }; let reply_to_message = raw.reply_to_message.clone(); @@ -244,21 +244,21 @@ impl Message { raw.forward_from_message_id, &raw.forward_sender_name, ) { - (None, &None, &None, None, &None) => None, - (Some(date), &Some(ref from), &None, None, &None) => Some(Forward { - date: date, + (None, None, None, None, None) => None, + (Some(date), Some(from), None, None, None) => Some(Forward { + date, from: ForwardFrom::User { user: from.clone() }, }), - (Some(date), &None, &Some(Chat::Channel(ref channel)), Some(message_id), &None) => { + (Some(date), None, Some(Chat::Channel(channel)), Some(message_id), None) => { Some(Forward { - date: date, + date, from: ForwardFrom::Channel { channel: channel.clone(), - message_id: message_id, + message_id, }, }) } - (Some(date), &None, &None, None, &Some(ref sender_name)) => Some(Forward { + (Some(date), None, None, None, Some(sender_name)) => Some(Forward { date, from: ForwardFrom::ChannelHiddenUser { sender_name: sender_name.clone(), @@ -267,31 +267,33 @@ impl Message { ( Some(date), None, - Some(Chat::Supergroup(Supergroup { - id: chat_id, title, .. + &Some(Chat::Supergroup(Supergroup { + id: chat_id, + ref title, + .. })), None, None, ) => Some(Forward { date, from: ForwardFrom::HiddenGroupAdmin { - chat_id: chat_id.clone(), + chat_id, title: title.clone(), }, }), - _ => return Err(format!("invalid forward fields combination")), + _ => return Err("invalid forward fields combination".to_string()), }; let make_message = |kind| { Ok(Message { id: id.into(), - from: from, - date: date, - chat: chat, - forward: forward, - reply_to_message: reply_to_message, - edit_date: edit_date, - kind: kind, + from, + date, + chat, + forward, + reply_to_message, + edit_date, + kind, }) }; @@ -335,10 +337,10 @@ impl Message { } if let Some(text) = raw.text { - let entities = raw.entities.unwrap_or_else(Vec::new); + let entities = raw.entities.unwrap_or_default(); return make_message(MessageKind::Text { data: text, - entities: entities, + entities, }); } @@ -366,7 +368,7 @@ impl Message { maybe_field!(migrate_from_chat_id, MigrateFromChatId); maybe_field!(pinned_message, PinnedMessage); - make_message(MessageKind::Unknown { raw: raw }) + make_message(MessageKind::Unknown { raw }) } } @@ -377,7 +379,7 @@ impl<'de> Deserialize<'de> for Message { { let raw: RawMessage = Deserialize::deserialize(deserializer)?; - Self::from_raw_message(raw).map_err(|err| D::Error::custom(err)) + Self::from_raw_message(raw).map_err(D::Error::custom) } } @@ -387,7 +389,7 @@ impl ChannelPost { let date = raw.date; let chat = match raw.chat.clone() { Chat::Channel(channel) => channel, - _ => return Err(format!("Expected channel chat type for ChannelMessage")), + _ => return Err("Expected channel chat type for ChannelMessage".to_string()), }; let reply_to_message = raw.reply_to_message.clone(); let edit_date = raw.edit_date; @@ -399,21 +401,21 @@ impl ChannelPost { raw.forward_from_message_id, &raw.forward_sender_name, ) { - (None, &None, &None, None, &None) => None, - (Some(date), &Some(ref from), &None, None, &None) => Some(Forward { - date: date, + (None, None, None, None, None) => None, + (Some(date), Some(from), None, None, None) => Some(Forward { + date, from: ForwardFrom::User { user: from.clone() }, }), - (Some(date), &None, &Some(Chat::Channel(ref channel)), Some(message_id), &None) => { + (Some(date), None, Some(Chat::Channel(channel)), Some(message_id), None) => { Some(Forward { - date: date, + date, from: ForwardFrom::Channel { channel: channel.clone(), - message_id: message_id, + message_id, }, }) } - (Some(date), &None, &None, None, &Some(ref sender_name)) => Some(Forward { + (Some(date), None, None, None, Some(sender_name)) => Some(Forward { date, from: ForwardFrom::ChannelHiddenUser { sender_name: sender_name.clone(), @@ -422,30 +424,32 @@ impl ChannelPost { ( Some(date), None, - Some(Chat::Supergroup(Supergroup { - id: chat_id, title, .. + &Some(Chat::Supergroup(Supergroup { + id: chat_id, + ref title, + .. })), None, None, ) => Some(Forward { date, from: ForwardFrom::HiddenGroupAdmin { - chat_id: chat_id.clone(), + chat_id, title: title.clone(), }, }), - _ => return Err(format!("invalid forward fields combination")), + _ => return Err("invalid forward fields combination".to_string()), }; let make_message = |kind| { Ok(ChannelPost { id: id.into(), - date: date, - chat: chat, - forward: forward, - reply_to_message: reply_to_message, - edit_date: edit_date, - kind: kind, + date, + chat, + forward, + reply_to_message, + edit_date, + kind, }) }; @@ -489,10 +493,10 @@ impl ChannelPost { } if let Some(text) = raw.text { - let entities = raw.entities.unwrap_or_else(Vec::new); + let entities = raw.entities.unwrap_or_default(); return make_message(MessageKind::Text { data: text, - entities: entities, + entities, }); } @@ -520,7 +524,7 @@ impl ChannelPost { maybe_field!(migrate_from_chat_id, MigrateFromChatId); maybe_field!(pinned_message, PinnedMessage); - make_message(MessageKind::Unknown { raw: raw }) + make_message(MessageKind::Unknown { raw }) } } @@ -532,7 +536,7 @@ impl<'de> Deserialize<'de> for ChannelPost { { let raw: RawMessage = Deserialize::deserialize(deserializer)?; - Self::from_raw_message(raw).map_err(|err| D::Error::custom(err)) + Self::from_raw_message(raw).map_err(D::Error::custom) } } @@ -543,10 +547,7 @@ impl<'de> Deserialize<'de> for MessageOrChannelPost { D: Deserializer<'de>, { let raw: RawMessage = Deserialize::deserialize(deserializer)?; - let is_channel = match raw.chat { - Chat::Channel(_) => true, - _ => false, - }; + let is_channel = matches!(raw.chat, Chat::Channel(_)); let res = if is_channel { ChannelPost::from_raw_message(raw).map(MessageOrChannelPost::ChannelPost) @@ -554,7 +555,7 @@ impl<'de> Deserialize<'de> for MessageOrChannelPost { Message::from_raw_message(raw).map(MessageOrChannelPost::Message) }; - res.map_err(|err| D::Error::custom(err)) + res.map_err(D::Error::custom) } } @@ -716,9 +717,9 @@ impl<'de> Deserialize<'de> for MessageEntity { }; Ok(MessageEntity { - offset: offset, - length: length, - kind: kind, + offset, + length, + kind, }) } } diff --git a/raw/src/types/primitive.rs b/raw/src/types/primitive.rs index b2d9cca11f..ce0681c44e 100644 --- a/raw/src/types/primitive.rs +++ b/raw/src/types/primitive.rs @@ -10,7 +10,7 @@ pub type Integer = i64; /// The Telegram `Float`, currently f32. pub type Float = f32; -#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct True; impl<'de> Deserialize<'de> for True { diff --git a/raw/src/types/refs.rs b/raw/src/types/refs.rs index 981316b293..9c57a77691 100644 --- a/raw/src/types/refs.rs +++ b/raw/src/types/refs.rs @@ -82,8 +82,8 @@ impl ToSourceChat for ChannelPost { impl ToSourceChat for MessageOrChannelPost { fn to_source_chat(&self) -> ChatId { match self { - &MessageOrChannelPost::Message(ref message) => message.to_source_chat(), - &MessageOrChannelPost::ChannelPost(ref channel_post) => channel_post.to_source_chat(), + MessageOrChannelPost::Message(message) => message.to_source_chat(), + MessageOrChannelPost::ChannelPost(channel_post) => channel_post.to_source_chat(), } } } @@ -166,9 +166,9 @@ impl Serialize for ChatRef { where S: Serializer, { - match *self { - ChatRef::Id(id) => serializer.serialize_i64(id.into()), - ChatRef::ChannelUsername(ref username) => serializer.serialize_str(&username), + match self { + &ChatRef::Id(id) => serializer.serialize_i64(id.into()), + ChatRef::ChannelUsername(username) => serializer.serialize_str(username), } } } @@ -306,8 +306,8 @@ impl ToMessageId for ChannelPost { impl ToMessageId for MessageOrChannelPost { fn to_message_id(&self) -> MessageId { match self { - &MessageOrChannelPost::Message(ref message) => message.to_message_id(), - &MessageOrChannelPost::ChannelPost(ref channel_post) => channel_post.to_message_id(), + MessageOrChannelPost::Message(message) => message.to_message_id(), + MessageOrChannelPost::ChannelPost(channel_post) => channel_post.to_message_id(), } } } @@ -364,7 +364,7 @@ impl<'a> From<&'a str> for FileRef { } } -impl<'a> From for FileRef { +impl From for FileRef { fn from(s: String) -> Self { FileRef { inner: s.clone() } } diff --git a/raw/src/types/reply_markup.rs b/raw/src/types/reply_markup.rs index 85cbad9025..cf3302ca1c 100644 --- a/raw/src/types/reply_markup.rs +++ b/raw/src/types/reply_markup.rs @@ -42,7 +42,7 @@ impl From for ReplyMarkup { } /// This object represents a custom keyboard with reply options. -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] +#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Serialize)] pub struct ReplyKeyboardMarkup { keyboard: Vec>, #[serde(skip_serializing_if = "Not::not")] @@ -55,12 +55,7 @@ pub struct ReplyKeyboardMarkup { impl ReplyKeyboardMarkup { pub fn new() -> Self { - ReplyKeyboardMarkup { - keyboard: Vec::new(), - resize_keyboard: false, - one_time_keyboard: false, - selective: false, - } + Self::default() } fn init(rows: Vec>) -> Self { @@ -166,7 +161,7 @@ impl From for KeyboardButton { /// By default, custom keyboards are displayed until a new keyboard is sent /// by a bot. An exception is made for one-time keyboards that are hidden /// immediately after the user presses a button (see ReplyKeyboardMarkup). -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] +#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Serialize)] pub struct ReplyKeyboardRemove { remove_keyboard: True, #[serde(skip_serializing_if = "Not::not")] @@ -175,10 +170,7 @@ pub struct ReplyKeyboardRemove { impl ReplyKeyboardRemove { pub fn new() -> Self { - Self { - remove_keyboard: True, - selective: false, - } + Self::default() } /// Use this method if you want to force reply from specific users only. @@ -192,16 +184,14 @@ impl ReplyKeyboardRemove { } /// This object represents an inline keyboard that appears right next to the message it belongs to. -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] +#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Serialize)] pub struct InlineKeyboardMarkup { inline_keyboard: Vec>, } impl InlineKeyboardMarkup { pub fn new() -> Self { - Self { - inline_keyboard: Default::default(), - } + Self::default() } fn init(inline_keyboard: Vec>) -> Self { @@ -298,7 +288,7 @@ pub enum InlineKeyboardButtonKind { /// selected the bot‘s message and tapped ’Reply'). This can be /// extremely useful if you want to create user-friendly step-by-step /// interfaces without having to sacrifice privacy mod -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] +#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Serialize)] pub struct ForceReply { force_reply: True, #[serde(skip_serializing_if = "Not::not")] @@ -307,10 +297,7 @@ pub struct ForceReply { impl ForceReply { pub fn new() -> Self { - Self { - force_reply: True, - selective: false, - } + Self::default() } /// Use this method if you want to force reply from specific users only. diff --git a/raw/src/types/response_parameters.rs b/raw/src/types/response_parameters.rs index 05e3cd6dd0..34ca3342cf 100644 --- a/raw/src/types/response_parameters.rs +++ b/raw/src/types/response_parameters.rs @@ -27,10 +27,10 @@ impl<'de, T: Deserialize<'de>> Deserialize<'de> for ResponseWrapper { let raw: RawResponse = Deserialize::deserialize(deserializer)?; match (raw.ok, raw.description, raw.result) { (false, Some(description), None) => Ok(ResponseWrapper::Error { - description: description, + description, parameters: raw.parameters, }), - (true, None, Some(result)) => Ok(ResponseWrapper::Success { result: result }), + (true, None, Some(result)) => Ok(ResponseWrapper::Success { result }), _ => Err(D::Error::custom("ambiguous response")), } } diff --git a/raw/tests/update.rs b/raw/tests/update.rs index 12cc783e7b..73e300138e 100644 --- a/raw/tests/update.rs +++ b/raw/tests/update.rs @@ -1,7 +1,7 @@ use std::fs::File; use std::io::prelude::*; -use telegram_bot_raw::types::message::MessageKind; +use telegram_bot_raw::types::message::{Message, MessageKind}; use telegram_bot_raw::types::update::{Update, UpdateKind}; macro_rules! make_test { @@ -22,35 +22,29 @@ macro_rules! make_test { } make_test!(migrate_from_chat_id, |update: Update| { - if let UpdateKind::Message(message) = update.kind { - if let MessageKind::MigrateFromChatId { .. } = message.kind { - return (); - } - } - assert!(false) + assert!(matches!( + update.kind, + UpdateKind::Message(Message { + kind: MessageKind::MigrateFromChatId { .. }, + .. + }) + )); }); make_test!(migrate_to_chat_id, |update: Update| { - if let UpdateKind::Message(message) = update.kind { - if let MessageKind::MigrateToChatId { .. } = message.kind { - return (); - } - } - assert!(false) + assert!(matches!( + update.kind, + UpdateKind::Message(Message { + kind: MessageKind::MigrateToChatId { .. }, + .. + }) + )); }); make_test!(inline_query, |update: Update| { - if let UpdateKind::InlineQuery(_query) = update.kind { - return (); - } - - assert!(false) + assert!(matches!(update.kind, UpdateKind::InlineQuery(_))); }); make_test!(regression_test_208, |update: Update| { - if let UpdateKind::CallbackQuery(_query) = update.kind { - return (); - } - - assert!(false) + assert!(matches!(update.kind, UpdateKind::CallbackQuery(_))); }); From be2f1a15828f56e55a1596dc30c0106029f56ec1 Mon Sep 17 00:00:00 2001 From: Yotam Ofek Date: Mon, 21 Oct 2024 18:15:39 +0000 Subject: [PATCH 4/5] [lib] create HeaderValue at compile time --- lib/src/connector/hyper.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/lib/src/connector/hyper.rs b/lib/src/connector/hyper.rs index 905aebf0a5..6b832b0f9a 100644 --- a/lib/src/connector/hyper.rs +++ b/lib/src/connector/hyper.rs @@ -4,11 +4,11 @@ use std::pin::Pin; use std::str::FromStr; use bytes::Bytes; -use futures::{Future, FutureExt, TryFutureExt}; +use futures::{Future, FutureExt}; use hyper::{ body::to_bytes, client::{connect::Connect, Client}, - header::CONTENT_TYPE, + header::{HeaderValue, CONTENT_TYPE}, http::Error as HttpError, Method, Request, Uri, }; @@ -60,13 +60,11 @@ impl Connector for let request = match req.body { TelegramBody::Empty => http_request.body(Into::::into(vec![])), TelegramBody::Json(body) => { - let content_type = "application/json" - .parse() - .map_err(HttpError::from) - .map_err(ErrorKind::from)?; + const JSON_MIME_TYPE: HeaderValue = + HeaderValue::from_static("application/json"); http_request .headers_mut() - .map(move |headers| headers.insert(CONTENT_TYPE, content_type)); + .map(move |headers| headers.insert(CONTENT_TYPE, JSON_MIME_TYPE)); http_request.body(Into::::into(body)) } TelegramBody::Multipart(parts) => { From 147b683c50b988abac1696f682226e50976204c9 Mon Sep 17 00:00:00 2001 From: Yotam Ofek Date: Tue, 22 Oct 2024 09:11:09 +0000 Subject: [PATCH 5/5] capture idents in format strings --- lib/src/connector/hyper.rs | 11 +++++------ lib/src/errors.rs | 8 ++++---- raw/src/requests/_base/http.rs | 6 +++--- raw/src/types/refs.rs | 6 +++--- 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/lib/src/connector/hyper.rs b/lib/src/connector/hyper.rs index 6b832b0f9a..ed86716847 100644 --- a/lib/src/connector/hyper.rs +++ b/lib/src/connector/hyper.rs @@ -121,11 +121,10 @@ impl Connector for let boundary = prepared.boundary(); - let content_type = - format!("multipart/form-data;boundary={bound}", bound = boundary) - .parse() - .map_err(HttpError::from) - .map_err(ErrorKind::from)?; + let content_type = format!("multipart/form-data;boundary={boundary}") + .parse() + .map_err(HttpError::from) + .map_err(ErrorKind::from)?; if let Some(headers) = http_request.headers_mut() { headers.insert(CONTENT_TYPE, content_type); } @@ -134,7 +133,7 @@ impl Connector for prepared.read_to_end(&mut bytes).map_err(ErrorKind::from)?; http_request.body(bytes.into()) } - body => panic!("Unknown body type {:?}", body), + body => panic!("Unknown body type {body:?}"), } .map_err(ErrorKind::from)?; diff --git a/lib/src/errors.rs b/lib/src/errors.rs index 8ee859264e..30fa2b6720 100644 --- a/lib/src/errors.rs +++ b/lib/src/errors.rs @@ -46,10 +46,10 @@ impl From for Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.0 { - ErrorKind::Raw(error) => write!(f, "{}", error), - ErrorKind::Hyper(error) => write!(f, "{}", error), - ErrorKind::Http(error) => write!(f, "{}", error), - ErrorKind::Io(error) => write!(f, "{}", error), + ErrorKind::Raw(error) => write!(f, "{error}"), + ErrorKind::Hyper(error) => write!(f, "{error}"), + ErrorKind::Http(error) => write!(f, "{error}"), + ErrorKind::Io(error) => write!(f, "{error}"), ErrorKind::InvalidMultipartFilename => write!(f, "invalid multipart filename"), } } diff --git a/raw/src/requests/_base/http.rs b/raw/src/requests/_base/http.rs index 54644f1d6e..70565cfc37 100644 --- a/raw/src/requests/_base/http.rs +++ b/raw/src/requests/_base/http.rs @@ -49,9 +49,9 @@ pub enum Body { impl fmt::Display for Body { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { - Body::Empty => "".fmt(f), - Body::Multipart(multipart) => write!(f, "{:?}", multipart), - Body::Json(s) => s.fmt(f), + Body::Empty => f.write_str(""), + Body::Multipart(multipart) => write!(f, "{multipart:?}"), + Body::Json(s) => f.write_str(s), Body::__Nonexhaustive => unreachable!(), } } diff --git a/raw/src/types/refs.rs b/raw/src/types/refs.rs index 9c57a77691..545ef80f44 100644 --- a/raw/src/types/refs.rs +++ b/raw/src/types/refs.rs @@ -175,9 +175,9 @@ impl Serialize for ChatRef { impl fmt::Display for ChatRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - ChatRef::Id(id) => write!(f, "{}", id), - ChatRef::ChannelUsername(ref username) => write!(f, "{}", username), + match self { + ChatRef::Id(id) => write!(f, "{id}"), + ChatRef::ChannelUsername(username) => write!(f, "{username}"), } } }