Fix clippy pedantic warnings (#204)

This commit is contained in:
Gnome!
2023-11-09 11:42:41 +00:00
committed by Kyle Simpson
parent 63d48ee597
commit 3d307aaa8b
22 changed files with 96 additions and 64 deletions

View File

@@ -153,7 +153,7 @@ impl CryptoMode {
cipher
.decrypt_in_place_detached(nonce_slice, b"", data_bytes, tag)
.map(|_| (body_start, body_tail))
.map(|()| (body_start, body_tail))
}
/// Encrypts a Discord RT(C)P packet using the given key.
@@ -290,8 +290,7 @@ mod test {
let mut pkt = MutableRtpPacket::new(&mut buf[..]).unwrap();
let mut crypto_state = CryptoState::from(mode);
let payload = pkt.payload_mut();
(&mut payload[TAG_SIZE..TAG_SIZE + TRUE_PAYLOAD.len()])
.copy_from_slice(&TRUE_PAYLOAD[..]);
payload[TAG_SIZE..TAG_SIZE + TRUE_PAYLOAD.len()].copy_from_slice(&TRUE_PAYLOAD[..]);
let final_payload_size =
crypto_state.write_packet_nonce(&mut pkt, TAG_SIZE + TRUE_PAYLOAD.len());

View File

@@ -94,7 +94,7 @@ impl Idle {
self.schedule_mixer(task, id, None);
},
Ok(false) => {},
Ok(true) | Err(_) => self.to_cull.push(id),
Ok(true) | Err(()) => self.to_cull.push(id),
}
} else {
info!("Received post-cull message for {id:?}, discarding.");
@@ -161,7 +161,7 @@ impl Idle {
let task = loop_task.take().unwrap();
let (worker, idx) = self.fetch_worker(&task, avoid);
match worker.schedule_mixer(id, task) {
Ok(_) => {
Ok(()) => {
self.stats.move_mixer_to_live();
break;
},
@@ -239,8 +239,10 @@ mod test {
#[tokio::test]
async fn active_mixers_spawn_threads() {
let mut config = Config::default();
config.move_expensive_tasks = false;
let config = Config {
strategy: Mode::default(),
move_expensive_tasks: false,
};
let sched = Scheduler::new(config);
let (pkt_tx, _pkt_rx) = flume::unbounded();
@@ -270,11 +272,14 @@ mod test {
#[tokio::test]
async fn excess_threads_are_cleaned_up() {
let mut config = Config::default();
config.strategy = Mode::MaxPerThread(1.try_into().unwrap());
let (mut core, tx) = Idle::new(config.clone());
const TEST_TIMER: Duration = Duration::from_millis(500);
let config = Config {
strategy: Mode::MaxPerThread(1.try_into().unwrap()),
move_expensive_tasks: true,
};
let (mut core, tx) = Idle::new(config.clone());
core.cull_timer = TEST_TIMER;
let mut next_id = TaskId::new();

View File

@@ -273,7 +273,7 @@ impl Live {
for (i, mixer) in self.tasks.iter_mut().enumerate() {
let res = mixer
.audio_commands_events()
.and_then(|_| mixer.check_and_send_keepalive(self.start_of_work));
.and_then(|()| mixer.check_and_send_keepalive(self.start_of_work));
rebuild_if_err(mixer, res, &mut self.to_cull, i);
}

View File

@@ -39,7 +39,7 @@ impl<T> IsEnabled for ResId<T> {}
#[allow(missing_docs)]
impl<T: Copy> ResId<T> {
pub fn new() -> Self {
ResId(0, PhantomData)
Self::default()
}
pub fn incr(&mut self) -> Self {
@@ -49,11 +49,17 @@ impl<T: Copy> ResId<T> {
}
#[cfg(any(test, feature = "internals"))]
pub fn get(&self) -> u64 {
pub fn get(self) -> u64 {
self.0
}
}
impl<T: Copy> Default for ResId<T> {
fn default() -> Self {
Self(0, PhantomData)
}
}
/// An idle mixer instance, externally controlled by a `Driver`.
///
/// Since we do not allocate packet buffers for idle threads, this
@@ -152,7 +158,7 @@ impl ParkedMixer {
self.mixer
.do_rebuilds(events_failure, conn_failure)
.map_err(|_| ())
.map(|_| should_exit)
.map(|()| should_exit)
},
}
}

View File

@@ -576,12 +576,12 @@ impl Mixer {
let msg = match mix_len {
MixType::Passthrough(len) if len == SILENT_FRAME.len() => OutputMessage::Silent,
MixType::Passthrough(len) => {
let rtp = RtpPacket::new(&packet).expect(
let rtp = RtpPacket::new(packet).expect(
"FATAL: Too few bytes in self.packet for RTP header.\
(Blame: VOICE_PACKET_MAX?)",
);
let payload = rtp.payload();
let opus_frame = (&payload[TAG_SIZE..][..len]).to_vec();
let opus_frame = (payload[TAG_SIZE..][..len]).to_vec();
OutputMessage::Passthrough(opus_frame)
},

View File

@@ -82,7 +82,7 @@ impl AuxNetwork {
let hb = sleep_until(next_heartbeat);
select! {
_ = hb => {
() = hb => {
ws_error = match self.send_heartbeat().await {
Err(e) => {
should_reconnect = ws_error_is_not_final(&e);

View File

@@ -27,14 +27,17 @@ pub enum OutputMessage {
#[allow(dead_code)]
impl OutputMessage {
#[must_use]
pub fn is_passthrough(&self) -> bool {
matches!(self, Self::Passthrough(_))
}
#[must_use]
pub fn is_mixed(&self) -> bool {
matches!(self, Self::Mixed(_))
}
#[must_use]
pub fn is_mixed_with_nonzero_signal(&self) -> bool {
if let Self::Mixed(data) = self {
data.iter().any(|v| *v != 0.0f32)
@@ -43,6 +46,7 @@ impl OutputMessage {
}
}
#[must_use]
pub fn is_explicit_silence(&self) -> bool {
*self == Self::Silent
}
@@ -94,6 +98,7 @@ pub enum OutputPacket {
}
impl OutputPacket {
#[must_use]
pub fn raw(&self) -> Option<&OutputMessage> {
if let Self::Raw(o) = self {
Some(o)
@@ -116,6 +121,7 @@ pub struct DriverTestHandle {
}
impl DriverTestHandle {
#[must_use]
pub fn recv(&self) -> OutputPacket {
match &self.rx {
OutputReceiver::Raw(rx) => rx.recv().unwrap().into(),
@@ -130,6 +136,7 @@ impl DriverTestHandle {
}
}
#[must_use]
pub fn len(&self) -> usize {
match &self.rx {
OutputReceiver::Raw(rx) => rx.len(),
@@ -137,6 +144,11 @@ impl DriverTestHandle {
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn wait(&self, n_ticks: u64) {
for _i in 0..n_ticks {
drop(self.recv());
@@ -149,7 +161,7 @@ impl DriverTestHandle {
}
}
pub async fn spawn_ticker(&self) {
pub fn spawn_ticker(&self) {
let remote = self.clone();
tokio::spawn(async move {
loop {
@@ -179,9 +191,11 @@ impl DriverTestHandle {
}
pub fn tick(&self, n_ticks: u64) {
if n_ticks == 0 {
panic!("Number of ticks to advance driver/mixer must be >= 1.");
}
assert!(
n_ticks != 0,
"Number of ticks to advance driver/mixer must be >= 1."
);
self.tx.send(n_ticks).unwrap();
}
@@ -190,9 +204,6 @@ impl DriverTestHandle {
handle: &TrackHandle,
tick_wait: Option<Duration>,
) -> TrackState {
let (tx, rx) = flume::bounded(1);
let (err_tx, err_rx) = flume::bounded(1);
struct SongPlayable {
tx: Sender<TrackState>,
}
@@ -223,6 +234,9 @@ impl DriverTestHandle {
}
}
let (tx, rx) = flume::bounded(1);
let (err_tx, err_rx) = flume::bounded(1);
handle
.add_event(Event::Track(TrackEvent::Playable), SongPlayable { tx })
.expect("Adding track evt should not fail before any ticks.");
@@ -237,7 +251,7 @@ impl DriverTestHandle {
self.wait_async(1).await;
match err_rx.try_recv() {
Ok(e) => panic!("Error reported on track: {:?}", e),
Ok(e) => panic!("Error reported on track: {e:?}"),
Err(flume::TryRecvError::Empty | flume::TryRecvError::Disconnected) => {},
}

View File

@@ -66,7 +66,7 @@ impl Mixer {
#[cfg(feature = "receive")]
let fake_conn = MixerConnection {
cipher: Cipher::new_from_slice(&vec![0u8; KEY_SIZE]).unwrap(),
cipher: Cipher::new_from_slice(&[0u8; KEY_SIZE]).unwrap(),
crypto_state: CryptoState::Normal,
udp_rx: udp_receiver_tx,
udp_tx,
@@ -74,7 +74,7 @@ impl Mixer {
#[cfg(not(feature = "receive"))]
let fake_conn = MixerConnection {
cipher: Cipher::new_from_slice(&vec![0u8; KEY_SIZE]).unwrap(),
cipher: Cipher::new_from_slice(&[0u8; KEY_SIZE]).unwrap(),
crypto_state: CryptoState::Normal,
udp_tx,
};
@@ -97,7 +97,7 @@ impl Mixer {
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
_ => panic!("Failed to create a guaranteed source."),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
_ = out.0.add_track(ctx);
@@ -114,7 +114,7 @@ impl Mixer {
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
_ => panic!("Failed to create a guaranteed source."),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let mut track = Track::from(Input::Live(promoted.unwrap(), None));
track.loops = LoopState::Infinite;
@@ -133,7 +133,7 @@ impl Mixer {
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
_ => panic!("Failed to create a guaranteed source."),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
_ = out.0.add_track(ctx);
@@ -142,7 +142,7 @@ impl Mixer {
out
}
pub fn test_with_opus(handle: Handle) -> DummyMixer {
pub fn test_with_opus(handle: &Handle) -> DummyMixer {
// should add a single opus-based track.
// make this fully loaded to prevent any perf cost there.
let mut out = Self::mock(handle.clone(), false);
@@ -161,7 +161,7 @@ impl Mixer {
let promoted = match src.into() {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
_ => panic!("Failed to create a guaranteed source."),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
@@ -181,6 +181,7 @@ pub struct MockScheduler {
}
impl MockScheduler {
#[must_use]
pub fn new(mode: Option<Mode>) -> Self {
let stats = Arc::new(StatBlock::default());
let local = Arc::new(LiveStatBlock::default());
@@ -188,8 +189,10 @@ impl MockScheduler {
let (task_tx, task_rx) = flume::unbounded();
let (sched_tx, sched_rx) = flume::unbounded();
let mut cfg = crate::driver::SchedulerConfig::default();
cfg.strategy = mode.unwrap_or_default();
let cfg = crate::driver::SchedulerConfig {
strategy: mode.unwrap_or_default(),
move_expensive_tasks: true,
};
let core = Live::new(
WorkerId::new(),
@@ -214,6 +217,7 @@ impl MockScheduler {
self.core.add_task_direct(m, id);
}
#[must_use]
pub fn from_mixers(mode: Option<Mode>, mixers: Vec<DummyMixer>) -> (Self, Vec<Listeners>) {
let mut out = Self::new(mode);
let mut listeners = vec![];