Skip to main content
Be Bitwise
RustCapstone: CLI Network Tool

Output & Formatting

Results are useless if you can't read them. The tool offers two flavours: a column-aligned table for humans and JSON for everything else.

Plain Text Output

rust
pub fn format_plain(results: &[CheckResult]) -> String {
let mut output = String::new();
output.push_str(&format!(
"{:<40} {:>6} {:>10} {}\n",
"URL", "Status", "Time(ms)", "Error"
));
output.push_str(&"-".repeat(75));
output.push('\n');
for result in results {
let status = result
.status
.map(|s| s.to_string())
.unwrap_or_else(|| "---".to_string());
let error = result
.error
.as_deref()
.unwrap_or("");
output.push_str(&format!(
"{:<40} {:>6} {:>10} {}\n",
truncate(&result.url, 40),
status,
result.response_time_ms,
error,
));
}
output
}
fn truncate(s: &str, max_len: usize) -> String {
if s.chars().count() <= max_len {
s.to_string()
} else {
// Count chars, not bytes: slicing mid-character panics.
let head: String = s.chars().take(max_len - 3).collect();
format!("{}...", head)
}
}

JSON Output

rust
pub fn format_json(results: &[CheckResult]) -> String {
let mut entries = Vec::new();
for r in results {
let status = r.status
.map(|s| format!("{}", s))
.unwrap_or_else(|| "null".to_string());
let error = r.error
.as_ref()
.map(|e| format!("\"{}\"", json_escape(e)))
.unwrap_or_else(|| "null".to_string());
entries.push(format!(
" {{\"url\": \"{}\", \"status\": {}, \"time_ms\": {}, \"error\": {}}}",
json_escape(&r.url), status, r.response_time_ms, error
));
}
format!("[\n{}\n]", entries.join(",\n"))
}
fn json_escape(s: &str) -> String {
let mut out = String::new();
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out
}

Escaping only the double quote isn't enough. URLs and error messages are outside text, and a backslash just before a quote cancels the escape and closes the JSON string early. The runner compares a quote-only escape with json_escape.

Try itCompare the two url lines, then uncomment the byte slice at the bottom to see why truncate counts chars.
Rust (1.40.0)
Key Concept

Hand-rolling a JSON serialiser is the quickest way to internalise the format. Real codebases reach for serde and serde_json, which derive the whole thing from a struct. Knowing what the bytes look like still pays off when you're staring down a malformed payload at 2am.

Colored Terminal Output

A bit of ANSI colour goes a long way:

rust
fn status_color(status: Option<u16>) -> &'static str {
match status {
Some(200..=299) => "\x1b[32m", // green
Some(300..=399) => "\x1b[33m", // yellow
Some(400..=599) => "\x1b[31m", // red
None => "\x1b[31m", // red (error)
_ => "\x1b[0m", // default
}
}
const RESET: &str = "\x1b[0m";
fn format_status(status: Option<u16>) -> String {
let color = status_color(status);
let text = status.map(|s| s.to_string()).unwrap_or("ERR".into());
format!("{}{}{}", color, text, RESET)
}

Summary Statistics

rust
pub fn format_summary(results: &[CheckResult]) -> String {
let total = results.len();
let successful = results.iter().filter(|r| r.error.is_none()).count();
let avg_time: u128 = if successful > 0 {
results.iter()
.filter(|r| r.error.is_none())
.map(|r| r.response_time_ms)
.sum::<u128>() / successful as u128
} else {
0
};
format!(
"\nChecked {} URLs: {} OK, {} failed, avg response time: {}ms",
total, successful, total - successful, avg_time
)
}

Putting the Output Module Together

rust
pub fn print_results(results: &[CheckResult], format: &OutputFormat) {
match format {
OutputFormat::Plain => {
print!("{}", format_plain(results));
print!("{}", format_summary(results));
}
OutputFormat::Json => {
println!("{}", format_json(results));
}
}
}