1use std::fs;
2use std::path::Path;
3use thiserror::Error;
4
5use crate::models::Symbol;
6
7#[derive(Debug, Error)]
8pub enum SliceError {
9 #[error("Failed to read file '{0}': {1}")]
10 Io(String, #[source] std::io::Error),
11 #[error("Invalid slice range: start {0} > end {1}")]
12 InvalidRange(usize, usize),
13 #[error("File '{0}' is empty")]
14 EmptyFile(String),
15}
16
17fn snap_to_char_boundary_floor(bytes: &[u8], mut idx: usize) -> usize {
19 if idx >= bytes.len() {
20 return bytes.len();
21 }
22 while idx > 0 && (bytes[idx] & 0xC0) == 0x80 {
23 idx -= 1;
24 }
25 idx
26}
27
28fn snap_to_char_boundary_ceil(bytes: &[u8], mut idx: usize) -> usize {
30 if idx >= bytes.len() {
31 return bytes.len();
32 }
33 while idx < bytes.len() && (bytes[idx] & 0xC0) == 0x80 {
34 idx += 1;
35 }
36 idx
37}
38
39pub fn slice_bytes_safe(
41 content: &[u8],
42 start_byte: usize,
43 end_byte: usize,
44) -> Result<&str, SliceError> {
45 if start_byte > end_byte {
46 return Err(SliceError::InvalidRange(start_byte, end_byte));
47 }
48
49 let start = snap_to_char_boundary_floor(content, start_byte.min(content.len()));
50 let end = snap_to_char_boundary_ceil(content, end_byte.min(content.len()));
51
52 std::str::from_utf8(&content[start..end]).map_err(|_| SliceError::InvalidRange(start, end))
53}
54
55pub fn slice_symbol(file_path: &Path, symbol: &Symbol) -> Result<String, SliceError> {
57 let bytes =
58 fs::read(file_path).map_err(|e| SliceError::Io(file_path.display().to_string(), e))?;
59
60 if bytes.is_empty() {
61 return Err(SliceError::EmptyFile(file_path.display().to_string()));
62 }
63
64 if symbol.end_byte <= bytes.len()
66 && symbol.start_byte <= symbol.end_byte
67 && symbol.end_byte > 0
68 && let Ok(slice) = slice_bytes_safe(&bytes, symbol.start_byte, symbol.end_byte)
69 {
70 return Ok(slice.to_string());
71 }
72
73 slice_lines(&bytes, symbol.start_line, symbol.end_line)
75}
76
77pub fn slice_symbol_body(file_path: &Path, symbol: &Symbol) -> Result<String, SliceError> {
79 let bytes =
80 fs::read(file_path).map_err(|e| SliceError::Io(file_path.display().to_string(), e))?;
81
82 if bytes.is_empty() {
83 return Err(SliceError::EmptyFile(file_path.display().to_string()));
84 }
85
86 if let (Some(body_start), Some(body_end)) = (symbol.body_start_byte, symbol.body_end_byte)
88 && body_end <= bytes.len()
89 && body_start <= body_end
90 && let Ok(slice) = slice_bytes_safe(&bytes, body_start, body_end)
91 {
92 return Ok(slice.to_string());
93 }
94
95 if let (Some(b_start), Some(b_end)) = (symbol.body_start_line, symbol.body_end_line) {
97 return slice_lines(&bytes, b_start, b_end);
98 }
99
100 slice_symbol(file_path, symbol)
102}
103
104pub fn slice_lines(bytes: &[u8], start_line: usize, end_line: usize) -> Result<String, SliceError> {
106 if start_line > end_line {
107 return Err(SliceError::InvalidRange(start_line, end_line));
108 }
109
110 let text = String::from_utf8_lossy(bytes);
111 let mut selected = Vec::new();
112
113 for (idx, line) in text.lines().enumerate() {
114 let line_num = idx + 1;
115 if line_num >= start_line && line_num <= end_line {
116 selected.push(line);
117 }
118 if line_num > end_line {
119 break;
120 }
121 }
122
123 Ok(selected.join("\n"))
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn test_slice_bytes_safe() {
132 let sample = "fn hello() {\n println!(\"hi\");\n}\n";
133 let sliced = slice_bytes_safe(sample.as_bytes(), 0, sample.len()).unwrap();
134 assert_eq!(sliced, sample);
135 }
136
137 #[test]
138 fn test_slice_lines() {
139 let sample = "line 1\nline 2\nline 3\nline 4\n";
140 let sliced = slice_lines(sample.as_bytes(), 2, 3).unwrap();
141 assert_eq!(sliced, "line 2\nline 3");
142 }
143}