Skip to content

Instantly share code, notes, and snippets.

@aelloc
Created February 15, 2026 13:16
Show Gist options
  • Select an option

  • Save aelloc/a06c67a2e650b6b486ae2dfbca58dcc8 to your computer and use it in GitHub Desktop.

Select an option

Save aelloc/a06c67a2e650b6b486ae2dfbca58dcc8 to your computer and use it in GitHub Desktop.
Random Rust snippet
use regex::Regex;
use std::fs;
use std::path::Path;
fn main() {
let _ = get_battery_path();
let p = get_battery_percentages();
let s = get_battery_status();
println!("{:?}", p);
println!("{:?}", s);
}
fn get_battery_path() -> Vec<fs::DirEntry> {
let global_path = Path::new("/sys/class/power_supply/");
let re = Regex::new(r"BAT[0-9]+").expect("Wrong RegEx");
global_path
.read_dir()
.unwrap()
.filter_map(|el| el.ok())
.filter(|el| re.is_match(el.path().to_str().unwrap()))
.collect()
}
fn get_battery_percentages() -> Vec<String> {
let batteries = get_battery_path();
batteries
.iter()
.map(|el| {
fs::read_to_string(format!("{}/capacity", el.path().display()))
.unwrap_or(String::from("No battery"))
})
.collect()
}
fn get_battery_status() -> Vec<String> {
let batteries = get_battery_path();
batteries
.iter()
.map(|el| {
fs::read_to_string(format!("{}/status", el.path().display()))
.unwrap_or(String::from(""))
})
.collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment