1use crate::{ContextError, Document};
4
5impl Document {
6 pub fn chunks_at_lines(&self, starts: &[usize]) -> Result<Vec<Self>, ContextError> {
18 if self.text.len() > 16_777_216 || starts.len() >= 4096 {
19 return Err(ContextError::LimitExceeded);
20 }
21 if self.id.len() > 100
22 || !crate::graph::valid_id(&self.id)
23 || self.start_line == 0
24 || self.source.is_empty()
25 || self.source.len() > 2048
26 || self.source.chars().any(char::is_control)
27 || self.text.trim().is_empty()
28 || starts.first().is_some_and(|line| *line <= self.start_line)
29 || starts.windows(2).any(|pair| pair.first() >= pair.get(1))
30 {
31 return Err(ContextError::InvalidInput);
32 }
33 let mut offsets = Vec::with_capacity(starts.len() + 1);
34 offsets.push((self.start_line, 0_usize));
35 let mut line = self.start_line;
36 let mut offset = 0;
37 let mut next = 0;
38 for text in self.text.split_inclusive('\n') {
39 if starts.get(next) == Some(&line) {
40 offsets.push((line, offset));
41 next += 1;
42 }
43 offset += text.len();
44 if offset < self.text.len() {
45 line = line.checked_add(1).ok_or(ContextError::LimitExceeded)?;
46 }
47 }
48 if next != starts.len() {
49 return Err(ContextError::InvalidInput);
50 }
51 let mut chunks = Vec::with_capacity(offsets.len());
52 for (index, (start_line, start)) in offsets.iter().copied().enumerate() {
53 let end = offsets
54 .get(index + 1)
55 .map_or(self.text.len(), |(_, offset)| *offset);
56 let text = self.text.get(start..end).ok_or(ContextError::Integrity)?;
57 if text.trim().is_empty() {
58 return Err(ContextError::InvalidInput);
59 }
60 chunks.push(Self {
61 id: format!("{}:L{start_line}", self.id),
62 source: self.source.clone(),
63 start_line,
64 text: text.to_owned(),
65 });
66 }
67 Ok(chunks)
68 }
69}