cart_tmp_wgc/
power.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use std::fmt;
6
7#[derive(Debug)]
8pub enum Error {
9    Unsupported,
10    Error(Box<dyn std::error::Error>),
11}
12
13impl fmt::Display for Error {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        match self {
16            Error::Unsupported => write!(f, "Battery status is unsupported on this platform"),
17            Error::Error(err) => write!(f, "Battery status retrieval failed: {}", err),
18        }
19    }
20}
21
22#[cfg(all(
23    feature = "battery",
24    any(
25        target_os = "linux",
26        target_os = "macos",
27        target_os = "windows",
28        target_os = "dragonfly",
29        target_os = "freebsd"
30    )
31))]
32mod platform {
33    use super::Error;
34    use battery::{self, Manager, State};
35
36    impl From<battery::errors::Error> for Error {
37        fn from(err: battery::errors::Error) -> Error {
38            // Box the error so that the battery::errors::Error type does
39            // not leak out of this module.
40            Error::Error(Box::new(err))
41        }
42    }
43
44    pub fn is_battery_discharging() -> Result<bool, Error> {
45        let manager = Manager::new()?;
46        for battery in manager.batteries()? {
47            if battery?.state() == State::Discharging {
48                return Ok(true);
49            }
50        }
51        Ok(false)
52    }
53}
54
55#[cfg(any(
56    not(feature = "battery"),
57    not(any(
58        target_os = "linux",
59        target_os = "macos",
60        target_os = "windows",
61        target_os = "dragonfly",
62        target_os = "freebsd"
63    ))
64))]
65mod platform {
66    use super::Error;
67
68    pub fn is_battery_discharging() -> Result<bool, Error> {
69        Err(Error::Unsupported)
70    }
71}
72
73pub use platform::is_battery_discharging;