To find the next occurrence of {{ or {% in a UTF-8 string and return the byte index (not character index) without manually iterating through the string, you can use Rust's built-in string search methods. Here's the most efficient way:
Solution (Byte Index Search)
fn find_next_delimiter(s: &str, start_byte: usize) -> Option<usize> {
let remaining = &s[start_byte..];
// Find both patterns and take the earliest match
let pos1 = remaining.find("{{");
let pos2 = remaining.find("{%");
match (pos1, pos2) {
(Some(p1), Some(p2)) => Some(start_byte + p1.min(p2)),
(Some(p), None) | (None, Some(p)) => Some(start_byte + p),
(None, None) => None,
}
}
Explanation:
s[start_byte..] slices the string from the given byte index.
find("{{") and find("{%") return the byte offset of the first occurrence of each pattern.
p1.min(p2) picks the earlier match.
start_byte + pos converts the relative offset to an absolute byte index.
Example Usage:
fn main() {
let text = "Hello 世界 {{name}}, your score is {%score%}";
let pos = find_next_delimiter(text, 0); // Returns Some(12) (byte index of "{{")
println!("Found at byte index: {:?}", pos);
}
Why This Works:
- Handles UTF-8 correctly:
find() works on bytes, so it correctly skips multi-byte Unicode characters.
- Efficient: Uses built-in string search, which is optimized in Rust.
- Returns byte index: Useful for low-level string manipulation (e.g., parsing, tokenization).
If You Need Character Index Instead:
fn find_next_delimiter_char_index(s: &str, start_char: usize) -> Option<usize> {
// Convert char index to byte index
let start_byte = s.char_indices()
.nth(start_char)
.map(|(idx, _)| idx)
.unwrap_or(s.len());
// Find the next delimiter in bytes
let remaining = &s[start_byte..];
let pos1 = remaining.find("{{");
let pos2 = remaining.find("{%");
let byte_offset = match (pos1, pos2) {
(Some(p1), Some(p2)) => Some(p1.min(p2)),
(Some(p), None) | (None, Some(p)) => Some(p),
(None, None) => None,
}?;
// Convert back to char index
Some(s[..start_byte + byte_offset].chars().count())
}
This approach ensures correct handling of UTF-8 while efficiently finding the next delimiter. 🚀