Skip to content
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

Clippy fixes #272

Open
wants to merge 5 commits into
base: main
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
33 changes: 17 additions & 16 deletions lib/examples/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}

Expand Down
5 changes: 2 additions & 3 deletions lib/examples/live_location.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?
}
}
}
Expand Down
23 changes: 12 additions & 11 deletions lib/examples/poll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
15 changes: 7 additions & 8 deletions lib/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(_) => "<invalid utf-8 string>"
},
None => "<empty body>",
}, "response received"
response = %http_response
.body
.as_deref()
.map(|body| std::str::from_utf8(body).unwrap_or("<invalid utf-8 string>"))
.unwrap_or("<empty body>"),
"response received"
);

let response = Resp::deserialize(http_response).map_err(ErrorKind::from)?;
Expand Down
37 changes: 15 additions & 22 deletions lib/src/connector/hyper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ 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,
};
Expand Down Expand Up @@ -60,13 +60,11 @@ impl<C: Connect + std::fmt::Debug + 'static + Clone + Send + Sync> Connector for
let request = match req.body {
TelegramBody::Empty => http_request.body(Into::<hyper::Body>::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::<hyper::Body>::into(body))
}
TelegramBody::Multipart(parts) => {
Expand Down Expand Up @@ -123,32 +121,27 @@ impl<C: Connect + std::fmt::Debug + 'static + Clone + Send + Sync> 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)?;
http_request.headers_mut().map(move |headers| {
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);
});
}

let mut bytes = Vec::new();
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)?;

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<u8> {
acc.extend_from_slice(&chunk);
acc
});
let body = to_bytes(response.into_body())
.await
.unwrap_or_default()
.to_vec();

Ok::<HttpResponse, Error>(HttpResponse { body: Some(body) })
};
Expand Down
8 changes: 4 additions & 4 deletions lib/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ impl From<ErrorKind> 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"),
}
}
Expand Down
7 changes: 4 additions & 3 deletions lib/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ 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<Box<dyn Future<Output = Result<Option<Vec<Update>>, 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"]
pub struct UpdatesStream {
api: Api,
last_update: Integer,
buffer: VecDeque<Update>,
current_request:
Option<Pin<Box<dyn Future<Output = Result<Option<Vec<Update>>, Error>> + Send>>>,
current_request: Option<Request>,
timeout: Duration,
allowed_updates: Vec<AllowedUpdate>,
limit: Integer,
Expand Down Expand Up @@ -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);
Expand Down
28 changes: 12 additions & 16 deletions lib/src/util/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>;
fn text(&self) -> Option<String>;
}

impl MessageText for MessageOrChannelPost {
fn text<'a>(&'a self) -> Option<String> {
fn text(&self) -> Option<String> {
match self {
MessageOrChannelPost::Message(msg) => msg.text(),
MessageOrChannelPost::ChannelPost(post) => post.text(),
Expand All @@ -25,13 +25,13 @@ impl MessageText for MessageOrChannelPost {
}

impl MessageText for Message {
fn text<'a>(&'a self) -> Option<String> {
fn text(&self) -> Option<String> {
self.kind.text()
}
}

impl MessageText for MessageKind {
fn text<'a>(&'a self) -> Option<String> {
fn text(&self) -> Option<String> {
match self {
MessageKind::Text { data, .. } => Some(data.to_owned()),
MessageKind::Audio { data } => data.title.to_owned(),
Expand Down Expand Up @@ -64,7 +64,7 @@ impl MessageText for MessageKind {
}

impl MessageText for ChannelPost {
fn text<'a>(&'a self) -> Option<String> {
fn text(&self) -> Option<String> {
self.kind.text()
}
}
Expand All @@ -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<Vec<GetFile>>;
fn get_files(&self) -> Option<Vec<GetFile>>;
}

impl MessageGetFiles for MessageOrChannelPost {
fn get_files<'a>(&'a self) -> Option<Vec<GetFile>> {
fn get_files(&self) -> Option<Vec<GetFile>> {
match self {
MessageOrChannelPost::Message(msg) => msg.get_files(),
MessageOrChannelPost::ChannelPost(post) => post.get_files(),
Expand All @@ -89,13 +89,13 @@ impl MessageGetFiles for MessageOrChannelPost {
}

impl MessageGetFiles for Message {
fn get_files<'a>(&'a self) -> Option<Vec<GetFile>> {
fn get_files(&self) -> Option<Vec<GetFile>> {
self.kind.get_files()
}
}

impl MessageGetFiles for MessageKind {
fn get_files<'a>(&'a self) -> Option<Vec<GetFile>> {
fn get_files(&self) -> Option<Vec<GetFile>> {
match self {
MessageKind::Text { .. } => None,
MessageKind::Audio { data } => Some(vec![data.get_file()]),
Expand All @@ -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()];
Expand All @@ -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,
Expand All @@ -148,7 +144,7 @@ impl MessageGetFiles for MessageKind {
}

impl MessageGetFiles for ChannelPost {
fn get_files<'a>(&'a self) -> Option<Vec<GetFile>> {
fn get_files(&self) -> Option<Vec<GetFile>> {
self.kind.get_files()
}
}
2 changes: 1 addition & 1 deletion raw/src/requests/_base/_base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl<Resp: ResponseType + 'static> Request for DetachedRequest<Resp> {
type Response = Resp;

fn serialize(&self) -> Result<HttpRequest, Error> {
Ok(Self::Type::serialize((), &self.http_request)?)
Self::Type::serialize((), &self.http_request)
}
}

Expand Down
10 changes: 5 additions & 5 deletions raw/src/requests/_base/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"),
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions raw/src/requests/_base/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => "<empty body>".fmt(f),
Body::Multipart(multipart) => write!(f, "{:?}", multipart),
Body::Json(s) => s.fmt(f),
Body::Empty => f.write_str("<empty body>"),
Body::Multipart(multipart) => write!(f, "{multipart:?}"),
Body::Json(s) => f.write_str(s),
Body::__Nonexhaustive => unreachable!(),
}
}
Expand Down
4 changes: 2 additions & 2 deletions raw/src/requests/_base/request_types/detached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ impl RequestType for DetachedRequestType {

fn serialize(_options: Self::Options, request: &Self::Request) -> Result<HttpRequest, Error> {
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()),
}
}
}
2 changes: 1 addition & 1 deletion raw/src/requests/_base/request_types/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl<Request: Serialize> RequestType for JsonRequestType<Request> {
fn serialize(url: Self::Options, request: &Self::Request) -> Result<HttpRequest, Error> {
let body = serde_json::to_string(&request).map_err(ErrorKind::from)?;
Ok(HttpRequest {
url: url,
url,
method: Method::Post,
body: Body::Json(body),
})
Expand Down
Loading