Skip to content

Instantly share code, notes, and snippets.

@dist1ll
Created May 15, 2023 20:27
Show Gist options
  • Save dist1ll/4aeb98c045ab5c31edfc911a02f7a47d to your computer and use it in GitHub Desktop.
Save dist1ll/4aeb98c045ab5c31edfc911a02f7a47d to your computer and use it in GitHub Desktop.
ASCII Counter
use std::{
fs::{read_dir, DirEntry},
path::Path,
};
const DIRECTORY: &'static str = "<ENTER YOUR TARGET PATH>";
const FILE_EXT: &'static str = ".rs";
fn main() {
let mut source_files = vec![];
let mut dir_stack: Vec<DirEntry> = read_dir(Path::new(DIRECTORY))
.unwrap()
.into_iter()
.map(Result::unwrap)
.filter(|d| d.metadata().unwrap().is_dir())
.collect();
while let Some(d) = dir_stack.pop() {
for f in std::fs::read_dir(d.path()).unwrap().map(Result::unwrap) {
let metadata = f.metadata().unwrap();
if metadata.is_dir() {
dir_stack.push(f);
} else if metadata.is_file() && f.path().to_str().unwrap().ends_with(FILE_EXT) {
source_files.push(f);
}
}
}
let result = source_files
.iter()
.map(|s| check_ascii_ratio(s))
.reduce(|lhs, rhs| (lhs.0 + rhs.0, lhs.1 + rhs.1, lhs.2 + rhs.2))
.unwrap();
println!(
"Total: {}\nASCII: {}\nRatio: {}\nLoC: {}",
result.0,
result.1,
(result.1 as f64) / (result.0 as f64),
result.2
)
}
/// Returns a tuple of (total chars, ascii chars)
fn check_ascii_ratio(f: &DirEntry) -> (usize, usize, usize) {
let mut result = (0, 0, 0);
let buf = std::fs::read_to_string(f.path()).unwrap();
for c in buf.chars() {
if c == '\n' {
result.2 += 1;
}
if c.is_ascii() {
result.1 += 1;
}
result.0 += 1;
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment