Consistent formatting

- Format manually with `cargo +nightly fmt`
This commit is contained in:
usagi-flow 2023-04-15 12:15:54 +02:00
parent 0cfe50bb95
commit 8d45765aa8
No known key found for this signature in database
4 changed files with 89 additions and 58 deletions

23
rustfmt.toml Normal file
View File

@ -0,0 +1,23 @@
# See: https://rust-lang.github.io/rustfmt
# Check:
# cargo +nightly fmt --check
# Install the nightly toolchain (required for the unstable features):
# rustup toolchain install nightly
unstable_features = true # For now, unstable features are unavailable on a stable rust channel
# https://github.com/rust-lang/rustfmt/issues/3387
hard_tabs = true
max_width = 120 # Default is 100
chain_width = 100 # Default is 60
fn_call_width = 100 # Default is 60
single_line_if_else_max_width = 80 # Default is 50
brace_style = "AlwaysNextLine" # Unstable, default is "SameLineWhere"
control_brace_style = "ClosingNextLine" # Unstable, default is "AlwaysSameLine"
imports_granularity = "Module" # Unstable, default is "Preserve"
reorder_impl_items = true # Unstable
trailing_comma = "Never" # Unstable, default is "Vertical"
#reorder_impl_items = true # Unstable
newline_style = "Unix" # Default is "Auto"

View File

@ -1,13 +1,10 @@
use std::net::SocketAddr; use std::net::SocketAddr;
use tokio::io::AsyncReadExt; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::AsyncWriteExt; use tokio::net::{TcpListener, TcpStream};
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::watch; use tokio::sync::watch;
use tokio::sync::watch::Receiver;
use tokio::sync::watch::Sender;
use tokio::sync::watch::error::SendError; use tokio::sync::watch::error::SendError;
use tokio::sync::watch::{Receiver, Sender};
use tokio::time::sleep; use tokio::time::sleep;
use tokio_serial::SerialPortBuilderExt; use tokio_serial::SerialPortBuilderExt;
@ -20,9 +17,7 @@ lazy_static! {
}; };
} }
pub struct App pub struct App {}
{
}
impl App impl App
{ {
@ -66,8 +61,11 @@ impl App
} }
}); });
log::info!("Listening for connections on {}:{}...", log::info!(
Config::get().await.bind_address, Config::get().await.bind_port); "Listening for connections on {}:{}...",
Config::get().await.bind_address,
Config::get().await.bind_port
);
loop { loop {
let (socket, peer_address) = listener.accept().await?; let (socket, peer_address) = listener.accept().await?;
@ -81,10 +79,12 @@ impl App
} }
} }
async fn serve(&self, async fn serve(
&self,
mut socket: TcpStream, mut socket: TcpStream,
peer_address: SocketAddr, peer_address: SocketAddr,
mut receiver: Receiver<Chunk>) -> Result<(), std::io::Error> mut receiver: Receiver<Chunk>
) -> Result<(), std::io::Error>
{ {
log::info!("{:?} connected", peer_address); log::info!("{:?} connected", peer_address);
@ -110,8 +110,7 @@ impl App
} }
else { else {
// The sender has been dropped; disconnect gracefully from the peer. // The sender has been dropped; disconnect gracefully from the peer.
log::warn!("Serial data sender has been dropped, disconnecting from peer: {:?}", log::warn!("Serial data sender has been dropped, disconnecting from peer: {:?}", peer_address);
peer_address);
socket.shutdown().await?; socket.shutdown().await?;
let result: Result<(), std::io::Error> = Ok(()); let result: Result<(), std::io::Error> = Ok(());
@ -125,7 +124,7 @@ impl App
// Quickly copy the data into a vec and release the borrowed chunk // Quickly copy the data into a vec and release the borrowed chunk
// TODO: use borrow_and_update() instead? // TODO: use borrow_and_update() instead?
let chunk = receiver_instance.borrow(); let chunk = receiver_instance.borrow();
return chunk.data[0 .. chunk.size].to_vec(); return chunk.data[0..chunk.size].to_vec();
} }
pub async fn read_serial(&self, sender: &Sender<Chunk>) -> Result<bool, String> pub async fn read_serial(&self, sender: &Sender<Chunk>) -> Result<bool, String>
@ -170,10 +169,13 @@ impl App
size: bytes size: bytes
}; };
sender.send(chunk).or_else(|_: SendError<Chunk>| -> Result<(), ()> { sender
log::warn!("Failed to transfer obtained serial data to the TCP connection(s)"); .send(chunk)
return Ok(()); .or_else(|_: SendError<Chunk>| -> Result<(), ()> {
}).unwrap(); log::warn!("Failed to transfer obtained serial data to the TCP connection(s)");
return Ok(());
})
.unwrap();
} }
else { else {
// No more data // No more data

View File

@ -11,6 +11,6 @@ impl Default for Chunk
return Chunk { return Chunk {
data: [0u8; 1024], data: [0u8; 1024],
size: 0usize size: 0usize
} };
} }
} }

