Skip to content

Commit ba43227

Browse files
authored
Merge pull request #34 from Razican/untry
Removed try! macro in favour of the ? operator
2 parents 606e123 + b776dc5 commit ba43227

File tree

6 files changed

+88
-91
lines changed

6 files changed

+88
-91
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
language: rust
22
sudo: false
33
rust:
4-
- 1.10.0
4+
- 1.15.0
55
- stable
66
- beta
77
- nightly

examples/blinky.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@ struct Arguments {
2323
fn blink_my_led(led: u64, duration_ms: u64, period_ms: u64) -> sysfs_gpio::Result<()> {
2424
let my_led = Pin::new(led);
2525
my_led.with_exported(|| {
26-
try!(my_led.set_direction(Direction::Low));
26+
my_led.set_direction(Direction::Low)?;
2727
let iterations = duration_ms / period_ms / 2;
2828
for _ in 0..iterations {
29-
try!(my_led.set_value(0));
29+
my_led.set_value(0)?;
3030
sleep(Duration::from_millis(period_ms));
31-
try!(my_led.set_value(1));
31+
my_led.set_value(1)?;
3232
sleep(Duration::from_millis(period_ms));
3333
}
34-
try!(my_led.set_value(0));
34+
my_led.set_value(0)?;
3535
Ok(())
3636
})
3737
}
@@ -58,10 +58,10 @@ fn get_args() -> Option<Arguments> {
5858
Err(_) => return None,
5959
};
6060
Some(Arguments {
61-
pin: pin,
62-
duration_ms: duration_ms,
63-
period_ms: period_ms,
64-
})
61+
pin: pin,
62+
duration_ms: duration_ms,
63+
period_ms: period_ms,
64+
})
6565
}
6666

