Skip to main content

vtcode_commons/
tokens.rs

1//! Token estimation utilities
2
3/// Estimate token count from string (rough approximation)
4///
5/// Simple estimation: 1 token ≈ 4 characters.
6/// Returns a minimum of 1 for non-empty strings.
7#[inline]
8pub fn estimate_tokens(text: &str) -> usize {
9    if text.is_empty() {
10        return 0;
11    }
12    // Simple estimation: 1 token ≈ 4 characters.
13    // Use ceiling division: (len + 3) / 4
14    (text.len() + 3) / 4
15}
16
17/// Truncate string to approximate token limit
18///
19/// Returns a truncated string that fits within the approximate token limit.
20/// Tries to truncate at word boundaries when possible to avoid mid-word cuts.
21pub fn truncate_to_tokens(text: &str, max_tokens: usize) -> String {
22    if max_tokens == 0 || text.is_empty() {
23        return String::new();
24    }
25
26    let max_chars = max_tokens * 4;
27    if text.len() <= max_chars {
28        return text.to_string();
29    }
30
31    // Ensure we don't slice in the middle of a character
32    let mut end = max_chars;
33    while !text.is_char_boundary(end) {
34        end -= 1;
35    }
36    let truncated = &text[..end];
37
38    // Try to truncate at a word boundary
39    match truncated.rfind(' ') {
40        Some(last_space) if last_space > end / 2 => {
41            let mut result = truncated[..last_space].to_string();
42            result.push_str("...");
43            result
44        }
45        _ => {
46            let mut result = truncated.to_string();
47            result.push_str("...");
48            result
49        }
50    }
51}