You're right! Here are UTF-8 safe approaches that work with character indices rather than byte indices:
Using char_indices() for proper UTF-8 handling
fn find_next_delimiter(s: &str, start_char: usize) -> Option<usize> {
let mut chars = s.char_indices().skip(start_char).peekable();
while let Some((idx, ch)) = chars.next() {
if ch == '{' {
if let Some((_, next_ch)) = chars.peek() {
if *next_ch == '{' || *next_ch == '%' {
return Some(idx);
}
}
}
}
None
}
// Usage
let text = "Hello 世界 {{name}}, your score is {%score%}";
let pos = find_next_delimiter(text, 0); // Returns character index, not byte index
Using match_indices() for a cleaner approach
fn find_next_delimiter(s: &str, start_char: usize) -> Option<usize> {
// Convert character index to byte index
let start_byte = s.char_indices()
.nth(start_char)
.map(|(idx, _)| idx)
.unwrap_or(s.len());
let remaining = &s[start_byte..];
// Find both patterns
let pos1 = remaining.match_indices("{{").next();
let pos2 = remaining.match_indices("{%").next();
// Get the earliest match
match (pos1, pos2) {
(Some((p1, _)), Some((p2, _))) => {
let byte_pos = start_byte + p1.min(p2);
// Convert back to char index
Some(s[..byte_pos].chars().count())
}
(Some((p, _)), None) | (None, Some((p, _))) => {
let byte_pos = start_byte + p;
Some(s[..byte_pos].chars().count())
}
(None, None) => None,
}
}
Complete example with all occurrences
fn find_all_delimiters(s: &str) -> Vec<(usize, &str)> {
let mut results = Vec::new();
let mut chars = s.char_indices().peekable();
while let Some((char_idx, ch)) = chars.next() {
if ch == '{' {
if let Some((_, next_ch)) = chars.peek() {
match next_ch {
'{' => {
results.push((char_idx, "{{"));
chars.next(); // Skip the second '{'
}
'%' => {
results.push((char_idx, "{%"));
chars.next(); // Skip the '%'
}
_ => {}
}
}
}
}
results
}
// Usage with UTF-8
let text = "Start 你好 {{var1}} middle 世界 {%block%} end";
let delimiters = find_all_delimiters(text);
// Returns character indices, not byte indices
Helper struct for easier use
struct DelimiterFinder<'a> {
text: &'a str,
char_pos: usize,
}
impl<'a> DelimiterFinder<'a> {
fn new(text: &'a str) -> Self {
Self { text, char_pos: 0 }
}
fn find_next(&mut self) -> Option<(usize, &'static str)> {
let mut chars = self.text.char_indices().skip(self.char_pos).peekable();
while let Some((idx, ch)) = chars.next() {
if ch == '{' {
if let Some((_, next_ch)) = chars.peek() {
let delimiter = match next_ch {
'{' => "{{",
'%' => "{%",
_ => continue,
};
self.char_pos = self.text[..idx].chars().count() + 2;
return Some((self.text[..idx].chars().count(), delimiter));
}
}
}
None
}
}
// Usage
let text = "Hello 世界 {{name}} and {%data%}";
let mut finder = DelimiterFinder::new(text);
while let Some((pos, delim)) = finder.find_next() {
println!("Found {} at character position {}", delim, pos);
}