1use serde::Serialize;
8
9pub struct LineIndex {
11 line_starts: Vec<u32>,
14}
15
16impl LineIndex {
17 pub fn new(source: &str) -> Self {
19 let mut starts = vec![0u32];
20 for (i, ch) in source.char_indices() {
21 if ch == '\n' {
22 starts.push((i + 1) as u32);
23 }
24 }
25 Self {
26 line_starts: starts,
27 }
28 }
29
30 pub fn offset_to_line_col(&self, offset: u32) -> (u32, u32) {
32 let line_0 = match self.line_starts.binary_search(&offset) {
33 Ok(exact) => exact,
34 Err(insert) => insert.saturating_sub(1),
35 };
36 let col_0 = offset.saturating_sub(self.line_starts[line_0]);
37 (line_0 as u32 + 1, col_0 + 1)
38 }
39}
40
41#[derive(Debug, Clone, Serialize)]
43pub struct SourceMapping {
44 pub zig_line: u32,
46 pub js_file: String,
48 pub js_line: u32,
50 pub js_col: u32,
52 pub kind: String,
54}
55
56#[derive(Debug, Clone, Serialize)]
58pub struct SourceMap {
59 pub source_file: String,
61 pub mappings: Vec<SourceMapping>,
63}
64
65impl SourceMap {
66 pub fn new(source_file: &str) -> Self {
67 Self {
68 source_file: source_file.to_string(),
69 mappings: Vec::new(),
70 }
71 }
72
73 pub fn add(&mut self, zig_line: u32, js_line: u32, js_col: u32, kind: &str) {
75 self.mappings.push(SourceMapping {
76 zig_line,
77 js_file: self.source_file.clone(),
78 js_line,
79 js_col,
80 kind: kind.to_string(),
81 });
82 }
83
84 pub fn to_json(&self) -> String {
86 serde_json::to_string_pretty(self).unwrap_or_default()
87 }
88}
89
90pub fn count_lines(s: &str) -> u32 {
93 s.bytes().filter(|&b| b == b'\n').count() as u32 + 1
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 fn test_line_index_single_line() {
102 let idx = LineIndex::new("hello world");
103 assert_eq!(idx.offset_to_line_col(0), (1, 1));
104 assert_eq!(idx.offset_to_line_col(5), (1, 6));
105 }
106
107 #[test]
108 fn test_line_index_multi_line() {
109 let idx = LineIndex::new("abc\ndef\nghi");
110 assert_eq!(idx.offset_to_line_col(0), (1, 1)); assert_eq!(idx.offset_to_line_col(4), (2, 1)); assert_eq!(idx.offset_to_line_col(8), (3, 1)); assert_eq!(idx.offset_to_line_col(10), (3, 3)); }
115
116 #[test]
117 fn test_count_lines() {
118 assert_eq!(count_lines(""), 1);
119 assert_eq!(count_lines("a"), 1);
120 assert_eq!(count_lines("a\nb"), 2);
121 assert_eq!(count_lines("a\nb\nc\n"), 4);
122 }
123
124 #[test]
125 fn test_source_map_json() {
126 let mut sm = SourceMap::new("test.js");
127 sm.add(1, 1, 1, "function add");
128 let json = sm.to_json();
129 assert!(json.contains("function add"));
130 assert!(json.contains("test.js"));
131 }
132}