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 { line_starts: starts }
26 }
27
28 pub fn offset_to_line_col(&self, offset: u32) -> (u32, u32) {
30 let line_0 = match self.line_starts.binary_search(&offset) {
31 Ok(exact) => exact,
32 Err(insert) => insert.saturating_sub(1),
33 };
34 let col_0 = offset.saturating_sub(self.line_starts[line_0]);
35 (line_0 as u32 + 1, col_0 + 1)
36 }
37}
38
39#[derive(Debug, Clone, Serialize)]
41pub struct SourceMapping {
42 pub zig_line: u32,
44 pub js_file: String,
46 pub js_line: u32,
48 pub js_col: u32,
50 pub kind: String,
52}
53
54#[derive(Debug, Clone, Serialize)]
56pub struct SourceMap {
57 pub source_file: String,
59 pub mappings: Vec<SourceMapping>,
61}
62
63impl SourceMap {
64 pub fn new(source_file: &str) -> Self {
65 Self {
66 source_file: source_file.to_string(),
67 mappings: Vec::new(),
68 }
69 }
70
71 pub fn add(
73 &mut self,
74 zig_line: u32,
75 js_line: u32,
76 js_col: u32,
77 kind: &str,
78 ) {
79 self.mappings.push(SourceMapping {
80 zig_line,
81 js_file: self.source_file.clone(),
82 js_line,
83 js_col,
84 kind: kind.to_string(),
85 });
86 }
87
88 pub fn to_json(&self) -> String {
90 serde_json::to_string_pretty(self).unwrap_or_default()
91 }
92}
93
94pub fn count_lines(s: &str) -> u32 {
97 s.bytes().filter(|&b| b == b'\n').count() as u32 + 1
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[test]
105 fn test_line_index_single_line() {
106 let idx = LineIndex::new("hello world");
107 assert_eq!(idx.offset_to_line_col(0), (1, 1));
108 assert_eq!(idx.offset_to_line_col(5), (1, 6));
109 }
110
111 #[test]
112 fn test_line_index_multi_line() {
113 let idx = LineIndex::new("abc\ndef\nghi");
114 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)); }
119
120 #[test]
121 fn test_count_lines() {
122 assert_eq!(count_lines(""), 1);
123 assert_eq!(count_lines("a"), 1);
124 assert_eq!(count_lines("a\nb"), 2);
125 assert_eq!(count_lines("a\nb\nc\n"), 4);
126 }
127
128 #[test]
129 fn test_source_map_json() {
130 let mut sm = SourceMap::new("test.js");
131 sm.add(1, 1, 1, "function add");
132 let json = sm.to_json();
133 assert!(json.contains("function add"));
134 assert!(json.contains("test.js"));
135 }
136}