slovo/benchmarks/json-quote-loop/rust/json_quote_loop.rs

63 lines
1.5 KiB
Rust

use std::io::Read;
const LOOP_COUNT: i32 = 1_000_000;
const EXPECTED_CHECKSUM: i32 = 15_000_001;
fn configured_loop_count() -> i32 {
let mut input = String::new();
if std::io::stdin().read_to_string(&mut input).is_err() {
return LOOP_COUNT;
}
input
.trim()
.parse::<i32>()
.ok()
.filter(|value| *value > 0)
.unwrap_or(LOOP_COUNT)
}
fn configured_target() -> String {
std::env::args()
.nth(1)
.unwrap_or_else(|| "slo\"vo\\path".to_string())
}
fn quote_json_string(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
'\u{08}' => out.push_str("\\b"),
'\u{0c}' => out.push_str("\\f"),
_ => out.push(ch),
}
}
out.push('"');
out
}
fn json_quote_loop(limit: i32, target: &str) -> i32 {
let mut i = 0;
let mut acc = 1;
while i < limit {
acc += quote_json_string(target).len() as i32;
i += 1;
}
acc
}
fn main() {
let target = configured_target();
let result = json_quote_loop(configured_loop_count(), &target);
println!("{}", result);
std::process::exit(if result == EXPECTED_CHECKSUM { 0 } else { 1 });
}