1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00

Fix clippy warnings (#168)

This commit is contained in:
Yuki Okushi 2019-09-05 00:04:57 +09:00 committed by GitHub
parent bb639d5fe3
commit f232b6c684
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 41 additions and 46 deletions

View File

@ -1,4 +1,4 @@
use actix_web::{error, web}; use actix_web::web;
use crate::handlers::{parts, products}; use crate::handlers::{parts, products};

View File

@ -1,9 +1,5 @@
use actix_multipart::{Field, Multipart, MultipartError}; use actix_web::{web, Error, HttpResponse};
use actix_web::{error, web, Error, HttpResponse}; use futures::{future::ok as fut_ok, Future};
use futures::{
future::{err as fut_err, ok as fut_ok, Either},
Future, Stream,
};
use crate::common::{Part, Product}; use crate::common::{Part, Product};

View File

@ -1,9 +1,5 @@
use actix_multipart::{Field, Multipart, MultipartError}; use actix_web::{web, Error, HttpResponse};
use actix_web::{error, web, Error, HttpResponse}; use futures::{future::ok as fut_ok, Future};
use futures::{
future::{err as fut_err, ok as fut_ok, Either},
Future, Stream,
};
use crate::common::{Part, Product}; use crate::common::{Part, Product};

View File

@ -132,7 +132,7 @@ fn main() -> io::Result<()> {
.route( .route(
web::route() web::route()
.guard(guard::Not(guard::Get())) .guard(guard::Not(guard::Get()))
.to(|| HttpResponse::MethodNotAllowed()), .to(HttpResponse::MethodNotAllowed),
), ),
) )
}) })

View File

