Skip to content

Commit

Permalink
Fix clippy pedantic warnings (#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev authored and FelixMcFelix committed Nov 20, 2023
1 parent 63d48ee commit 3d307aa
Show file tree
Hide file tree
Showing 22 changed files with 96 additions and 64 deletions.
7 changes: 5 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ impl Config {
self
}

#[must_use]
pub fn test_cfg(raw_output: bool) -> (DriverTestHandle, Config) {
let (tick_tx, tick_rx) = flume::unbounded();

Expand All @@ -418,8 +419,10 @@ impl Config {
(OutputMode::Rtp(rtp_tx), OutputReceiver::Rtp(rtp_rx))
};

let mut sc_config = SchedulerConfig::default();
sc_config.strategy = crate::driver::SchedulerMode::MaxPerThread(1.try_into().unwrap());
let sc_config = SchedulerConfig {
strategy: crate::driver::SchedulerMode::MaxPerThread(1.try_into().unwrap()),
move_expensive_tasks: true,
};

let config = Config::default()
.tick_style(TickStyle::UntimedWithExecLimit(tick_rx))
Expand Down
1 change: 1 addition & 0 deletions src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ pub const RTP_VERSION: u8 = 2;
pub const RTP_PROFILE_TYPE: RtpType = RtpType::Dynamic(120);

#[cfg(test)]
#[allow(clippy::doc_markdown)]
pub mod test_data {
/// URL for a source which YTDL must extract.
///
Expand Down
5 changes: 2 additions & 3 deletions src/driver/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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());
Expand Down
21 changes: 13 additions & 8 deletions src/driver/scheduler/idle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand Down Expand Up @@ -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;
},
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/driver/scheduler/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
12 changes: 9 additions & 3 deletions src/driver/scheduler/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -152,7 +158,7 @@ impl ParkedMixer {
self.mixer
.do_rebuilds(events_failure, conn_failure)
.map_err(|_| ())
.map(|_| should_exit)
.map(|()| should_exit)
},
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/driver/tasks/mixer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
},
Expand Down
2 changes: 1 addition & 1 deletion src/driver/tasks/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
30 changes: 22 additions & 8 deletions src/driver/test_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -43,6 +46,7 @@ impl OutputMessage {
}
}

#[must_use]
pub fn is_explicit_silence(&self) -> bool {
*self == Self::Silent
}
Expand Down Expand Up @@ -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)
Expand All @@ -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(),
Expand All @@ -130,13 +136,19 @@ impl DriverTestHandle {
}
}

#[must_use]
pub fn len(&self) -> usize {
match &self.rx {
OutputReceiver::Raw(rx) => rx.len(),
OutputReceiver::Rtp(rx) => rx.len(),
}
}

#[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());
Expand All @@ -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 {
Expand Down Expand Up @@ -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();
}

Expand All @@ -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>,
}
Expand Down Expand Up @@ -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.");
Expand All @@ -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) => {},
}

Expand Down
22 changes: 13 additions & 9 deletions src/driver/test_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,15 @@ 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,
};

#[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,
};
Expand All @@ -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);
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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();

Expand All @@ -181,15 +181,18 @@ 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());

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(),
Expand All @@ -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![];
Expand Down
Loading

0 comments on commit 3d307aa

Please sign in to comment.