Unverified 提交 94905469 authored 作者: dhilipsiva's avatar dhilipsiva 提交者: GitHub

refactor: make `hex_as_bytes` DRY (#1409)

上级 5c4b6ce1
[toolchain]
channel = "1.72.0"
channel = "1.79.0"
components = ["rustfmt", "clippy"]
......@@ -528,12 +528,15 @@ pub enum DtlsFingerprint {
},
}
fn hex_as_bytes(input: &str, output: &mut [u8]) {
fn hex_as_bytes<const N: usize>(input: &str) -> [u8; N] {
let mut output = [0_u8; N];
for (i, o) in input.split(':').zip(&mut output.iter_mut()) {
*o = u8::from_str_radix(i, 16).unwrap_or_else(|error| {
panic!("Failed to parse value {i} as series of hex bytes: {error}")
});
}
output
}
impl DtlsFingerprint {
......@@ -565,45 +568,35 @@ impl DtlsFingerprint {
pub(crate) fn from_fbs(fingerprint: &web_rtc_transport::Fingerprint) -> DtlsFingerprint {
match fingerprint.algorithm {
web_rtc_transport::FingerprintAlgorithm::Sha1 => {
let mut value_result = [0_u8; 20];
hex_as_bytes(fingerprint.value.as_str(), &mut value_result);
let value_result = hex_as_bytes::<20>(fingerprint.value.as_str());
DtlsFingerprint::Sha1 {
value: value_result,
}
}
web_rtc_transport::FingerprintAlgorithm::Sha224 => {
let mut value_result = [0_u8; 28];
hex_as_bytes(fingerprint.value.as_str(), &mut value_result);
let value_result = hex_as_bytes::<28>(fingerprint.value.as_str());
DtlsFingerprint::Sha224 {
value: value_result,
}
}
web_rtc_transport::FingerprintAlgorithm::Sha256 => {
let mut value_result = [0_u8; 32];
hex_as_bytes(fingerprint.value.as_str(), &mut value_result);
let value_result = hex_as_bytes::<32>(fingerprint.value.as_str());
DtlsFingerprint::Sha256 {
value: value_result,
}
}
web_rtc_transport::FingerprintAlgorithm::Sha384 => {
let mut value_result = [0_u8; 48];
hex_as_bytes(fingerprint.value.as_str(), &mut value_result);
let value_result = hex_as_bytes::<48>(fingerprint.value.as_str());
DtlsFingerprint::Sha384 {
value: value_result,
}
}
web_rtc_transport::FingerprintAlgorithm::Sha512 => {
let mut value_result = [0_u8; 64];
hex_as_bytes(fingerprint.value.as_str(), &mut value_result);
let value_result = hex_as_bytes::<64>(fingerprint.value.as_str());
DtlsFingerprint::Sha512 {
value: value_result,
......
......@@ -681,7 +681,7 @@ pub(crate) fn can_consume(
if caps
.codecs
.iter()
.any(|cap_codec| match_codecs(cap_codec.deref().into(), codec.into(), true).is_ok())
.any(|cap_codec| match_codecs(cap_codec.into(), codec.into(), true).is_ok())
{
matching_codecs.push(codec);
}
......@@ -689,7 +689,7 @@ pub(crate) fn can_consume(
// Ensure there is at least one media codec.
Ok(matching_codecs
.get(0)
.first()
.map(|codec| !codec.is_rtx())
.unwrap_or_default())
}
......@@ -841,7 +841,7 @@ pub(crate) fn get_consumer_rtp_parameters(
// (assume all encodings have the same value).
let mut scalability_mode = consumable_rtp_parameters
.encodings
.get(0)
.first()
.map(|encoding| encoding.scalability_mode.clone())
.unwrap_or_default();
......
......@@ -255,8 +255,8 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
]
);
assert_eq!(rtp_mapping.encodings.get(0).unwrap().ssrc, Some(11111111));
assert_eq!(rtp_mapping.encodings.get(0).unwrap().rid, None);
assert_eq!(rtp_mapping.encodings.first().unwrap().ssrc, Some(11111111));
assert_eq!(rtp_mapping.encodings.first().unwrap().rid, None);
assert_eq!(rtp_mapping.encodings.get(1).unwrap().ssrc, Some(21111111));
assert_eq!(rtp_mapping.encodings.get(1).unwrap().rid, None);
assert_eq!(rtp_mapping.encodings.get(2).unwrap().ssrc, None);
......@@ -303,13 +303,13 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
);
assert_eq!(
consumable_rtp_parameters.encodings.get(0).unwrap().ssrc,
Some(rtp_mapping.encodings.get(0).unwrap().mapped_ssrc),
consumable_rtp_parameters.encodings.first().unwrap().ssrc,
Some(rtp_mapping.encodings.first().unwrap().mapped_ssrc),
);
assert_eq!(
consumable_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.max_bitrate,
Some(111111),
......@@ -317,7 +317,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
assert_eq!(
consumable_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.scalability_mode,
ScalabilityMode::L1T3,
......@@ -489,20 +489,20 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
assert_eq!(consumer_rtp_parameters.encodings.len(), 1);
assert!(consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.ssrc
.is_some());
assert!(consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.rtx
.is_some());
assert_eq!(
consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.scalability_mode,
ScalabilityMode::L3T3,
......@@ -510,7 +510,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
assert_eq!(
consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.max_bitrate,
Some(333333),
......@@ -566,26 +566,26 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
assert_eq!(pipe_consumer_rtp_parameters.encodings.len(), 3);
assert!(pipe_consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.ssrc
.is_some());
assert!(pipe_consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.rtx
.is_none());
assert!(pipe_consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.max_bitrate
.is_some());
assert_eq!(
pipe_consumer_rtp_parameters
.encodings
.get(0)
.first()
.unwrap()
.scalability_mode,
ScalabilityMode::L1T3,
......
......@@ -1303,8 +1303,12 @@ impl Router {
// We've created `DataConsumer` with SCTP above, so this should never panic
pipe_data_consumer.sctp_stream_parameters().unwrap(),
);
producer_options.label = pipe_data_consumer.label().clone();
producer_options.protocol = pipe_data_consumer.protocol().clone();
producer_options
.label
.clone_from(pipe_data_consumer.label());
producer_options
.protocol
.clone_from(pipe_data_consumer.protocol());
producer_options.app_data = data_producer.app_data().clone();
producer_options
......
......@@ -759,7 +759,7 @@ impl Producer {
match Notification::from_fbs(notification) {
Ok(notification) => match notification {
Notification::Score(scores) => {
*score.lock() = scores.clone();
score.lock().clone_from(&scores);
handlers.score.call(|callback| {
callback(&scores);
});
......
......@@ -919,7 +919,6 @@ impl RtpParameters {
})
}
#[allow(dead_code)]
pub(crate) fn into_fbs(self) -> rtp_parameters::RtpParameters {
rtp_parameters::RtpParameters {
mid: self.mid,
......
......@@ -184,9 +184,9 @@ impl FromStr for ScalabilityMode {
}
}
impl ToString for ScalabilityMode {
fn to_string(&self) -> String {
self.as_str().to_string()
impl std::fmt::Display for ScalabilityMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
......
......@@ -35,9 +35,7 @@ impl<F: Sized + Send + Sync + 'static> EventHandlers<F> {
let index;
{
let mut event_handlers = self.handlers.lock();
let list = event_handlers
.entry(target_id.clone())
.or_insert_with(EventHandlersList::default);
let list = event_handlers.entry(target_id.clone()).or_default();
index = list.index;
list.index += 1;
list.callbacks.insert(index, callback);
......
......@@ -8,9 +8,18 @@ unsafe extern "C" fn free_vec(message: *mut u8, message_len: u32, message_capaci
Vec::from_raw_parts(message, message_len as usize, message_capacity);
}
pub(super) struct ChannelReadCallback(
Box<dyn (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static>,
);
pub(super) struct ChannelReadCallback {
// Silence clippy warnings
_callback: Box<dyn (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static>,
}
impl ChannelReadCallback {
pub(super) fn new(
_callback: Box<dyn (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static>,
) -> Self {
Self { _callback }
}
}
pub(crate) struct PreparedChannelRead {
channel_read_fn: ChannelReadFn,
......@@ -71,6 +80,6 @@ where
PreparedChannelRead {
channel_read_fn: wrapper::<F>,
channel_read_ctx: ChannelReadCtx(read_callback.as_ref() as *const F as *const c_void),
write_callback: ChannelReadCallback(read_callback),
write_callback: ChannelReadCallback::new(read_callback),
}
}
......@@ -2,8 +2,19 @@ pub(super) use mediasoup_sys::{ChannelWriteCtx, ChannelWriteFn};
use std::os::raw::c_void;
use std::slice;
#[allow(clippy::type_complexity)]
pub(super) struct ChannelReadCallback(Box<dyn FnMut(&[u8]) + Send + 'static>);
/// TypeAlias to silience clippy::type_complexity warnings
type CallbackType = Box<dyn FnMut(&[u8]) + Send + 'static>;
pub(super) struct ChannelReadCallback {
// Silence clippy warnings
_callback: CallbackType,
}
impl ChannelReadCallback {
pub(super) fn new(_callback: CallbackType) -> Self {
Self { _callback }
}
}
pub(crate) struct PreparedChannelWrite {
channel_write_fn: ChannelWriteFn,
......@@ -54,6 +65,6 @@ where
PreparedChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: ChannelWriteCtx(read_callback.as_ref() as *const F as *const c_void),
read_callback: ChannelReadCallback(read_callback),
read_callback: ChannelReadCallback::new(read_callback),
}
}
......@@ -291,7 +291,16 @@ fn consumer_device_capabilities() -> RtpCapabilities {
}
// Keeps executor threads running until dropped
struct ExecutorGuard(Vec<async_oneshot::Sender<()>>);
struct ExecutorGuard {
// Silence clippy warnings
_senders: Vec<async_oneshot::Sender<()>>,
}
impl ExecutorGuard {
fn new(_senders: Vec<async_oneshot::Sender<()>>) -> Self {
Self { _senders }
}
}
fn create_executor() -> (ExecutorGuard, Arc<Executor<'static>>) {
let executor = Arc::new(Executor::new());
......@@ -318,7 +327,7 @@ fn create_executor() -> (ExecutorGuard, Arc<Executor<'static>>) {
})
.collect();
(ExecutorGuard(senders), executor)
(ExecutorGuard::new(senders), executor)
}
async fn init() -> (
......@@ -977,7 +986,7 @@ fn dump_succeeds() {
ssrc: audio_consumer
.rtp_parameters()
.encodings
.get(0)
.first()
.unwrap()
.ssrc,
rid: None,
......@@ -1086,13 +1095,13 @@ fn dump_succeeds() {
ssrc: video_consumer
.rtp_parameters()
.encodings
.get(0)
.first()
.unwrap()
.ssrc,
rtx: video_consumer
.rtp_parameters()
.encodings
.get(0)
.first()
.unwrap()
.rtx,
dtx: None,
......@@ -1165,7 +1174,7 @@ fn get_stats_succeeds() {
audio_consumer
.rtp_parameters()
.encodings
.get(0)
.first()
.unwrap()
.ssrc
.unwrap()
......@@ -1214,7 +1223,7 @@ fn get_stats_succeeds() {
video_consumer
.rtp_parameters()
.encodings
.get(0)
.first()
.unwrap()
.ssrc
.unwrap()
......
......@@ -10,6 +10,11 @@ use std::net::{IpAddr, Ipv4Addr};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Debug, PartialEq)]
struct CustomAppData {
foo: u32,
}
async fn init() -> (Worker, Worker) {
{
let mut builder = env_logger::builder();
......@@ -52,11 +57,6 @@ fn create_webrtc_server_succeeds() {
})
.detach();
#[derive(Debug, PartialEq)]
struct CustomAppData {
foo: u32,
}
let webrtc_server = worker1
.create_webrtc_server({
let listen_infos = WebRtcServerListenInfos::new(ListenInfo {
......@@ -150,11 +150,6 @@ fn create_webrtc_server_without_specifying_port_succeeds() {
})
.detach();
#[derive(Debug, PartialEq)]
struct CustomAppData {
foo: u32,
}
let webrtc_server = worker1
.create_webrtc_server({
let listen_infos = WebRtcServerListenInfos::new(ListenInfo {
......@@ -233,11 +228,6 @@ fn unavailable_infos_fails() {
})
.detach();
#[derive(Debug, PartialEq)]
struct CustomAppData {
foo: u32,
}
// Using an unavailable listen IP.
{
let create_result = worker1
......
......@@ -280,7 +280,7 @@ fn create_with_fixed_port_succeeds() {
.await
.expect("Failed to create WebRTC transport");
assert_eq!(transport.ice_candidates().get(0).unwrap().port, port);
assert_eq!(transport.ice_candidates().first().unwrap().port, port);
});
}
......@@ -306,7 +306,7 @@ fn create_with_port_range_succeeds() {
.await
.expect("Failed to create WebRTC transport");
let port1 = transport1.ice_candidates().get(0).unwrap().port;
let port1 = transport1.ice_candidates().first().unwrap().port;
assert!(port1 >= *port_range.start() && port1 <= *port_range.end());
let transport2 = router
......@@ -325,7 +325,7 @@ fn create_with_port_range_succeeds() {
.await
.expect("Failed to create WebRTC transport");
let port2 = transport2.ice_candidates().get(0).unwrap().port;
let port2 = transport2.ice_candidates().first().unwrap().port;
assert!(port2 >= *port_range.start() && port2 <= *port_range.end());
assert!(matches!(
......
......@@ -39,7 +39,6 @@ fn main() {
.expect("Failed to generate Rust code from flatbuffers"),
)
.expect("Failed to write generated Rust flatbuffers into fbs.rs");
if env::var("DOCS_RS").is_ok() {
// Skip everything when building docs on docs.rs
return;
......
use std::os::raw::{c_char, c_int, c_void};
include!(concat!(env!("OUT_DIR"), "/fbs.rs"));
pub use planus_codegen::*;
mod planus_codegen {
#![allow(clippy::all)]
include!(concat!(env!("OUT_DIR"), "/fbs.rs"));
}
#[repr(transparent)]
#[derive(Copy, Clone)]
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论