pub const CHARS_PER_TOKEN: f64 = 4.0;
pub fn estimate_tokens(text: &str) -> u64 {
if text.is_empty() {
return 0;
}
let chars = text.chars().count() as f64;
(chars / CHARS_PER_TOKEN).ceil().max(1.0) as u64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_is_zero() {
assert_eq!(estimate_tokens(""), 0);
}
#[test]
fn rough_quarter_of_chars() {
assert_eq!(estimate_tokens("abcd"), 1);
assert_eq!(estimate_tokens(&"x".repeat(400)), 100);
assert_eq!(estimate_tokens("a"), 1);
}
#[test]
fn counts_chars_not_bytes() {
assert_eq!(estimate_tokens("日本語訳"), 1);
}
}