@ -3,7 +3,10 @@ use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpResponse, HttpServer}; use actix_web::{middleware, web, App, HttpResponse, HttpServer};
fn index(id: Identity) -> String { fn index(id: Identity) -> String {
format!("Hello {}", id.identity().unwrap_or("Anonymous".to_owned())) format!(
"Hello {}",
id.identity().unwrap_or_else(|| "Anonymous".to_owned())
)
} }
fn login(id: Identity) -> HttpResponse { fn login(id: Identity) -> HttpResponse {

View File

@ -86,7 +86,10 @@ fn rpc_select(
pub trait ImplNetwork { pub trait ImplNetwork {
fn ping(&self) -> String; fn ping(&self) -> String;
fn wait(&self, d: u64) -> Box<Future<Item = String, Error = Box<error::Error>>>; fn wait(
&self,
d: u64,
) -> Box<dyn Future<Item = String, Error = Box<dyn error::Error>>>;
fn get(&self) -> u32; fn get(&self) -> u32;
fn inc(&mut self); fn inc(&mut self);
@ -107,9 +110,12 @@ impl ImplNetwork for ObjNetwork {
String::from("pong") String::from("pong")
} }
fn wait(&self, d: u64) -> Box<Future<Item = String, Error = Box<error::Error>>> { fn wait(
&self,
d: u64,
) -> Box<dyn Future<Item = String, Error = Box<dyn error::Error>>> {
if let Err(e) = Delay::new(Duration::from_secs(d)).wait() { if let Err(e) = Delay::new(Duration::from_secs(d)).wait() {
let e: Box<error::Error> = Box::new(e); let e: Box<dyn error::Error> = Box::new(e);
return Box::new(future::err(e)); return Box::new(future::err(e));
}; };
Box::new(future::ok(String::from("pong"))) Box::new(future::ok(String::from("pong")))
@ -126,11 +132,11 @@ impl ImplNetwork for ObjNetwork {
#[derive(Clone)] #[derive(Clone)]
pub struct AppState { pub struct AppState {
network: Arc<RwLock<ImplNetwork>>, network: Arc<RwLock<dyn ImplNetwork>>,
} }
impl AppState { impl AppState {
pub fn new(network: Arc<RwLock<ImplNetwork>>) -> Self { pub fn new(network: Arc<RwLock<dyn ImplNetwork>>) -> Self {
Self { network } Self { network }
} }
} }

View File

@ -43,7 +43,7 @@ where
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready() self.service.poll_ready()

View File

@ -1,4 +1,4 @@
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] #![allow(clippy::needless_pass_by_value)]
//! Application may have multiple data objects that are shared across //! Application may have multiple data objects that are shared across
//! all handlers within same Application. Data could be added //! all handlers within same Application. Data could be added
//! with `App::data()` method, multiple different data objects could be added. //! with `App::data()` method, multiple different data objects could be added.

View File

@ -17,7 +17,7 @@ struct Index;
fn index(query: web::Query<HashMap<String, String>>) -> Result<HttpResponse> { fn index(query: web::Query<HashMap<String, String>>) -> Result<HttpResponse> {
let s = if let Some(name) = query.get("name") { let s = if let Some(name) = query.get("name") {
UserTemplate { UserTemplate {
name: name, name,
text: "Welcome!", text: "Welcome!",
} }
.render() .render()

View File

@ -68,7 +68,7 @@ impl WsChatSession {
fn send_msg(&self, msg: &str) { fn send_msg(&self, msg: &str) {
let content = format!( let content = format!(
"{}: {}", "{}: {}",
self.name.clone().unwrap_or("anon".to_string()), self.name.clone().unwrap_or_else(|| "anon".to_string()),
msg msg
); );
let msg = SendMessage(self.room.clone(), self.id, content); let msg = SendMessage(self.room.clone(), self.id, content);
@ -87,7 +87,7 @@ impl Actor for WsChatSession {
fn stopped(&mut self, _ctx: &mut Self::Context) { fn stopped(&mut self, _ctx: &mut Self::Context) {
info!( info!(
"WsChatSession closed for {}({}) in room {}", "WsChatSession closed for {}({}) in room {}",
self.name.clone().unwrap_or("anon".to_string()), self.name.clone().unwrap_or_else(|| "anon".to_string()),
self.id, self.id,
self.room self.room
); );

View File

@ -42,7 +42,7 @@ impl WsChatServer {
id: Option<usize>, id: Option<usize>,
client: Client, client: Client,
) -> usize { ) -> usize {
let mut id = id.unwrap_or_else(|| rand::random::<usize>()); let mut id = id.unwrap_or_else(rand::random::<usize>);
if let Some(room) = self.rooms.get_mut(room_name) { if let Some(room) = self.rooms.get_mut(room_name) {
loop { loop {
if room.contains_key(&id) { if room.contains_key(&id) {
@ -94,7 +94,7 @@ impl Handler<JoinRoom> for WsChatServer {
let id = self.add_client_to_room(&room_name, None, client); let id = self.add_client_to_room(&room_name, None, client);
let join_msg = format!( let join_msg = format!(
"{} joined {}", "{} joined {}",
client_name.unwrap_or("anon".to_string()), client_name.unwrap_or_else(|| "anon".to_string()),
room_name room_name
); );
self.send_chat_message(&room_name, &join_msg, id); self.send_chat_message(&room_name, &join_msg, id);

View File

@ -164,7 +164,7 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
// send message to chat server // send message to chat server
self.addr.do_send(server::ClientMessage { self.addr.do_send(server::ClientMessage {
id: self.id, id: self.id,
msg: msg, msg,
room: self.room.clone(), room: self.room.clone(),
}) })
} }

View File

@ -68,7 +68,7 @@ impl Default for ChatServer {
ChatServer { ChatServer {
sessions: HashMap::new(), sessions: HashMap::new(),
rooms: rooms, rooms,
rng: rand::thread_rng(), rng: rand::thread_rng(),
} }
} }

View File

@ -154,7 +154,7 @@ impl StreamHandler<codec::ChatResponse, io::Error> for ChatClient {
for room in rooms { for room in rooms {
println!("{}", room); println!("{}", room);
} }
println!(""); println!();
} }
_ => (), _ => (),
} }

View File

@ -171,7 +171,7 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
// send message to chat server // send message to chat server
self.addr.do_send(server::Message { self.addr.do_send(server::Message {
id: self.id, id: self.id,
msg: msg, msg,
room: self.room.clone(), room: self.room.clone(),
}) })
} }
@ -212,7 +212,7 @@ impl WsChatSession {
} }
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
let _ = env_logger::init(); env_logger::init();
let sys = actix::System::new("websocket-example"); let sys = actix::System::new("websocket-example");
// Start chat server actor // Start chat server actor

View File

@ -66,7 +66,7 @@ impl Default for ChatServer {
ChatServer { ChatServer {
sessions: HashMap::new(), sessions: HashMap::new(),
rooms: rooms, rooms,
rng: rand::thread_rng(), rng: rand::thread_rng(),
} }
} }

View File

@ -138,10 +138,10 @@ impl ChatSession {
) -> ChatSession { ) -> ChatSession {
ChatSession { ChatSession {
id: 0, id: 0,
addr: addr, addr,
hb: Instant::now(), hb: Instant::now(),
room: "Main".to_owned(), room: "Main".to_owned(),
framed: framed, framed,
} }
} }
@ -187,10 +187,8 @@ impl TcpServer {
// implement stream handler `StreamHandler<(TcpStream, // implement stream handler `StreamHandler<(TcpStream,
// net::SocketAddr), io::Error>` // net::SocketAddr), io::Error>`
TcpServer::create(|ctx| { TcpServer::create(|ctx| {
ctx.add_message_stream( ctx.add_message_stream(listener.incoming().map_err(|_| ()).map(TcpConnect));
listener.incoming().map_err(|_| ()).map(|s| TcpConnect(s)), TcpServer { chat }
);
TcpServer { chat: chat }
}); });
} }
} }

View File

@ -18,7 +18,7 @@ use futures::{
fn main() { fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info"); ::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init(); env_logger::init();
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
Arbiter::spawn(lazy(|| { Arbiter::spawn(lazy(|| {
@ -27,7 +27,6 @@ fn main() {
.connect() .connect()
.map_err(|e| { .map_err(|e| {
println!("Error: {}", e); println!("Error: {}", e);
()
}) })
.map(|(response, framed)| { .map(|(response, framed)| {
println!("{:?}", response); println!("{:?}", response);
@ -46,8 +45,6 @@ fn main() {
} }
addr.do_send(ClientCommand(cmd)); addr.do_send(ClientCommand(cmd));
}); });
()
}) })
})); }));
@ -113,9 +110,8 @@ where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
{ {
fn handle(&mut self, msg: Frame, _ctx: &mut Context<Self>) { fn handle(&mut self, msg: Frame, _ctx: &mut Context<Self>) {
match msg { if let Frame::Text(txt) = msg {
Frame::Text(txt) => println!("Server: {:?}", txt), println!("Server: {:?}", txt)
_ => (),
} }
} }