use std::path::Path;
use crate::error::{Error, Result};
use crate::util::Bytes;
use crate::util::parse;
#[derive(Debug)]
pub struct NetDevStat {
pub name: Box<str>,
pub rx_bytes: Bytes,
pub rx_packets: u64,
pub rx_errors: u64,
pub rx_drop: u64,
pub rx_fifo_errors: u64,
pub rx_frame_errors: u64,
pub rx_compressed: u64,
pub rx_multicast: u64,
pub tx_bytes: Bytes,
pub tx_packets: u64,
pub tx_errors: u64,
pub tx_drop: u64,
pub tx_fifo_errors: u64,
pub tx_collisions: u64,
pub tx_carrier_errors: u64,
pub tx_compressed: u64,
}
pub fn dev() -> impl Iterator<Item = Result<NetDevStat>> {
let path = Path::new("/proc/net/dev");
let bytes = match parse::read_file(path) {
Ok(b) => b,
Err(e) => return vec![Err(e)].into_iter(),
};
let mut entries = Vec::new();
for line in bytes
.split(|&b| b == b'\n')
.filter(|l| !l.is_empty())
.skip(2)
{
let colon = match parse::memchr(b':', line) {
Some(idx) => idx,
None => {
entries.push(Err(Error::Parse {
path: path.to_path_buf(),
line: 0,
msg: "missing colon in device line",
}));
continue;
}
};
let name = parse::trim_end(&line[..colon]);
let name_str = std::str::from_utf8(name)
.unwrap_or("")
.trim()
.to_string()
.into_boxed_str();
let counters = parse::trim_start(&line[colon + 1..]);
let fields = parse::SplitFields::<16>::new(counters);
if fields.len() < 16 {
entries.push(Err(Error::Parse {
path: path.to_path_buf(),
line: 0,
msg: "expected 16 counter fields",
}));
continue;
}
let get = |i: usize| parse::parse_dec_u64_fast(fields[i]).unwrap_or(0);
entries.push(Ok(NetDevStat {
name: name_str,
rx_bytes: Bytes(get(0)),
rx_packets: get(1),
rx_errors: get(2),
rx_drop: get(3),
rx_fifo_errors: get(4),
rx_frame_errors: get(5),
rx_compressed: get(6),
rx_multicast: get(7),
tx_bytes: Bytes(get(8)),
tx_packets: get(9),
tx_errors: get(10),
tx_drop: get(11),
tx_fifo_errors: get(12),
tx_collisions: get(13),
tx_carrier_errors: get(14),
tx_compressed: get(15),
}));
}
entries.into_iter()
}