gemini_adk_rs/utils/
text.rs1use serde_json::Value;
5
6pub fn strip_code_fence(text: &str) -> &str {
21 let trimmed = text.trim();
22 let Some(rest) = trimmed.strip_prefix("```") else {
23 return trimmed;
24 };
25 let body = match rest.split_once('\n') {
26 Some((tag, body)) if is_fence_tag(tag) => body,
28 _ => strip_json_tag(rest),
30 };
31 let body = body.trim_end();
32 body.strip_suffix("```").unwrap_or(body).trim()
33}
34
35fn is_fence_tag(tag: &str) -> bool {
37 tag.trim()
38 .chars()
39 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '+' | '.' | '#'))
40}
41
42fn strip_json_tag(rest: &str) -> &str {
44 match rest.get(..4) {
45 Some(tag)
46 if tag.eq_ignore_ascii_case("json")
47 && !rest[4..].starts_with(|c: char| c.is_ascii_alphanumeric()) =>
48 {
49 &rest[4..]
50 }
51 _ => rest,
52 }
53}
54
55pub fn truncate_chars(s: &str, max_chars: usize) -> &str {
66 match s.char_indices().nth(max_chars) {
67 Some((i, _)) => &s[..i],
68 None => s,
69 }
70}
71
72pub fn truncate_with_marker(s: &str, max_chars: usize, marker: &str) -> String {
82 let head = truncate_chars(s, max_chars);
83 if head.len() == s.len() {
84 s.to_string()
85 } else {
86 format!("{head}{marker}")
87 }
88}
89
90pub fn interpolate_with(template: &str, mut lookup: impl FnMut(&str) -> Option<Value>) -> String {
111 let mut out = String::with_capacity(template.len());
112 let mut rest = template;
113 while let Some(open) = rest.find('{') {
114 out.push_str(&rest[..open]);
115 let after = &rest[open + 1..];
116 let Some(close) = after.find('}') else {
117 out.push_str(&rest[open..]);
118 return out;
119 };
120 match lookup(after[..close].trim()) {
121 Some(Value::String(s)) => out.push_str(&s),
122 Some(v) => out.push_str(&v.to_string()),
123 None => {}
124 }
125 rest = &after[close + 1..];
126 }
127 out.push_str(rest);
128 out
129}
130
131pub fn levenshtein(a: &str, b: &str) -> usize {
141 strsim::levenshtein(a, b)
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147 use serde_json::json;
148
149 #[test]
150 fn fence_with_a_json_tag() {
151 assert_eq!(strip_code_fence("```json\n{\"a\": 1}\n```"), "{\"a\": 1}");
152 assert_eq!(strip_code_fence("```JSON\n{\"a\": 1}\n```"), "{\"a\": 1}");
153 assert_eq!(
154 strip_code_fence("```json\r\n{\"a\": 1}\r\n```"),
155 "{\"a\": 1}"
156 );
157 }
158
159 #[test]
160 fn bare_fence() {
161 assert_eq!(strip_code_fence("```\n{\"a\": 1}\n```"), "{\"a\": 1}");
162 assert_eq!(strip_code_fence("```\n[1, 2]\n```"), "[1, 2]");
163 }
164
165 #[test]
166 fn no_fence() {
167 assert_eq!(strip_code_fence("{\"a\": 1}"), "{\"a\": 1}");
168 assert_eq!(strip_code_fence("plain words"), "plain words");
169 assert_eq!(strip_code_fence(""), "");
170 }
171
172 #[test]
173 fn surrounding_whitespace() {
174 assert_eq!(strip_code_fence(" \n{\"a\": 1}\n "), "{\"a\": 1}");
175 assert_eq!(
176 strip_code_fence("\n\n ```json\n {\"a\": 1} \n``` \n\n"),
177 "{\"a\": 1}"
178 );
179 }
180
181 #[test]
182 fn single_line_and_unclosed_fences() {
183 assert_eq!(strip_code_fence("```{\"a\": 1}```"), "{\"a\": 1}");
184 assert_eq!(strip_code_fence("```json{\"a\": 1}```"), "{\"a\": 1}");
185 assert_eq!(strip_code_fence("```json {\"a\": 1}```"), "{\"a\": 1}");
186 assert_eq!(strip_code_fence("```json\n{\"a\": 1}"), "{\"a\": 1}");
187 assert_eq!(strip_code_fence("```jsonish```"), "jsonish");
189 assert_eq!(strip_code_fence("```{\n\"a\": 1\n}\n```"), "{\n\"a\": 1\n}");
191 }
192
193 #[test]
194 fn truncate_chars_cuts_on_a_character_boundary() {
195 let s = "é日本語です";
197 assert_eq!(truncate_chars(s, 2), "é日");
198 assert_eq!(truncate_chars(s, 0), "");
199 assert_eq!(truncate_chars(s, 6), s);
200 assert_eq!(truncate_chars(s, 100), s);
201 assert_eq!(truncate_chars("", 3), "");
202 }
203
204 #[test]
205 fn truncate_with_marker_marks_only_a_cut() {
206 let s = "日本語のテキスト";
207 assert_eq!(truncate_with_marker(s, 3, "..."), "日本語...");
208 assert_eq!(truncate_with_marker(s, 8, "..."), s);
209 assert_eq!(truncate_with_marker("abc", 2, "…"), "ab…");
210 }
211
212 #[test]
215 fn a_multibyte_string_that_byte_slicing_would_have_panicked_on() {
216 let s = "日".repeat(100); assert!(!s.is_char_boundary(77));
218 let cut = truncate_with_marker(&s, 77, "...");
219 assert_eq!(cut.chars().count(), 80);
220 assert!(cut.ends_with("日..."));
221 }
222
223 #[test]
224 fn interpolate_with_substitutes_strings_and_json() {
225 let out = interpolate_with("a {x} b {n} c {obj} d {gone}.", |k| match k {
226 "x" => Some(json!("X")),
227 "n" => Some(json!(7)),
228 "obj" => Some(json!({"k": 1})),
229 _ => None,
230 });
231 assert_eq!(out, "a X b 7 c {\"k\":1} d .");
232 }
233
234 #[test]
235 fn interpolate_with_trims_keys_and_keeps_an_unclosed_brace() {
236 let out = interpolate_with("{ k } and {oops", |k| {
237 assert_eq!(k, "k");
238 Some(json!("v"))
239 });
240 assert_eq!(out, "v and {oops");
241 assert_eq!(interpolate_with("no braces", |_| None), "no braces");
242 }
243
244 #[test]
245 fn levenshtein_counts_characters_not_bytes() {
246 assert_eq!(levenshtein("", ""), 0);
247 assert_eq!(levenshtein("abc", ""), 3);
248 assert_eq!(levenshtein("kitten", "sitting"), 3);
249 assert_eq!(levenshtein("héllo", "hello"), 1);
250 assert_eq!(levenshtein("日本語", "日本"), 1);
251 }
252}