Skip to content

Commit 44d918a

Browse files
committed
refactor!: clippy and idiomatic Rust compliance
- Add clippy and Rust idiom lint attributes - Refactor code for clippy::pedantic and idiomatic style - Replace unwrap() with infallible constructors where possible - Improve error handling and documentation - Use assert! instead of panic! for invariants - Prefer From over Into for conversions - Update examples and tests for new API - Remove unused imports and code - Add Default implementation for Responder
1 parent da55724 commit 44d918a

File tree

14 files changed

+249
-171
lines changed

14 files changed

+249
-171
lines changed

examples/register.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,8 @@ pub fn main() {
33
builder.parse_filters("libmdns=debug");
44
builder.init();
55

6-
let responder = libmdns::Responder::new().unwrap();
7-
let _svc = responder.register(
8-
"_http._tcp".to_owned(),
9-
"libmdns Web Server".to_owned(),
10-
80,
11-
&["path=/"],
12-
);
6+
let responder = libmdns::Responder::new();
7+
let _svc = responder.register("_http._tcp", "libmdns Web Server", 80, &["path=/"]);
138

149
loop {
1510
::std::thread::sleep(::std::time::Duration::from_secs(10));

examples/register_with_ip_list.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,7 @@ pub fn main() {
1010
];
1111

1212
let responder = libmdns::Responder::new_with_ip_list(vec).unwrap();
13-
let _svc = responder.register(
14-
"_http._tcp".to_owned(),
15-
"libmdns Web Server".to_owned(),
16-
80,
17-
&["path=/"],
18-
);
13+
let _svc = responder.register("_http._tcp", "libmdns Web Server", 80, &["path=/"]);
1914

2015
loop {
2116
::std::thread::sleep(::std::time::Duration::from_secs(10));

src/dns_parser/builder.rs

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ impl Builder<Questions> {
4141
pub fn new_query(id: u16, recursion: bool) -> Builder<Questions> {
4242
let mut buf = Vec::with_capacity(512);
4343
let head = Header {
44-
id: id,
44+
id,
4545
query: true,
4646
opcode: Opcode::StandardQuery,
4747
authoritative: false,
@@ -57,7 +57,7 @@ impl Builder<Questions> {
5757
buf.extend([0u8; 12].iter());
5858
head.write(&mut buf[..12]);
5959
Builder {
60-
buf: buf,
60+
buf,
6161
max_size: Some(512),
6262
_state: PhantomData,
6363
}
@@ -66,10 +66,10 @@ impl Builder<Questions> {
6666
pub fn new_response(id: u16, recursion: bool, authoritative: bool) -> Builder<Questions> {
6767
let mut buf = Vec::with_capacity(512);
6868
let head = Header {
69-
id: id,
69+
id,
7070
query: false,
7171
opcode: Opcode::StandardQuery,
72-
authoritative: authoritative,
72+
authoritative,
7373
truncated: false,
7474
recursion_desired: recursion,
7575
recursion_available: false,
@@ -82,15 +82,15 @@ impl Builder<Questions> {
8282
buf.extend([0u8; 12].iter());
8383
head.write(&mut buf[..12]);
8484
Builder {
85-
buf: buf,
85+
buf,
8686
max_size: Some(512),
8787
_state: PhantomData,
8888
}
8989
}
9090
}
9191

9292
impl<T> Builder<T> {
93-
fn write_rr(&mut self, name: &Name, cls: QueryClass, ttl: u32, data: &RRData) {
93+
fn write_rr(&mut self, name: &Name<'_>, cls: QueryClass, ttl: u32, data: &RRData<'_>) {
9494
name.write_to(&mut self.buf).unwrap();
9595
self.buf.write_u16::<BigEndian>(data.typ() as u16).unwrap();
9696
self.buf.write_u16::<BigEndian>(cls as u16).unwrap();
@@ -103,6 +103,12 @@ impl<T> Builder<T> {
103103
data.write_to(&mut self.buf).unwrap();
104104
let data_size = self.buf.len() - data_offset;
105105

106+
assert!(
107+
(data_offset <= 65535),
108+
"{} is too long to write to a RR record",
109+
data_offset
110+
);
111+
#[allow(clippy::cast_possible_truncation)]
106112
BigEndian::write_u16(
107113
&mut self.buf[size_offset..size_offset + 2],
108114
data_size as u16,
@@ -166,7 +172,7 @@ impl<T: MoveTo<Questions>> Builder<T> {
166172
#[allow(dead_code)]
167173
pub fn add_question(
168174
self,
169-
qname: &Name,
175+
qname: &Name<'_>,
170176
qtype: QueryType,
171177
qclass: QueryClass,
172178
) -> Builder<Questions> {
@@ -183,10 +189,10 @@ impl<T: MoveTo<Questions>> Builder<T> {
183189
impl<T: MoveTo<Answers>> Builder<T> {
184190
pub fn add_answer(
185191
self,
186-
name: &Name,
192+
name: &Name<'_>,
187193
cls: QueryClass,
188194
ttl: u32,
189-
data: &RRData,
195+
data: &RRData<'_>,
190196
) -> Builder<Answers> {
191197
let mut builder = self.move_to::<Answers>();
192198

@@ -201,10 +207,10 @@ impl<T: MoveTo<Nameservers>> Builder<T> {
201207
#[allow(dead_code)]
202208
pub fn add_nameserver(
203209
self,
204-
name: &Name,
210+
name: &Name<'_>,
205211
cls: QueryClass,
206212
ttl: u32,
207-
data: &RRData,
213+
data: &RRData<'_>,
208214
) -> Builder<Nameservers> {
209215
let mut builder = self.move_to::<Nameservers>();
210216

@@ -219,10 +225,10 @@ impl Builder<Additional> {
219225
#[allow(dead_code)]
220226
pub fn add_additional(
221227
self,
222-
name: &Name,
228+
name: &Name<'_>,
223229
cls: QueryClass,
224230
ttl: u32,
225-
data: &RRData,
231+
data: &RRData<'_>,
226232
) -> Builder<Additional> {
227233
let mut builder = self.move_to::<Additional>();
228234

@@ -243,7 +249,7 @@ mod test {
243249
#[test]
244250
fn build_query() {
245251
let mut bld = Builder::new_query(1573, true);
246-
let name = Name::from_str("example.com").unwrap();
252+
let name = Name::from_str("example.com");
247253
bld = bld.add_question(&name, QT::A, QC::IN);
248254
let result = b"\x06%\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\
249255
\x07example\x03com\x00\x00\x01\x00\x01";
@@ -253,7 +259,7 @@ mod test {
253259
#[test]
254260
fn build_srv_query() {
255261
let mut bld = Builder::new_query(23513, true);
256-
let name = Name::from_str("_xmpp-server._tcp.gmail.com").unwrap();
262+
let name = Name::from_str("_xmpp-server._tcp.gmail.com");
257263
bld = bld.add_question(&name, QT::SRV, QC::IN);
258264
let result = b"[\xd9\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\
259265
\x0c_xmpp-server\x04_tcp\x05gmail\x03com\x00\x00!\x00\x01";

src/dns_parser/enums.rs

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use super::Error;
44
///
55
/// All "EXPERIMENTAL" markers here are from the RFC
66
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
7+
#[allow(clippy::upper_case_acronyms)]
78
pub enum Type {
89
/// a host addresss
910
A = 1,
@@ -55,6 +56,7 @@ pub enum Type {
5556
///
5657
/// All "EXPERIMENTAL" markers here are from the RFC
5758
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
59+
#[allow(clippy::upper_case_acronyms)]
5860
pub enum QueryType {
5961
/// a host addresss
6062
A = 1,
@@ -153,7 +155,7 @@ pub enum ResponseCode {
153155

154156
impl From<u16> for Opcode {
155157
fn from(code: u16) -> Opcode {
156-
use self::Opcode::*;
158+
use self::Opcode::{InverseQuery, Reserved, ServerStatusRequest, StandardQuery};
157159
match code {
158160
0 => StandardQuery,
159161
1 => InverseQuery,
@@ -162,10 +164,10 @@ impl From<u16> for Opcode {
162164
}
163165
}
164166
}
165-
impl Into<u16> for Opcode {
166-
fn into(self) -> u16 {
167-
use self::Opcode::*;
168-
match self {
167+
impl From<Opcode> for u16 {
168+
fn from(val: Opcode) -> Self {
169+
use self::Opcode::{InverseQuery, Reserved, ServerStatusRequest, StandardQuery};
170+
match val {
169171
StandardQuery => 0,
170172
InverseQuery => 1,
171173
ServerStatusRequest => 2,
@@ -176,7 +178,9 @@ impl Into<u16> for Opcode {
176178

177179
impl From<u8> for ResponseCode {
178180
fn from(code: u8) -> ResponseCode {
179-
use self::ResponseCode::*;
181+
use self::ResponseCode::{
182+
FormatError, NameError, NoError, NotImplemented, Refused, Reserved, ServerFailure,
183+
};
180184
match code {
181185
0 => NoError,
182186
1 => FormatError,
@@ -189,10 +193,12 @@ impl From<u8> for ResponseCode {
189193
}
190194
}
191195
}
192-
impl Into<u8> for ResponseCode {
193-
fn into(self) -> u8 {
194-
use self::ResponseCode::*;
195-
match self {
196+
impl From<ResponseCode> for u8 {
197+
fn from(val: ResponseCode) -> Self {
198+
use self::ResponseCode::{
199+
FormatError, NameError, NoError, NotImplemented, Refused, Reserved, ServerFailure,
200+
};
201+
match val {
196202
NoError => 0,
197203
FormatError => 1,
198204
ServerFailure => 2,
@@ -206,7 +212,10 @@ impl Into<u8> for ResponseCode {
206212

207213
impl QueryType {
208214
pub fn parse(code: u16) -> Result<QueryType, Error> {
209-
use self::QueryType::*;
215+
use self::QueryType::{
216+
All, A, AAAA, AXFR, CNAME, HINFO, MAILA, MAILB, MB, MF, MG, MINFO, MR, MX, NS, NULL,
217+
PTR, SOA, SRV, TXT, WKS,
218+
};
210219
match code {
211220
1 => Ok(A),
212221
2 => Ok(NS),
@@ -236,7 +245,7 @@ impl QueryType {
236245

237246
impl QueryClass {
238247
pub fn parse(code: u16) -> Result<QueryClass, Error> {
239-
use self::QueryClass::*;
248+
use self::QueryClass::{Any, CH, CS, HS, IN};
240249
match code {
241250
1 => Ok(IN),
242251
2 => Ok(CS),
@@ -250,7 +259,10 @@ impl QueryClass {
250259

251260
impl Type {
252261
pub fn parse(code: u16) -> Result<Type, Error> {
253-
use self::Type::*;
262+
use self::Type::{
263+
A, AAAA, CNAME, DNSKEY, DS, HINFO, MB, MF, MG, MINFO, MR, MX, NS, NSEC, NULL, OPT, PTR,
264+
RRSIG, SOA, SRV, TXT, WKS,
265+
};
254266
match code {
255267
1 => Ok(A),
256268
2 => Ok(NS),
@@ -281,7 +293,7 @@ impl Type {
281293

282294
impl Class {
283295
pub fn parse(code: u16) -> Result<Class, Error> {
284-
use self::Class::*;
296+
use self::Class::{CH, CS, HS, IN};
285297
match code {
286298
1 => Ok(IN),
287299
2 => Ok(CS),

src/dns_parser/error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,6 @@ pub enum Error {
2626
LabelIsNotAscii,
2727
#[error("parser is in the wrong state")]
2828
WrongState,
29+
#[error("label length exceeds maximum allowed size")]
30+
LabelTooLong,
2931
}

src/dns_parser/header.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ mod flag {
1515

1616
/// Represents parsed header of the packet
1717
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
18+
#[allow(clippy::struct_excessive_bools)]
1819
pub struct Header {
1920
pub id: u16,
2021
pub query: bool,
@@ -61,12 +62,10 @@ impl Header {
6162
///
6263
/// When buffer size is not exactly 12 bytes
6364
pub fn write(&self, data: &mut [u8]) {
64-
if data.len() != 12 {
65-
panic!("Header size is exactly 12 bytes");
66-
}
65+
assert_eq!(data.len(), 12, "Header size is exactly 12 bytes");
6766
let mut flags = 0u16;
68-
flags |= Into::<u16>::into(self.opcode) << flag::OPCODE_MASK.trailing_zeros();
69-
flags |= Into::<u8>::into(self.response_code) as u16;
67+
flags |= u16::from(self.opcode) << flag::OPCODE_MASK.trailing_zeros();
68+
flags |= u16::from(u8::from(self.response_code));
7069
if !self.query {
7170
flags |= flag::QUERY;
7271
}

src/dns_parser/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ pub use self::header::Header;
1212
mod rrdata;
1313
pub use self::rrdata::RRData;
1414
mod builder;
15-
pub use self::builder::{Answers, Builder, Questions};
15+
pub use self::builder::{Answers, Builder};

0 commit comments

Comments
 (0)