Skip to content

Commit

Permalink
Apply Pedantic Clippy Lints
Browse files Browse the repository at this point in the history
  • Loading branch information
barafael committed Oct 15, 2023
1 parent 66e62e9 commit 31d4516
Show file tree
Hide file tree
Showing 12 changed files with 123 additions and 143 deletions.
8 changes: 5 additions & 3 deletions embassy-usb/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ fn main() {

// envvars take priority.
if !cfg.seen_env {
if cfg.seen_feature {
panic!("multiple values set for feature {}: {} and {}", name, cfg.value, value);
}
assert!(
!cfg.seen_feature,
"multiple values set for feature {}: {} and {}",
name, cfg.value, value
);

cfg.value = value;
cfg.seen_feature = true;
Expand Down
42 changes: 20 additions & 22 deletions embassy-usb/src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use heapless::Vec;

use crate::config::*;
use crate::config::MAX_HANDLER_COUNT;
use crate::descriptor::{BosWriter, DescriptorWriter};
use crate::driver::{Driver, Endpoint, EndpointType};
#[cfg(feature = "msos-descriptor")]
use crate::msos::{DeviceLevelDescriptor, FunctionLevelDescriptor, MsOsDescriptorWriter};
use crate::types::*;
use crate::types::{InterfaceNumber, StringIndex};
use crate::{Handler, Interface, UsbDevice, MAX_INTERFACE_COUNT, STRING_INDEX_CUSTOM_START};

#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
/// Configuration used when creating [UsbDevice].
/// Configuration used when creating [`UsbDevice`].
pub struct Config<'a> {
pub(crate) vendor_id: u16,
pub(crate) product_id: u16,
Expand Down Expand Up @@ -159,9 +159,10 @@ impl<'d, D: Driver<'d>> Builder<'d, D> {
panic!("if composite_with_iads is set, you must set device_class = 0xEF, device_sub_class = 0x02, device_protocol = 0x01");
}

if config.max_power > 500 {
panic!("The maximum allowed value for `max_power` is 500mA");
}
assert!(
config.max_power <= 500,
"The maximum allowed value for `max_power` is 500mA"
);

match config.max_packet_size_0 {
8 | 16 | 32 | 64 => {}
Expand Down Expand Up @@ -260,12 +261,11 @@ impl<'d, D: Driver<'d>> Builder<'d, D> {
/// The Handler is called on some USB bus events, and to handle all control requests not already
/// handled by the USB stack.
pub fn handler(&mut self, handler: &'d mut dyn Handler) {
if self.handlers.push(handler).is_err() {
panic!(
"embassy-usb: handler list full. Increase the `max_handler_count` compile-time setting. Current value: {}",
MAX_HANDLER_COUNT
)
}
assert!(
self.handlers.push(handler).is_ok(),
"embassy-usb: handler list full. Increase the `max_handler_count` compile-time setting. Current value: {}",
MAX_HANDLER_COUNT
);
}

/// Allocates a new string index.
Expand Down Expand Up @@ -332,12 +332,10 @@ impl<'a, 'd, D: Driver<'d>> FunctionBuilder<'a, 'd, D> {
num_alt_settings: 0,
};

if self.builder.interfaces.push(iface).is_err() {
panic!(
"embassy-usb: interface list full. Increase the `max_interface_count` compile-time setting. Current value: {}",
MAX_INTERFACE_COUNT
)
}
assert!(self.builder.interfaces.push(iface).is_ok(),
"embassy-usb: interface list full. Increase the `max_interface_count` compile-time setting. Current value: {}",
MAX_INTERFACE_COUNT
);

InterfaceBuilder {
builder: self.builder,
Expand Down Expand Up @@ -371,7 +369,7 @@ pub struct InterfaceBuilder<'a, 'd, D: Driver<'d>> {

impl<'a, 'd, D: Driver<'d>> InterfaceBuilder<'a, 'd, D> {
/// Get the interface number.
pub fn interface_number(&self) -> InterfaceNumber {
pub const fn interface_number(&self) -> InterfaceNumber {
self.interface_number
}

Expand Down Expand Up @@ -422,12 +420,12 @@ pub struct InterfaceAltBuilder<'a, 'd, D: Driver<'d>> {

impl<'a, 'd, D: Driver<'d>> InterfaceAltBuilder<'a, 'd, D> {
/// Get the interface number.
pub fn interface_number(&self) -> InterfaceNumber {
pub const fn interface_number(&self) -> InterfaceNumber {
self.interface_number
}

/// Get the alternate setting number.
pub fn alt_setting_number(&self) -> u8 {
pub const fn alt_setting_number(&self) -> u8 {
self.alt_setting_number
}

Expand All @@ -436,7 +434,7 @@ impl<'a, 'd, D: Driver<'d>> InterfaceAltBuilder<'a, 'd, D> {
/// Descriptors are written in the order builder functions are called. Note that some
/// classes care about the order.
pub fn descriptor(&mut self, descriptor_type: u8, descriptor: &[u8]) {
self.builder.config_descriptor.write(descriptor_type, descriptor)
self.builder.config_descriptor.write(descriptor_type, descriptor);
}

fn endpoint_in(&mut self, ep_type: EndpointType, max_packet_size: u16, interval_ms: u8) -> D::EndpointIn {
Expand Down
45 changes: 22 additions & 23 deletions embassy-usb/src/class/cdc_acm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use embassy_sync::waitqueue::WakerRegistration;

use crate::control::{self, InResponse, OutResponse, Recipient, Request, RequestType};
use crate::driver::{Driver, Endpoint, EndpointError, EndpointIn, EndpointOut};
use crate::types::*;
use crate::types::InterfaceNumber;
use crate::{Builder, Handler};

/// This should be used as `device_class` when building the `UsbDevice`.
Expand Down Expand Up @@ -50,7 +50,7 @@ impl<'a> State<'a> {
pub fn new() -> Self {
Self {
control: MaybeUninit::uninit(),
shared: Default::default(),
shared: ControlShared::default(),
}
}
}
Expand All @@ -61,9 +61,9 @@ impl<'a> State<'a> {
/// writing USB packets with no intermediate buffers, but it will not act like a stream-like serial
/// port. The following constraints must be followed if you use this class directly:
///
/// - `read_packet` must be called with a buffer large enough to hold max_packet_size bytes.
/// - `write_packet` must not be called with a buffer larger than max_packet_size bytes.
/// - If you write a packet that is exactly max_packet_size bytes long, it won't be processed by the
/// - `read_packet` must be called with a buffer large enough to hold `max_packet_size` bytes.
/// - `write_packet` must not be called with a buffer larger than `max_packet_size` bytes.
/// - If you write a packet that is exactly `max_packet_size` bytes long, it won't be processed by the
/// host operating system until a subsequent shorter packet is sent. A zero-length packet (ZLP)
/// can be sent if there is no other data to send. This is because USB bulk transactions must be
/// terminated with a short packet, even if the bulk endpoint is used for stream-like data.
Expand Down Expand Up @@ -109,17 +109,16 @@ impl Default for ControlShared {

impl ControlShared {
async fn changed(&self) {
poll_fn(|cx| match self.changed.load(Ordering::Relaxed) {
true => {
poll_fn(|cx| {
if self.changed.load(Ordering::Relaxed) {
self.changed.store(false, Ordering::Relaxed);
Poll::Ready(())
}
false => {
} else {
self.waker.borrow_mut().register(cx.waker());
Poll::Pending
}
})
.await
.await;
}
}

Expand Down Expand Up @@ -198,7 +197,7 @@ impl<'d> Handler for Control<'d> {
// REQ_GET_ENCAPSULATED_COMMAND is not really supported - it will be rejected below.
REQ_GET_LINE_CODING if req.length == 7 => {
debug!("Sending line coding");
let coding = self.shared().line_coding.lock(|x| x.get());
let coding = self.shared().line_coding.lock(Cell::get);
assert!(buf.len() >= 7);
buf[0..4].copy_from_slice(&coding.data_rate.to_le_bytes());
buf[4] = coding.stop_bits as u8;
Expand All @@ -212,8 +211,8 @@ impl<'d> Handler for Control<'d> {
}

impl<'d, D: Driver<'d>> CdcAcmClass<'d, D> {
/// Creates a new CdcAcmClass with the provided UsbBus and max_packet_size in bytes. For
/// full-speed devices, max_packet_size has to be one of 8, 16, 32 or 64.
/// Creates a new CdcAcmClass with the provided UsbBus and `max_packet_size` in bytes. For
/// full-speed devices, `max_packet_size` has to be one of 8, 16, 32 or 64.
pub fn new(builder: &mut Builder<'d, D>, state: &'d mut State<'d>, max_packet_size: u16) -> Self {
assert!(builder.control_buf_len() >= 7);

Expand Down Expand Up @@ -289,7 +288,7 @@ impl<'d, D: Driver<'d>> CdcAcmClass<'d, D> {
/// Gets the current line coding. The line coding contains information that's mainly relevant
/// for USB to UART serial port emulators, and can be ignored if not relevant.
pub fn line_coding(&self) -> LineCoding {
self.control.line_coding.lock(|x| x.get())
self.control.line_coding.lock(Cell::get)
}

/// Gets the DTR (data terminal ready) state
Expand All @@ -314,7 +313,7 @@ impl<'d, D: Driver<'d>> CdcAcmClass<'d, D> {

/// Waits for the USB host to enable this interface
pub async fn wait_connection(&mut self) {
self.read_ep.wait_enabled().await
self.read_ep.wait_enabled().await;
}

/// Split the class into a sender and receiver.
Expand Down Expand Up @@ -362,7 +361,7 @@ pub struct ControlChanged<'d> {
impl<'d> ControlChanged<'d> {
/// Return a future for when the control settings change
pub async fn control_changed(&self) {
self.control.changed().await
self.control.changed().await;
}
}

Expand All @@ -384,7 +383,7 @@ impl<'d, D: Driver<'d>> Sender<'d, D> {
/// Gets the current line coding. The line coding contains information that's mainly relevant
/// for USB to UART serial port emulators, and can be ignored if not relevant.
pub fn line_coding(&self) -> LineCoding {
self.control.line_coding.lock(|x| x.get())
self.control.line_coding.lock(Cell::get)
}

/// Gets the DTR (data terminal ready) state
Expand All @@ -404,7 +403,7 @@ impl<'d, D: Driver<'d>> Sender<'d, D> {

/// Waits for the USB host to enable this interface
pub async fn wait_connection(&mut self) {
self.write_ep.wait_enabled().await
self.write_ep.wait_enabled().await;
}
}

Expand All @@ -426,7 +425,7 @@ impl<'d, D: Driver<'d>> Receiver<'d, D> {
/// Gets the current line coding. The line coding contains information that's mainly relevant
/// for USB to UART serial port emulators, and can be ignored if not relevant.
pub fn line_coding(&self) -> LineCoding {
self.control.line_coding.lock(|x| x.get())
self.control.line_coding.lock(Cell::get)
}

/// Gets the DTR (data terminal ready) state
Expand All @@ -446,7 +445,7 @@ impl<'d, D: Driver<'d>> Receiver<'d, D> {

/// Waits for the USB host to enable this interface
pub async fn wait_connection(&mut self) {
self.read_ep.wait_enabled().await
self.read_ep.wait_enabled().await;
}
}

Expand Down Expand Up @@ -520,17 +519,17 @@ impl LineCoding {
}

/// Gets the number of data bits for UART communication.
pub fn data_bits(&self) -> u8 {
pub const fn data_bits(&self) -> u8 {
self.data_bits
}

/// Gets the parity type for UART communication.
pub fn parity_type(&self) -> ParityType {
pub const fn parity_type(&self) -> ParityType {
self.parity_type
}

/// Gets the data rate in bits per second for UART communication.
pub fn data_rate(&self) -> u32 {
pub const fn data_rate(&self) -> u32 {
self.data_rate
}
}
Expand Down
48 changes: 20 additions & 28 deletions embassy-usb/src/class/cdc_ncm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
use core::intrinsics::copy_nonoverlapping;
use core::mem::{size_of, MaybeUninit};
use core::ptr::addr_of;

use crate::control::{self, InResponse, OutResponse, Recipient, Request, RequestType};
use crate::driver::{Driver, Endpoint, EndpointError, EndpointIn, EndpointOut};
use crate::types::*;
use crate::types::{InterfaceNumber, StringIndex};
use crate::{Builder, Handler};

pub mod embassy_net;
Expand Down Expand Up @@ -62,9 +63,9 @@ const REQ_SET_NTB_INPUT_SIZE: u8 = 0x86;
//const NOTIF_POLL_INTERVAL: u8 = 20;

const NTB_MAX_SIZE: usize = 2048;
const SIG_NTH: u32 = 0x484d434e;
const SIG_NDP_NO_FCS: u32 = 0x304d434e;
const SIG_NDP_WITH_FCS: u32 = 0x314d434e;
const SIG_NTH: u32 = 0x484d_434e;
const SIG_NDP_NO_FCS: u32 = 0x304d_434e;
const SIG_NDP_WITH_FCS: u32 = 0x314d_434e;

const ALTERNATE_SETTING_DISABLED: u8 = 0x00;
const ALTERNATE_SETTING_ENABLED: u8 = 0x01;
Expand Down Expand Up @@ -111,7 +112,7 @@ struct NtbParametersDir {

fn byteify<T>(buf: &mut [u8], data: T) -> &[u8] {
let len = size_of::<T>();
unsafe { copy_nonoverlapping(&data as *const _ as *const u8, buf.as_mut_ptr(), len) }
unsafe { copy_nonoverlapping(addr_of!(data).cast(), buf.as_mut_ptr(), len) }
&buf[..len]
}

Expand All @@ -132,12 +133,12 @@ impl<'a> State<'a> {
pub fn new() -> Self {
Self {
control: MaybeUninit::uninit(),
shared: Default::default(),
shared: ControlShared::default(),
}
}
}

/// Shared data between Control and CdcAcmClass
/// Shared data between Control and `CdcAcmClass`
#[derive(Default)]
struct ControlShared {
mac_addr: [u8; 6],
Expand Down Expand Up @@ -378,12 +379,12 @@ impl<'d, D: Driver<'d>> Sender<'d, D> {
///
/// This waits until the packet is successfully stored in the CDC-NCM endpoint buffers.
pub async fn write_packet(&mut self, data: &[u8]) -> Result<(), EndpointError> {
let seq = self.seq;
self.seq = self.seq.wrapping_add(1);

const OUT_HEADER_LEN: usize = 28;
const ABS_MAX_PACKET_SIZE: usize = 512;

let seq = self.seq;
self.seq = self.seq.wrapping_add(1);

let header = NtbOutHeader {
nth_sig: SIG_NTH,
nth_len: 0x0c,
Expand Down Expand Up @@ -460,12 +461,9 @@ impl<'d, D: Driver<'d>> Receiver<'d, D> {
let ntb = &ntb[..pos];

// Process NTB header (NTH)
let nth = match ntb.get(..12) {
Some(x) => x,
None => {
warn!("Received too short NTB");
continue;
}
let Some(nth) = ntb.get(..12) else {
warn!("Received too short NTB");
continue;
};
let sig = u32::from_le_bytes(nth[0..4].try_into().unwrap());
if sig != SIG_NTH {
Expand All @@ -475,12 +473,9 @@ impl<'d, D: Driver<'d>> Receiver<'d, D> {
let ndp_idx = u16::from_le_bytes(nth[10..12].try_into().unwrap()) as usize;

// Process NTB Datagram Pointer (NDP)
let ndp = match ntb.get(ndp_idx..ndp_idx + 12) {
Some(x) => x,
None => {
warn!("NTH has an NDP pointer out of range.");
continue;
}
let Some(ndp) = ntb.get(ndp_idx..ndp_idx + 12) else {
warn!("NTH has an NDP pointer out of range.");
continue;
};
let sig = u32::from_le_bytes(ndp[0..4].try_into().unwrap());
if sig != SIG_NDP_NO_FCS && sig != SIG_NDP_WITH_FCS {
Expand All @@ -496,12 +491,9 @@ impl<'d, D: Driver<'d>> Receiver<'d, D> {
}

// Process actual datagram, finally.
let datagram = match ntb.get(datagram_index..datagram_index + datagram_len) {
Some(x) => x,
None => {
warn!("NDP has a datagram pointer out of range.");
continue;
}
let Some(datagram) = ntb.get(datagram_index..datagram_index + datagram_len) else {
warn!("NDP has a datagram pointer out of range.");
continue;
};
buf[..datagram_len].copy_from_slice(datagram);

Expand Down
Loading

0 comments on commit 31d4516

Please sign in to comment.