Derive a lossless line/token view without creating CRDT rows or assigning unchanged bytes to the current editor. Binary or invalid UTF-8 data is rejected; callers must handle it as opaque content.
(&self)
| 1000 | /// assigning unchanged bytes to the current editor. Binary or invalid UTF-8 |
| 1001 | /// data is rejected; callers must handle it as opaque content. |
| 1002 | pub fn semantic_lines(&self) -> Result<Vec<SpanSemanticLine>> { |
| 1003 | use crate::diff::token::Tokenizer; |
| 1004 | std::str::from_utf8(&self.content).context("span semantic content is not UTF-8")?; |
| 1005 | ensure!( |
| 1006 | !self.content.contains(&0), |
| 1007 | "span semantic content is binary" |
| 1008 | ); |
| 1009 | // Validate the complete map once, then walk it monotonically as |
| 1010 | // tokens are emitted. Rescanning all spans per token is quadratic on |
| 1011 | // files with many independently authored fragments. |
| 1012 | let mut covered = 0usize; |
| 1013 | for span in &self.spans { |
| 1014 | ensure!( |
| 1015 | span.output.start == covered |
| 1016 | && span.output.end > covered |
| 1017 | && span.output.end <= self.content.len(), |
| 1018 | "authored spans do not uniquely cover semantic content" |
| 1019 | ); |
| 1020 | let length = u64::try_from(span.output.end - span.output.start)?; |
| 1021 | let target_len = span |
| 1022 | .target |
| 1023 | .end |
| 1024 | .checked_sub(span.target.start) |
| 1025 | .context("invalid authored span range")?; |
| 1026 | ensure!( |
| 1027 | span.target_start |
| 1028 | .checked_add(length) |
| 1029 | .is_some_and(|end| end <= target_len), |
| 1030 | "visible bytes exceed the authored span" |
| 1031 | ); |
| 1032 | covered = span.output.end; |
| 1033 | } |
| 1034 | ensure!( |
| 1035 | covered == self.content.len(), |
| 1036 | "authored spans do not cover semantic content" |
| 1037 | ); |
| 1038 | let mut result = Vec::new(); |
| 1039 | let mut line_start = 0usize; |
| 1040 | let mut span_index = 0usize; |
| 1041 | for line in crate::diff::Line::from_bytes(&self.content) { |
| 1042 | let bytes = line.content(); |
| 1043 | let line_end = line_start |
| 1044 | .checked_add(bytes.len()) |
| 1045 | .context("semantic line offset overflow")?; |
| 1046 | ensure!( |
| 1047 | self.content.get(line_start..line_end) == Some(bytes), |
| 1048 | "semantic lines do not cover the span content" |
| 1049 | ); |
| 1050 | let mut token_end = 0usize; |
| 1051 | let mut tokens = Vec::new(); |
| 1052 | let mut line_authors = Vec::new(); |
| 1053 | for token in Tokenizer::new(bytes) { |
| 1054 | ensure!( |
| 1055 | token.offset() == token_end, |
| 1056 | "semantic tokens do not uniquely cover the line" |
| 1057 | ); |
| 1058 | token_end = token_end |
| 1059 | .checked_add(token.content().len()) |