Skip to content

Commit 634553b

Browse files
author
Rusty Rain
authored
Merge pull request #20 from algesten/anyhow
Refactor out use of anyhow
2 parents 5a04493 + c56861d commit 634553b

22 files changed

+144
-140
lines changed

crates/mdns/Cargo.toml

+2-3
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,11 @@ default = [ "reuse_port" ]
1616
reuse_port = []
1717

1818
[dependencies]
19-
util = { package = "webrtc-util", version = "0.4.3", default-features = false, features = ["ifaces"] }
19+
util = { package = "webrtc-util", version = "0.5.0", default-features = false, features = ["ifaces"] }
2020
tokio = { version = "1.12.0", features = ["full"] }
2121
socket2 = { version = "0.4.2", features = ["all"] }
2222
log = "0.4"
23-
thiserror = "1.0.29"
24-
anyhow = "1.0.44"
23+
thiserror = "1.0"
2524

2625
[dev-dependencies]
2726
env_logger = "0.9"

crates/mdns/examples/mdns_query.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use webrtc_mdns as mdns;
22

3+
use mdns::Error;
34
use mdns::{config::*, conn::*};
45

5-
use anyhow::Result;
66
use clap::{App, AppSettings, Arg};
77
use std::net::SocketAddr;
88
use std::str::FromStr;
@@ -15,7 +15,7 @@ use tokio::sync::mpsc;
1515
// cargo run --color=always --package webrtc-mdns --example mdns_query -- --local-name pion-test.local
1616

