tinycodinglm / polyglot /polyglot-0000.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame Contribute Delete
1.26 kB
opencode trace
System You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

User

How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the Rust version.

Assistant

In Rust, String::len() is bytes and chars().count() is Unicode scalar values — exactly the distinction you need. read_to_string enforces valid UTF-8.

rust
use std::fs;

fn main() -> std::io::Result<()> {
    let text = "Olá mundo! Ação, coração.\nSegunda linha: Straße, 你好.\n";
    fs::write("sample.txt", text)?;
    let data = fs::read_to_string("sample.txt")?;
    let bytes = data.len();
    let chars = data.chars().count();
    let words = data.split_whitespace().count();
    let lines = data.lines().count();
    println!("lines={lines} words={words} chars={chars} bytes={bytes}");
    assert_eq!((lines, words), (2, 8));
    assert!(bytes > chars); // multibyte content present
    Ok(())
}