Skip to content

Commit

Permalink
Linux device checks for a folder existance during refresh (closes #29)
Browse files Browse the repository at this point in the history
  • Loading branch information
svartalf committed Jun 3, 2019
1 parent 34612e0 commit 505fdaa
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 20 deletions.
2 changes: 1 addition & 1 deletion battery-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ path = "../battery"
libc = "^0.2"

[build-dependencies]
cbindgen = { version = "0.8.0", optional = true }
cbindgen = { version = "0.8.7", optional = true }

[package.metadata.docs.rs]
no-default-features = true
4 changes: 2 additions & 2 deletions battery-ffi/src/battery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,13 @@ pub unsafe extern "C" fn battery_get_temperature(ptr: *const Battery) -> libc::c
///
/// # Returns
///
/// If value is not available, function returns max possible value for `uint32` type (`4294967295`).
/// If value is not available, function returns max possible value for the `u32` type (`4294967295`).
///
/// # Panics
///
/// This function will panic if passed pointer is `NULL`
#[no_mangle]
pub unsafe extern "C" fn battery_get_cycle_count(ptr: *const Battery) -> libc::uint32_t {
pub unsafe extern "C" fn battery_get_cycle_count(ptr: *const Battery) -> u32 {
assert!(!ptr.is_null());
let battery = &*ptr;

Expand Down
4 changes: 2 additions & 2 deletions battery/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@ core-foundation = "0.6.4"
winapi = { version ="0.3.7", features = ["impl-default", "devguid", "winbase", "ioapiset", "ntdef", "setupapi", "handleapi", "errhandlingapi", "winerror"] }

[target.'cfg(any(target_os = "dragonfly", target_os = "freebsd"))'.dependencies]
nix = "0.13.0"
libc = "0.2.51"
nix = "^0.14"
libc = "^0.2"
33 changes: 22 additions & 11 deletions battery/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Errors handling
//!

use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;
use std::io;
Expand All @@ -15,21 +16,31 @@ pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub struct Error {
source: io::Error,
description: Option<&'static str>,
description: Option<Cow<'static, str>>,
}

impl Error {
pub fn not_found(description: &'static str) -> Error {
#[allow(unused)]
pub(crate) fn new<T>(e: io::Error, description: T) -> Error where T: Into<Cow<'static, str>> {
Error {
source: e,
description: Some(description.into()),
}
}

#[allow(unused)]
pub(crate) fn not_found<T>(description: T) -> Error where T: Into<Cow<'static, str>> {
Error {
source: io::Error::from(io::ErrorKind::NotFound),
description: Some(description),
description: Some(description.into()),
}
}

pub fn invalid_data(description: &'static str) -> Error {
#[allow(unused)]
pub(crate) fn invalid_data<T>(description: T) -> Error where T: Into<Cow<'static, str>> {
Error {
source: io::Error::from(io::ErrorKind::InvalidData),
description: Some(description),
description: Some(description.into()),
}
}
}
Expand All @@ -42,7 +53,7 @@ impl StdError for Error {

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.description {
match &self.description {
Some(desc) => write!(f, "{}", desc),
None => self.source.fmt(f),
}
Expand All @@ -69,19 +80,19 @@ mod nix_impl {
match e {
nix::Error::Sys(errno) => Error {
source: io::Error::from_raw_os_error(errno as i32),
description: Some(errno.desc()),
description: Some(errno.desc().into()),
},
nix::Error::InvalidPath => Error {
source: io::Error::new(io::ErrorKind::InvalidInput, e),
description: Some("Invalid path"),
description: Some("Invalid path".into()),
},
nix::Error::InvalidUtf8 => Error {
source: io::Error::new(io::ErrorKind::InvalidData, e),
description: Some("Invalid UTF-8 string"),
description: Some("Invalid UTF-8 string".into()),
},
nix::Error::UnsupportedOperation => Error {
source: io::Error::new(io::ErrorKind::Other, e),
description: Some("Unsupported operation"),
description: Some("Unsupported operation".into()),
},
}
}
Expand Down
23 changes: 19 additions & 4 deletions battery/src/platform/linux/device.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::io;
use std::fmt;
use std::path::{Path, PathBuf};

use crate::platform::traits::*;
use crate::units::{ElectricPotential, Energy, Power, Ratio, ThermodynamicTemperature};
use crate::{Result, State, Technology};
use crate::{Result, Error, State, Technology};

use super::sysfs::{fs, DataBuilder, InstantData, Scope, Type};

Expand Down Expand Up @@ -50,9 +51,23 @@ impl SysFsDevice {
}

pub fn refresh(&mut self) -> Result<()> {
let builder = DataBuilder::new(&self.root);
self.source = builder.collect()?;
Ok(())
// It is necessary to ensure that `self.root`
// still exists and accessible.
// See https://github.com/svartalf/rust-battery/issues/29
if self.root.is_dir() {
let builder = DataBuilder::new(&self.root);
self.source = builder.collect()?;

Ok(())
} else {
let inner = io::Error::from(io::ErrorKind::NotFound);
let e = Error::new(
inner,
format!("Device directory `{:?}` is missing", self.root),
);

Err(e)
}
}
}

Expand Down

0 comments on commit 505fdaa

Please sign in to comment.