1717
#[tokio::main]
18-
async fn main() -> Result<()> {
18+
async fn main() -> Result<(), Error> {
1919
env_logger::init();
2020

2121
let mut app = App::new("mDNS Query")

crates/mdns/examples/mdns_server.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use webrtc_mdns as mdns;
22

3+
use mdns::Error;
34
use mdns::{config::*, conn::*};
45

5-
use anyhow::Result;
66
use clap::{App, AppSettings, Arg};
77
use std::net::SocketAddr;
88
use std::str::FromStr;
@@ -14,7 +14,7 @@ use std::str::FromStr;
1414
// cargo run --color=always --package webrtc-mdns --example mdns_server -- --local-name pion-test.local
1515

1616
#[tokio::main]
17-
async fn main() -> Result<()> {
17+
async fn main() -> Result<(), Error> {
1818
env_logger::init();
1919

2020
let mut app = App::new("mDNS Sever")

crates/mdns/src/conn/conn_test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ mod test {
1313
server_a.close().await?;
1414

1515
if let Err(err) = server_a.close().await {
16-
assert!(Error::ErrConnectionClosed.equal(&err));
16+
assert_eq!(Error::ErrConnectionClosed, err);
1717
} else {
1818
assert!(false, "expected error, but got ok");
1919
}

crates/mdns/src/conn/mod.rs

+9-10
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr};
77
use std::sync::Arc;
88
use std::time::Duration;
99

10-
use anyhow::Result;
1110
use core::sync::atomic;
1211
use socket2::SockAddr;
1312
use tokio::net::{ToSocketAddrs, UdpSocket};
@@ -71,7 +70,7 @@ impl DnsConn {
7170
Ok(e) => e,
7271
Err(e) => {
7372
log::error!("Error getting interfaces: {:?}", e);
74-
return Err(Error::new(e.to_string()).into());
73+
return Err(Error::Other(e.to_string()));
7574
}
7675
};
7776

@@ -89,7 +88,7 @@ impl DnsConn {
8988
}
9089

9190
if join_error_count >= interfaces.len() {
92-
return Err(Error::ErrJoiningMulticastGroup.into());
91+
return Err(Error::ErrJoiningMulticastGroup);
9392
}
9493
}
9594

@@ -143,7 +142,7 @@ impl DnsConn {
143142
pub async fn close(&self) -> Result<()> {
144143
log::info!("Closing connection");
145144
if self.is_server_closed.load(atomic::Ordering::SeqCst) {
146-
return Err(Error::ErrConnectionClosed.into());
145+
return Err(Error::ErrConnectionClosed);
147146
}
148147

149148
log::trace!("Sending close command to server");
@@ -154,7 +153,7 @@ impl DnsConn {
154153
}
155154
Err(e) => {
156155
log::warn!("Error sending close command to server: {:?}", e);
157-
Err(Error::ErrConnectionClosed.into())
156+
Err(Error::ErrConnectionClosed)
158157
}
159158
}
160159
}
@@ -167,7 +166,7 @@ impl DnsConn {
167166
mut close_query_signal: mpsc::Receiver<()>,
168167
) -> Result<(ResourceHeader, SocketAddr)> {
169168
if self.is_server_closed.load(atomic::Ordering::SeqCst) {
170-
return Err(Error::ErrConnectionClosed.into());
169+
return Err(Error::ErrConnectionClosed);
171170
}
172171

173172
let name_with_suffix = name.to_owned() + ".";
@@ -193,7 +192,7 @@ impl DnsConn {
193192

194193
_ = close_query_signal.recv() => {
195194
log::info!("Query close signal received.");
196-
return Err(Error::ErrConnectionClosed.into())
195+
return Err(Error::ErrConnectionClosed)
197196
},
198197

199198
res_opt = query_rx.recv() =>{
@@ -321,7 +320,7 @@ async fn run(
321320
let q = match p.question() {
322321
Ok(q) => q,
323322
Err(err) => {
324-
if Error::ErrSectionDone.equal(&err) {
323+
if Error::ErrSectionDone == err {
325324
log::trace!("Parsing has completed");
326325
break;
327326
} else {
@@ -353,7 +352,7 @@ async fn run(
353352
let a = match p.answer_header() {
354353
Ok(a) => a,
355354
Err(err) => {
356-
if !Error::ErrSectionDone.equal(&err) {
355+
if Error::ErrSectionDone != err {
357356
log::warn!("Failed to parse mDNS packet {}", err);
358357
}
359358
return;
@@ -407,7 +406,7 @@ async fn send_answer(
407406
a: match interface_addr.ip() {
408407
IpAddr::V4(ip) => ip.octets(),
409408
IpAddr::V6(_) => {
410-
return Err(Error::new("Unexpected IpV6 addr".to_owned()).into())
409+
return Err(Error::Other("Unexpected IpV6 addr".to_owned()))
411410
}
412411
},
413412
})),

crates/mdns/src/error.rs

+28-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
use thiserror::Error;
22

3+
use std::io;
4+
use std::net;
5+
use std::string::FromUtf8Error;
6+
7+
pub type Result<T> = std::result::Result<T, Error>;
8+
39
#[derive(Debug, Error, PartialEq)]
10+
#[non_exhaustive]
411
pub enum Error {
512
#[error("mDNS: failed to join multicast group")]
613
ErrJoiningMulticastGroup,
@@ -52,14 +59,29 @@ pub enum Error {
5259
ErrCompressedSrv,
5360
#[error("empty builder msg")]
5461
ErrEmptyBuilderMsg,
55-
56-
#[allow(non_camel_case_types)]
5762
#[error("{0}")]
58-
new(String),
63+
Io(#[source] IoError),
64+
#[error("utf-8 error: {0}")]
65+
Utf8(#[from] FromUtf8Error),
66+
#[error("parse addr: {0}")]
67+
ParseIp(#[from] net::AddrParseError),
68+
#[error("{0}")]
69+
Other(String),
70+
}
71+
72+
#[derive(Debug, Error)]
73+
#[error("io error: {0}")]
74+
pub struct IoError(#[from] pub io::Error);
75+
76+
// Workaround for wanting PartialEq for io::Error.
77+
impl PartialEq for IoError {
78+
fn eq(&self, other: &Self) -> bool {
79+
self.0.kind() == other.0.kind()
80+
}
5981
}
6082

61-
impl Error {
62-
pub fn equal(&self, err: &anyhow::Error) -> bool {
63-
err.downcast_ref::<Self>().map_or(false, |e| e == self)
83+
impl From<io::Error> for Error {
84+
fn from(e: io::Error) -> Self {
85+
Error::Io(IoError(e))
6486
}
6587
}

crates/mdns/src/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,7 @@
33

44
pub mod config;
55
pub mod conn;
6-
pub mod error;
6+
mod error;
77
pub mod message;
8+
9+
pub use error::Error;

crates/mdns/src/message/builder.rs

+13-14
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use super::resource::*;
44
use super::*;
55
use crate::error::*;
66

7-
use anyhow::Result;
87
use std::collections::HashMap;
98

109
// A Builder allows incrementally packing a DNS message.
@@ -84,10 +83,10 @@ impl Builder {
8483

8584
fn start_check(&self, section: Section) -> Result<()> {
8685
if self.section <= Section::NotStarted {
87-
return Err(Error::ErrNotStarted.into());
86+
return Err(Error::ErrNotStarted);
8887
}
8988
if self.section > section {
90-
return Err(Error::ErrSectionDone.into());
89+
return Err(Error::ErrSectionDone);
9190
}
9291

9392
Ok(())
@@ -128,13 +127,13 @@ impl Builder {
128127
Section::Answers => (&mut self.header.answers, Error::ErrTooManyAnswers),
129128
Section::Authorities => (&mut self.header.authorities, Error::ErrTooManyAuthorities),
130129
Section::Additionals => (&mut self.header.additionals, Error::ErrTooManyAdditionals),
131-
Section::NotStarted => return Err(Error::ErrNotStarted.into()),
132-
Section::Done => return Err(Error::ErrSectionDone.into()),
133-
Section::Header => return Err(Error::ErrSectionHeader.into()),
130+
Section::NotStarted => return Err(Error::ErrNotStarted),
131+
Section::Done => return Err(Error::ErrSectionDone),
132+
Section::Header => return Err(Error::ErrSectionHeader),
134133
};
135134

136135
if *count == u16::MAX {
137-
Err(err.into())
136+
Err(err)
138137
} else {
139138
*count += 1;
140139
Ok(())
@@ -144,10 +143,10 @@ impl Builder {
144143
// question adds a single question.
145144
pub fn add_question(&mut self, q: &Question) -> Result<()> {
146145
if self.section < Section::Questions {
147-
return Err(Error::ErrNotStarted.into());
146+
return Err(Error::ErrNotStarted);
148147
}
149148
if self.section > Section::Questions {
150-
return Err(Error::ErrSectionDone.into());
149+
return Err(Error::ErrSectionDone);
151150
}
152151
let msg = self.msg.take();
153152
if let Some(mut msg) = msg {
@@ -161,10 +160,10 @@ impl Builder {
161160

162161
fn check_resource_section(&self) -> Result<()> {
163162
if self.section < Section::Answers {
164-
return Err(Error::ErrNotStarted.into());
163+
return Err(Error::ErrNotStarted);
165164
}
166165
if self.section > Section::Additionals {
167-
return Err(Error::ErrSectionDone.into());
166+
return Err(Error::ErrSectionDone);
168167
}
169168
Ok(())
170169
}
@@ -176,7 +175,7 @@ impl Builder {
176175
if let Some(body) = &r.body {
177176
r.header.typ = body.real_type();
178177
} else {
179-
return Err(Error::ErrNilResourceBody.into());
178+
return Err(Error::ErrNilResourceBody);
180179
}
181180

182181
if let Some(msg) = self.msg.take() {
@@ -196,7 +195,7 @@ impl Builder {
196195
// Finish ends message building and generates a binary message.
197196
pub fn finish(&mut self) -> Result<Vec<u8>> {
198197
if self.section < Section::Header {
199-
return Err(Error::ErrNotStarted.into());
198+
return Err(Error::ErrNotStarted);
200199
}
201200
self.section = Section::Done;
202201

@@ -207,7 +206,7 @@ impl Builder {
207206
msg[..HEADER_LEN].copy_from_slice(&buf[..HEADER_LEN]);
208207
Ok(msg)
209208
} else {
210-
Err(Error::ErrEmptyBuilderMsg.into())
209+
Err(Error::ErrEmptyBuilderMsg)
211210
}
212211
}
213212
}

0 commit comments

Comments
 (0)