1pub fn extract_code_block(input: &str) -> Option<String> {
16 let start = input.find("```")?;
17 let after_start = &input[start + 3..];
18
19 let content_start = after_start.find('\n').map_or(0, |pos| pos + 1);
21 let rest = &after_start[content_start..];
22
23 let end = rest.find("```")?;
24 Some(rest[..end].to_string())
25}
26
27pub fn extract_code_block_or_original(input: &str) -> String {
42 extract_code_block(input).unwrap_or_else(|| input.to_string())
43}
44
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn extracts_simple_code_block() {
52 let input = "```\nhello\n```";
53 let result = extract_code_block(input);
54 assert_eq!(result, Some("hello\n".to_string()));
55 }
56
57 #[test]
58 fn extracts_code_block_with_language() {
59 let input = "```rust\nlet x = 42;\n```";
60 let result = extract_code_block(input);
61 assert_eq!(result, Some("let x = 42;\n".to_string()));
62 }
63
64 #[test]
65 fn extracts_first_code_block_only() {
66 let input = "```\nfirst\n```\n```\nsecond\n```";
67 let result = extract_code_block(input);
68 assert_eq!(result, Some("first\n".to_string()));
69 }
70
71 #[test]
72 fn returns_none_when_no_code_block() {
73 let input = "no code block here";
74 let result = extract_code_block(input);
75 assert_eq!(result, None);
76 }
77
78 #[test]
79 fn returns_original_when_no_code_block() {
80 let input = "no code block here";
81 let result = extract_code_block_or_original(input);
82 assert_eq!(result, input.to_string());
83 }
84
85 #[test]
86 fn returns_extracted_code_when_present() {
87 let input = "text before\n```\ncode\n```\ntext after";
88 let result = extract_code_block_or_original(input);
89 assert_eq!(result, "code\n".to_string());
90 }
91
92 #[test]
93 fn handles_unclosed_code_block() {
94 let input = "```\nunclosed";
95 let result = extract_code_block(input);
96 assert_eq!(result, None);
97 }
98}