6767
fn main() {

examples/interrupt.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,16 @@ use std::io::stdout;
1616
fn interrupt(pin: u64) -> sysfs_gpio::Result<()> {
1717
let input = Pin::new(pin);
1818
input.with_exported(|| {
19-
try!(input.set_direction(Direction::In));
20-
try!(input.set_edge(Edge::BothEdges));
21-
let mut poller = try!(input.get_poller());
19+
input.set_direction(Direction::In)?;
20+
input.set_edge(Edge::BothEdges)?;
21+
let mut poller = input.get_poller()?;
2222
loop {
23-
match try!(poller.poll(1000)) {
23+
match poller.poll(1000)? {
2424
Some(value) => println!("{}", value),
2525
None => {
2626
let mut stdout = stdout();
27-
try!(stdout.write_all(b"."));
28-
try!(stdout.flush());
27+
stdout.write_all(b".")?;
28+
stdout.flush()?;
2929
}
3030
}
3131
}

examples/poll.rs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,12 @@ fn poll(pin_num: u64) -> sysfs_gpio::Result<()> {
2121
// really present at the moment. Revisit later.
2222
let input = Pin::new(pin_num);
2323
input.with_exported(|| {
24-
try!(input.set_direction(Direction::In));
24+
input.set_direction(Direction::In)?;
2525
let mut prev_val: u8 = 255;
2626
loop {
27-
let val = try!(input.get_value());
27+
let val = input.get_value()?;
2828
if val != prev_val {
29-
println!("Pin State: {}",
30-
if val == 0 {
31-
"Low"
32-
} else {
33-
"High"
34-
});
29+
println!("Pin State: {}", if val == 0 { "Low" } else { "High" });
3530
prev_val = val;
3631
}
3732
sleep(Duration::from_millis(10));

examples/tokio.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,18 @@ fn stream(pin_nums: Vec<u64>) -> sysfs_gpio::Result<()> {
2222
// can be done about this as Rust signal handling isn't
2323
// really present at the moment. Revisit later.
2424
let pins: Vec<_> = pin_nums.iter().map(|&p| (p, Pin::new(p))).collect();
25-
let mut l = try!(Core::new());
25+
let mut l = Core::new()?;
2626
let handle = l.handle();
2727
for &(i, ref pin) in pins.iter() {
28-
try!(pin.export());
29-
try!(pin.set_direction(Direction::In));
30-
try!(pin.set_edge(Edge::BothEdges));
31-
handle.spawn(try!(pin.get_value_stream(&handle))
32-
.for_each(move |val| {
33-
println!("Pin {} changed value to {}", i, val);
34-
Ok(())
35-
})
36-
.map_err(|_| ()));
28+
pin.export()?;
29+
pin.set_direction(Direction::In)?;
30+
pin.set_edge(Edge::BothEdges)?;
31+
handle.spawn(pin.get_value_stream(&handle)?
32+
.for_each(move |val| {
33+
println!("Pin {} changed value to {}", i, val);
34+
Ok(())
35+
})
36+
.map_err(|_| ()));
3737
}
3838
// Wait forever for events
3939
loop {

src/lib.rs

Lines changed: 60 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,8 @@ fn flush_input_from_file(dev_file: &mut File, max: usize) -> io::Result<usize> {
122122
/// Get the pin value from the provided file
123123
fn get_value_from_file(dev_file: &mut File) -> Result<u8> {
124124
let mut s = String::with_capacity(10);
125-
try!(dev_file.seek(SeekFrom::Start(0)));
126-
try!(dev_file.read_to_string(&mut s));
125+
dev_file.seek(SeekFrom::Start(0))?;
126+
dev_file.read_to_string(&mut s)?;
127127
match s[..1].parse::<u8>() {
128128
Ok(n) => Ok(n),
129129
Err(_) => Err(Error::Unexpected(format!("Unexpected value file contents: {:?}", s))),
@@ -134,16 +134,16 @@ impl Pin {
134134
/// Write all of the provided contents to the specified devFile
135135
fn write_to_device_file(&self, dev_file_name: &str, value: &str) -> io::Result<()> {
136136
let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name);
137-
let mut dev_file = try!(File::create(&gpio_path));
138-
try!(dev_file.write_all(value.as_bytes()));
137+
let mut dev_file = File::create(&gpio_path)?;
138+
dev_file.write_all(value.as_bytes())?;
139139
Ok(())
140140
}
141141

142142
fn read_from_device_file(&self, dev_file_name: &str) -> io::Result<String> {
143143
let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name);
144-
let mut dev_file = try!(File::open(&gpio_path));
144+
let mut dev_file = File::open(&gpio_path)?;
145145
let mut s = String::new();
146-
try!(dev_file.read_to_string(&mut s));
146+
dev_file.read_to_string(&mut s)?;
147147
Ok(s)
148148
}
149149

@@ -168,12 +168,13 @@ impl Pin {
168168
/// will return an error.
169169
pub fn from_path<T: AsRef<Path>>(path: T) -> Result<Pin> {
170170
// Resolve all symbolic links in the provided path
171-
let pb = try!(fs::canonicalize(path.as_ref()));
171+
let pb = fs::canonicalize(path.as_ref())?;
172172

173173
// determine if this is valid and figure out the pin_num
174-
if !try!(fs::metadata(&pb)).is_dir() {
174+
if !fs::metadata(&pb)?.is_dir() {
175175
return Err(Error::Unexpected("Provided path not a directory or symlink to \
176-
a directory".to_owned()));
176+
a directory"
177+
.to_owned()));
177178
}
178179

179180
let re = regex::Regex::new(r"^/sys/.*?/gpio/gpio(\d+)$").unwrap();
@@ -183,10 +184,12 @@ impl Pin {
183184
};
184185

185186
let num: u64 = match caps.at(1) {
186-
Some(num) => match num.parse() {
187-
Ok(unum) => unum,
188-
Err(_) => return Err(Error::InvalidPath(format!("{:?}", pb))),
189-
},
187+
Some(num) => {
188+
match num.parse() {
189+
Ok(unum) => unum,
190+
Err(_) => return Err(Error::InvalidPath(format!("{:?}", pb))),
191+
}
192+
}
190193
None => return Err(Error::InvalidPath(format!("{:?}", pb))),
191194
};
192195

@@ -221,14 +224,14 @@ impl Pin {
221224
#[inline]
222225
pub fn with_exported<F: FnOnce() -> Result<()>>(&self, closure: F) -> Result<()> {
223226

224-
try!(self.export());
227+
self.export()?;
225228
match closure() {
226229
Ok(()) => {
227230
try!(self.unexport());
228231
Ok(())
229232
}
230233
Err(err) => {
231-
try!(self.unexport());
234+
self.unexport()?;
232235
Err(err)
233236
}
234237
}
@@ -269,8 +272,9 @@ impl Pin {
269272
/// ```
270273
pub fn export(&self) -> Result<()> {
271274
if fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)).is_err() {
272-
let mut export_file = try!(File::create("/sys/class/gpio/export"));
273-
try!(export_file.write_all(format!("{}", self.pin_num).as_bytes()));
275+
let mut export_file = File::create("/sys/class/gpio/export")?;
276+
export_file
277+
.write_all(format!("{}", self.pin_num).as_bytes())?;
274278
}
275279
Ok(())
276280
}
@@ -283,8 +287,9 @@ impl Pin {
283287
/// this function returns Ok, the GPIO is not exported.
284288
pub fn unexport(&self) -> Result<()> {
285289
if fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)).is_ok() {
286-
let mut unexport_file = try!(File::create("/sys/class/gpio/unexport"));
287-
try!(unexport_file.write_all(format!("{}", self.pin_num).as_bytes()));
290+
let mut unexport_file = File::create("/sys/class/gpio/unexport")?;
291+
unexport_file
292+
.write_all(format!("{}", self.pin_num).as_bytes())?;
288293
}
289294
Ok(())
290295
}
@@ -324,13 +329,12 @@ impl Pin {
324329
/// not support changing the direction of a pin in userspace. If
325330
/// this is the case, you will get an error.
326331
pub fn set_direction(&self, dir: Direction) -> Result<()> {
327-
try!(self.write_to_device_file("direction",
328-
match dir {
329-
Direction::In => "in",
330-
Direction::Out => "out",
331-
Direction::High => "high",
332-
Direction::Low => "low",
333-
}));
332+
self.write_to_device_file("direction", match dir {
333+
Direction::In => "in",
334+
Direction::Out => "out",
335+
Direction::High => "high",
336+
Direction::Low => "low",
337+
})?;
334338

335339
Ok(())
336340
}
@@ -360,11 +364,10 @@ impl Pin {
360364
/// A 0 value will set the pin low and any other value will
361365
/// set the pin high (1 is typical).
362366
pub fn set_value(&self, value: u8) -> Result<()> {
363-
try!(self.write_to_device_file("value",
364-
match value {
365-
0 => "0",
366-
_ => "1",
367-
}));
367+
self.write_to_device_file("value", match value {
368+
0 => "0",
369+
_ => "1",
370+
})?;
368371

369372
Ok(())
370373
}
@@ -394,13 +397,12 @@ impl Pin {
394397
/// result in `poll()` returning. This call will return an Error
395398
/// if the pin does not allow interrupts.
396399
pub fn set_edge(&self, edge: Edge) -> Result<()> {
397-
try!(self.write_to_device_file("edge",
398-
match edge {
399-
Edge::NoInterrupt => "none",
400-
Edge::RisingEdge => "rising",
401-
Edge::FallingEdge => "falling",
402-
Edge::BothEdges => "both",
403-
}));
400+
self.write_to_device_file("edge", match edge {
401+
Edge::NoInterrupt => "none",
402+
Edge::RisingEdge => "rising",
403+
Edge::FallingEdge => "falling",
404+
Edge::BothEdges => "both",
405+
})?;
404406

405407
Ok(())
406408
}
@@ -449,7 +451,7 @@ impl Pin {
449451
/// This method is only available when the `tokio` crate feature is enabled.
450452
#[cfg(feature = "tokio")]
451453
pub fn get_value_stream(&self, handle: &Handle) -> Result<PinValueStream> {
452-
Ok(PinValueStream(try!(PinStream::init(self.clone(), handle))))
454+
Ok(PinValueStream(PinStream::init(self.clone(), handle)?))
453455
}
454456
}
455457

@@ -472,9 +474,9 @@ impl PinPoller {
472474
/// Create a new PinPoller for the provided pin number
473475
#[cfg(any(target_os = "linux", target_os = "android"))]
474476
pub fn new(pin_num: u64) -> Result<PinPoller> {
475-
let devfile: File = try!(File::open(&format!("/sys/class/gpio/gpio{}/value", pin_num)));
477+
let devfile: File = File::open(&format!("/sys/class/gpio/gpio{}/value", pin_num))?;
476478
let devfile_fd = devfile.as_raw_fd();
477-
let epoll_fd = try!(epoll_create());
479+
let epoll_fd = epoll_create()?;
478480
let events = EPOLLPRI | EPOLLET;
479481
let info = EpollEvent {
480482
events: events,
@@ -484,10 +486,10 @@ impl PinPoller {
484486
match epoll_ctl(epoll_fd, EpollOp::EpollCtlAdd, devfile_fd, &info) {
485487
Ok(_) => {
486488
Ok(PinPoller {
487-
pin_num: pin_num,
488-
devfile: devfile,
489-
epoll_fd: epoll_fd,
490-
})
489+
pin_num: pin_num,
490+
devfile: devfile,
491+
epoll_fd: epoll_fd,
492+
})
491493
}
492494
Err(err) => {
493495
let _ = close(epoll_fd); // cleanup
@@ -520,17 +522,17 @@ impl PinPoller {
520522
/// occurred and the current time.
521523
#[cfg(any(target_os = "linux", target_os = "android"))]
522524
pub fn poll(&mut self, timeout_ms: isize) -> Result<Option<u8>> {
523-
try!(flush_input_from_file(&mut self.devfile, 255));
525+
flush_input_from_file(&mut self.devfile, 255)?;
524526
let dummy_event = EpollEvent {
525527
events: EPOLLPRI | EPOLLET,
526528
data: 0u64,
527529
};
528530
let mut events: [EpollEvent; 1] = [dummy_event];
529-
let cnt = try!(epoll_wait(self.epoll_fd, &mut events, timeout_ms));
531+
let cnt = epoll_wait(self.epoll_fd, &mut events, timeout_ms)?;
530532
Ok(match cnt {
531-
0 => None, // timeout
532-
_ => Some(try!(get_value_from_file(&mut self.devfile))),
533-
})
533+
0 => None, // timeout
534+
_ => Some(get_value_from_file(&mut self.devfile)?),
535+
})
534536
}
535537

536538
#[cfg(not(any(target_os = "linux", target_os = "android")))]
@@ -544,7 +546,7 @@ impl Drop for PinPoller {
544546
// we implement drop to close the underlying epoll fd as
545547
// it does not implement drop itself. This is similar to
546548
// how mio works
547-
close(self.epoll_fd).unwrap(); // panic! if close files
549+
close(self.epoll_fd).unwrap(); // panic! if close files
548550
}
549551
}
550552

@@ -557,7 +559,7 @@ pub struct AsyncPinPoller {
557559
#[cfg(feature = "mio-evented")]
558560
impl AsyncPinPoller {
559561
fn new(pin_num: u64) -> Result<Self> {
560-
let devfile = try!(File::open(&format!("/sys/class/gpio/gpio{}/value", pin_num)));
562+
let devfile = File::open(&format!("/sys/class/gpio/gpio{}/value", pin_num))?;
561563
Ok(AsyncPinPoller { devfile: devfile })
562564
}
563565
}
@@ -597,9 +599,9 @@ pub struct PinStream {
597599
impl PinStream {
598600
pub fn init(pin: Pin, handle: &Handle) -> Result<Self> {
599601
Ok(PinStream {
600-
evented: try!(PollEvented::new(try!(pin.get_async_poller()), &handle)),
601-
skipped_first_event: false,
602-
})
602+
evented: PollEvented::new(pin.get_async_poller()?, &handle)?,
603+
skipped_first_event: false,
604+
})
603605
}
604606
}
605607

@@ -610,7 +612,7 @@ impl Stream for PinStream {
610612

611613
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
612614
Ok(match self.evented.poll_read() {
613-
Async::Ready(()) => {
615+
Async::Ready(()) => {
614616
self.evented.need_read();
615617
if self.skipped_first_event {
616618
Async::Ready(Some(()))
@@ -619,8 +621,8 @@ impl Stream for PinStream {
619621
Async::NotReady
620622
}
621623
}
622-
Async::NotReady => Async::NotReady,
623-
})
624+
Async::NotReady => Async::NotReady,
625+
})
624626
}
625627
}
626628

0 commit comments

Comments
 (0)