View File

@ -8,7 +8,7 @@ mod config;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use app::App; use app::App;
use clap::{Arg, command}; use clap::{command, Arg};
use crate::config::Config; use crate::config::Config;
@ -20,7 +20,7 @@ struct CLIContext<'a>
#[tokio::main] #[tokio::main]
async fn main() async fn main()
{ {
simple_logger::SimpleLogger::new().with_level(log::LevelFilter::Info) .env().init().unwrap(); simple_logger::SimpleLogger::new().with_level(log::LevelFilter::Info).env().init().unwrap();
let default_panic = std::panic::take_hook(); let default_panic = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| { std::panic::set_hook(Box::new(move |info| {
@ -37,7 +37,7 @@ async fn main()
Ok(()) => { Ok(()) => {
let app = App::instance(); let app = App::instance();
app.run().await.unwrap(); app.run().await.unwrap();
}, }
Err(e) => { Err(e) => {
log::error!("{}\n", e); log::error!("{}\n", e);
context.command.print_help().unwrap(); context.command.print_help().unwrap();
@ -48,40 +48,46 @@ async fn main()
async fn init_cli<'a>(context: &mut CLIContext<'a>) -> Result<(), &'a str> async fn init_cli<'a>(context: &mut CLIContext<'a>) -> Result<(), &'a str>
{ {
context.command = command!() context.command = command!()
.arg(Arg::new("no-polling") .arg(Arg::new("no-polling").short('n').takes_value(false).display_order(0).help(
.short('n') "(optional) If set, do not poll the serial device: \
.takes_value(false) If the device is/becomes unavailable, terminate immediately."
.display_order(0) ))
.help("(optional) If set, do not poll the serial device: \ .arg(
If the device is/becomes unavailable, terminate immediately.")) Arg::new("serial-device-path")
.arg(Arg::new("serial-device-path") .long("serial-device")
.long("serial-device") .short('s')
.short('s') .required(true)
.required(true) .value_name("path")
.value_name("path") .display_order(1)
.display_order(1) .help("The serial device to read from, e.g. /dev/ttyUSB0")
.help("The serial device to read from, e.g. /dev/ttyUSB0")) )
.arg(Arg::new("serial-baud-rate") .arg(
.long("baud-rate") Arg::new("serial-baud-rate")
.short('b') .long("baud-rate")
.required(true) .short('b')
.value_name("number") .required(true)
.display_order(2) .value_name("number")
.help("The serial baud rate to use, e.g. 115200")) .display_order(2)
.arg(Arg::new("address") .help("The serial baud rate to use, e.g. 115200")
.long("address") )
.short('a') .arg(
.default_value("0.0.0.0") Arg::new("address")
.value_name("ip") .long("address")
.display_order(3) .short('a')
.help("The IP (v4 or v6) address to bind to")) .default_value("0.0.0.0")
.arg(Arg::new("port") .value_name("ip")
.long("port") .display_order(3)
.short('p') .help("The IP (v4 or v6) address to bind to")
.required(true) )
.value_name("number") .arg(
.display_order(4) Arg::new("port")
.help("The port to listen on")); .long("port")
.short('p')
.required(true)
.value_name("number")
.display_order(4)
.help("The port to listen on")
);
let matches = context.command.clone().get_matches(); let matches = context.command.clone().get_matches();