Fix many clippy lints

...and other small improvements
This commit is contained in:
johannesd3 2021-03-10 22:32:24 +01:00
parent 38761395d3
commit 5616004dbe
8 changed files with 43 additions and 49 deletions

View file

@ -13,9 +13,6 @@ use tokio::sync::{mpsc, oneshot};
#[cfg(feature = "with-dns-sd")] #[cfg(feature = "with-dns-sd")]
use dns_sd::DNSService; use dns_sd::DNSService;
#[cfg(not(feature = "with-dns-sd"))]
use libmdns;
use librespot_core::authentication::Credentials; use librespot_core::authentication::Credentials;
use librespot_core::config::ConnectConfig; use librespot_core::config::ConnectConfig;
use librespot_core::diffie_hellman::{DH_GENERATOR, DH_PRIME}; use librespot_core::diffie_hellman::{DH_GENERATOR, DH_PRIME};
@ -127,7 +124,7 @@ impl Discovery {
let mut h = HmacSha1::new_varkey(&checksum_key).expect("HMAC can take key of any size"); let mut h = HmacSha1::new_varkey(&checksum_key).expect("HMAC can take key of any size");
h.update(encrypted); h.update(encrypted);
if let Err(_) = h.verify(cksum) { if h.verify(cksum).is_err() {
warn!("Login error for user {:?}: MAC mismatch", username); warn!("Login error for user {:?}: MAC mismatch", username);
let result = json!({ let result = json!({
"status": 102, "status": 102,

View file

@ -426,8 +426,8 @@ impl SpircTask {
Ok(dur) => dur, Ok(dur) => dur,
Err(err) => err.duration(), Err(err) => err.duration(),
}; };
(dur.as_secs() as i64 + self.session.time_delta()) * 1000
+ (dur.subsec_nanos() / 1000_000) as i64 dur.as_millis() as i64 + 1000 * self.session.time_delta()
} }
fn ensure_mixer_started(&mut self) { fn ensure_mixer_started(&mut self) {
@ -512,7 +512,9 @@ impl SpircTask {
SpircCommand::Shutdown => { SpircCommand::Shutdown => {
CommandSender::new(self, MessageType::kMessageTypeGoodbye).send(); CommandSender::new(self, MessageType::kMessageTypeGoodbye).send();
self.shutdown = true; self.shutdown = true;
self.commands.as_mut().map(|rx| rx.close()); if let Some(rx) = self.commands.as_mut() {
rx.close()
}
} }
} }
} }
@ -620,7 +622,7 @@ impl SpircTask {
); );
if frame.get_ident() == self.ident if frame.get_ident() == self.ident
|| (frame.get_recipient().len() > 0 && !frame.get_recipient().contains(&self.ident)) || (!frame.get_recipient().is_empty() && !frame.get_recipient().contains(&self.ident))
{ {
return; return;
} }
@ -639,7 +641,7 @@ impl SpircTask {
self.update_tracks(&frame); self.update_tracks(&frame);
if self.state.get_track().len() > 0 { if !self.state.get_track().is_empty() {
let start_playing = let start_playing =
frame.get_state().get_status() == PlayStatus::kPlayStatusPlay; frame.get_state().get_status() == PlayStatus::kPlayStatusPlay;
self.load_track(start_playing, frame.get_state().get_position_ms()); self.load_track(start_playing, frame.get_state().get_position_ms());
@ -862,7 +864,7 @@ impl SpircTask {
fn preview_next_track(&mut self) -> Option<SpotifyId> { fn preview_next_track(&mut self) -> Option<SpotifyId> {
self.get_track_id_to_play_from_playlist(self.state.get_playing_track_index() + 1) self.get_track_id_to_play_from_playlist(self.state.get_playing_track_index() + 1)
.and_then(|(track_id, _)| Some(track_id)) .map(|(track_id, _)| track_id)
} }
fn handle_preload_next_track(&mut self) { fn handle_preload_next_track(&mut self) {
@ -981,7 +983,7 @@ impl SpircTask {
}; };
// Reinsert queued tracks after the new playing track. // Reinsert queued tracks after the new playing track.
let mut pos = (new_index + 1) as usize; let mut pos = (new_index + 1) as usize;
for track in queue_tracks.into_iter() { for track in queue_tracks {
self.state.mut_track().insert(pos, track); self.state.mut_track().insert(pos, track);
pos += 1; pos += 1;
} }
@ -1120,7 +1122,7 @@ impl SpircTask {
} }
self.state.set_playing_track_index(index); self.state.set_playing_track_index(index);
self.state.set_track(tracks.into_iter().cloned().collect()); self.state.set_track(tracks.iter().cloned().collect());
self.state.set_context_uri(context_uri); self.state.set_context_uri(context_uri);
// has_shuffle/repeat seem to always be true in these replace msgs, // has_shuffle/repeat seem to always be true in these replace msgs,
// but to replicate the behaviour of the Android client we have to // but to replicate the behaviour of the Android client we have to

View file

@ -192,11 +192,12 @@ impl Stream for ChannelData {
}; };
loop { loop {
let x = match channel.poll_next_unpin(cx) { let event = match channel.poll_next_unpin(cx) {
Poll::Ready(x) => x.transpose()?, Poll::Ready(x) => x.transpose()?,
Poll::Pending => return Poll::Pending, Poll::Pending => return Poll::Pending,
}; };
match x {
match event {
Some(ChannelEvent::Header(..)) => (), Some(ChannelEvent::Header(..)) => (),
Some(ChannelEvent::Data(data)) => return Poll::Ready(Some(Ok(data))), Some(ChannelEvent::Data(data)) => return Poll::Ready(Some(Ok(data))),
None => return Poll::Ready(None), None => return Poll::Ready(None),
@ -214,12 +215,12 @@ impl Stream for ChannelHeaders {
Poll::Pending => return Poll::Pending, Poll::Pending => return Poll::Pending,
}; };
let x = match channel.poll_next_unpin(cx) { let event = match channel.poll_next_unpin(cx) {
Poll::Ready(x) => x.transpose()?, Poll::Ready(x) => x.transpose()?,
Poll::Pending => return Poll::Pending, Poll::Pending => return Poll::Pending,
}; };
match x { match event {
Some(ChannelEvent::Header(id, data)) => Poll::Ready(Some(Ok((id, data)))), Some(ChannelEvent::Header(id, data)) => Poll::Ready(Some(Ok((id, data)))),
Some(ChannelEvent::Data(..)) | None => Poll::Ready(None), Some(ChannelEvent::Data(..)) | None => Poll::Ready(None),
} }

View file

@ -104,11 +104,11 @@ where
Ok(message) Ok(message)
} }
async fn read_into_accumulator<'a, T: AsyncRead + Unpin>( async fn read_into_accumulator<'a, 'b, T: AsyncRead + Unpin>(
connection: &mut T, connection: &'a mut T,
size: usize, size: usize,
acc: &'a mut Vec<u8>, acc: &'b mut Vec<u8>,
) -> io::Result<&'a mut [u8]> { ) -> io::Result<&'b mut [u8]> {
let offset = acc.len(); let offset = acc.len();
acc.resize(offset + size, 0); acc.resize(offset + size, 0);

View file

@ -42,11 +42,13 @@ impl Default for MixerConfig {
pub mod softmixer; pub mod softmixer;
use self::softmixer::SoftMixer; use self::softmixer::SoftMixer;
type MixerFn = fn(Option<MixerConfig>) -> Box<dyn Mixer>;
fn mk_sink<M: Mixer + 'static>(device: Option<MixerConfig>) -> Box<dyn Mixer> { fn mk_sink<M: Mixer + 'static>(device: Option<MixerConfig>) -> Box<dyn Mixer> {
Box::new(M::open(device)) Box::new(M::open(device))
} }
pub fn find<T: AsRef<str>>(name: Option<T>) -> Option<fn(Option<MixerConfig>) -> Box<dyn Mixer>> { pub fn find<T: AsRef<str>>(name: Option<T>) -> Option<MixerFn> {
match name.as_ref().map(AsRef::as_ref) { match name.as_ref().map(AsRef::as_ref) {
None | Some("softvol") => Some(mk_sink::<SoftMixer>), None | Some("softvol") => Some(mk_sink::<SoftMixer>),
#[cfg(feature = "alsa-backend")] #[cfg(feature = "alsa-backend")]

View file

@ -196,13 +196,12 @@ struct NormalisationData {
impl NormalisationData { impl NormalisationData {
fn parse_from_file<T: Read + Seek>(mut file: T) -> io::Result<NormalisationData> { fn parse_from_file<T: Read + Seek>(mut file: T) -> io::Result<NormalisationData> {
const SPOTIFY_NORMALIZATION_HEADER_START_OFFSET: u64 = 144; const SPOTIFY_NORMALIZATION_HEADER_START_OFFSET: u64 = 144;
file.seek(SeekFrom::Start(SPOTIFY_NORMALIZATION_HEADER_START_OFFSET)) file.seek(SeekFrom::Start(SPOTIFY_NORMALIZATION_HEADER_START_OFFSET))?;
.unwrap();
let track_gain_db = file.read_f32::<LittleEndian>().unwrap(); let track_gain_db = file.read_f32::<LittleEndian>()?;
let track_peak = file.read_f32::<LittleEndian>().unwrap(); let track_peak = file.read_f32::<LittleEndian>()?;
let album_gain_db = file.read_f32::<LittleEndian>().unwrap(); let album_gain_db = file.read_f32::<LittleEndian>()?;
let album_peak = file.read_f32::<LittleEndian>().unwrap(); let album_peak = file.read_f32::<LittleEndian>()?;
let r = NormalisationData { let r = NormalisationData {
track_gain_db: track_gain_db, track_gain_db: track_gain_db,
@ -889,8 +888,7 @@ impl Future for PlayerInternal {
if !passthrough { if !passthrough {
if let Some(ref packet) = packet { if let Some(ref packet) = packet {
*stream_position_pcm = *stream_position_pcm += (packet.samples().len() / 2) as u64;
*stream_position_pcm + (packet.samples().len() / 2) as u64;
let stream_position_millis = let stream_position_millis =
Self::position_pcm_to_ms(*stream_position_pcm); Self::position_pcm_to_ms(*stream_position_pcm);
@ -1111,7 +1109,9 @@ impl PlayerInternal {
editor.modify_stream(data) editor.modify_stream(data)
} }
if self.config.normalisation && normalisation_factor != 1.0 { if self.config.normalisation
&& f32::abs(normalisation_factor - 1.0) > f32::EPSILON
{
for x in data.iter_mut() { for x in data.iter_mut() {
*x = (*x as f32 * normalisation_factor) as i16; *x = (*x as f32 * normalisation_factor) as i16;
} }
@ -1598,12 +1598,10 @@ impl PlayerInternal {
let (result_tx, result_rx) = oneshot::channel(); let (result_tx, result_rx) = oneshot::channel();
std::thread::spawn(move || { std::thread::spawn(move || {
futures_executor::block_on(loader.load_track(spotify_id, position_ms)).and_then( let data = futures_executor::block_on(loader.load_track(spotify_id, position_ms));
move |data| { if let Some(data) = data {
let _ = result_tx.send(data); let _ = result_tx.send(data);
Some(()) }
},
);
}); });
result_rx.map_err(|_| ()) result_rx.map_err(|_| ())

View file

@ -236,13 +236,7 @@ fn setup(args: &[String]) -> Setup {
let matches = match opts.parse(&args[1..]) { let matches = match opts.parse(&args[1..]) {
Ok(m) => m, Ok(m) => m,
Err(f) => { Err(f) => {
writeln!( eprintln!("error: {}\n{}", f.to_string(), usage(&args[0], &opts));
stderr(),
"error: {}\n{}",
f.to_string(),
usage(&args[0], &opts)
)
.unwrap();
exit(1); exit(1);
} }
}; };
@ -360,7 +354,7 @@ fn setup(args: &[String]) -> Setup {
SessionConfig { SessionConfig {
user_agent: version::version_string(), user_agent: version::version_string(),
device_id: device_id, device_id: device_id,
proxy: matches.opt_str("proxy").or(std::env::var("http_proxy").ok()).map( proxy: matches.opt_str("proxy").or_else(|| std::env::var("http_proxy").ok()).map(
|s| { |s| {
match Url::parse(&s) { match Url::parse(&s) {
Ok(url) => { Ok(url) => {
@ -390,14 +384,14 @@ fn setup(args: &[String]) -> Setup {
.opt_str("b") .opt_str("b")
.as_ref() .as_ref()
.map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate")) .map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate"))
.unwrap_or(Bitrate::default()); .unwrap_or_default();
let gain_type = matches let gain_type = matches
.opt_str("normalisation-gain-type") .opt_str("normalisation-gain-type")
.as_ref() .as_ref()
.map(|gain_type| { .map(|gain_type| {
NormalisationType::from_str(gain_type).expect("Invalid normalisation type") NormalisationType::from_str(gain_type).expect("Invalid normalisation type")
}) })
.unwrap_or(NormalisationType::default()); .unwrap_or_default();
PlayerConfig { PlayerConfig {
bitrate: bitrate, bitrate: bitrate,
gapless: !matches.opt_present("disable-gapless"), gapless: !matches.opt_present("disable-gapless"),
@ -416,13 +410,13 @@ fn setup(args: &[String]) -> Setup {
.opt_str("device-type") .opt_str("device-type")
.as_ref() .as_ref()
.map(|device_type| DeviceType::from_str(device_type).expect("Invalid device type")) .map(|device_type| DeviceType::from_str(device_type).expect("Invalid device type"))
.unwrap_or(DeviceType::default()); .unwrap_or_default();
let volume_ctrl = matches let volume_ctrl = matches
.opt_str("volume-ctrl") .opt_str("volume-ctrl")
.as_ref() .as_ref()
.map(|volume_ctrl| VolumeCtrl::from_str(volume_ctrl).expect("Invalid volume ctrl type")) .map(|volume_ctrl| VolumeCtrl::from_str(volume_ctrl).expect("Invalid volume ctrl type"))
.unwrap_or(VolumeCtrl::default()); .unwrap_or_default();
ConnectConfig { ConnectConfig {
name: name, name: name,