22// use std::sync::Arc;
33
44use napi_derive:: napi;
5+ use oxc_data_structures:: rope:: { get_line_column, Rope } ;
56
67// use oxc_sourcemap::napi::SourceMap;
78use self_cell:: self_cell;
@@ -10,6 +11,7 @@ use string_wizard::MagicString as MS;
1011#[ napi]
1112pub struct MagicString {
1213 cell : MagicStringImpl ,
14+ rope : Option < Rope > ,
1315}
1416
1517self_cell ! (
@@ -22,10 +24,19 @@ self_cell!(
2224
2325impl MagicString {
2426 pub fn new ( source_text : String ) -> Self {
25- Self { cell : MagicStringImpl :: new ( source_text, |s| string_wizard:: MagicString :: new ( s) ) }
27+ Self {
28+ cell : MagicStringImpl :: new ( source_text, |s| string_wizard:: MagicString :: new ( s) ) ,
29+ rope : None ,
30+ }
2631 }
2732}
2833
34+ #[ napi( object) ]
35+ pub struct LineColumn {
36+ pub line : u32 ,
37+ pub column : u32 ,
38+ }
39+
2940#[ napi( object) ]
3041pub struct OverwriteOptions {
3142 pub content_only : bool ,
@@ -40,11 +51,21 @@ pub struct SourceMapOptions {
4051
4152#[ napi]
4253impl MagicString {
54+ /// Get source text from utf8 offset.
4355 #[ napi]
4456 pub fn get_source_text ( & self , start : u32 , end : u32 ) -> & str {
4557 & self . cell . borrow_owner ( ) [ start as usize ..end as usize ]
4658 }
4759
60+ /// Get 0-based line and column number from utf8 offset.
61+ #[ napi]
62+ pub fn get_line_column_number ( & mut self , offset : u32 ) -> LineColumn {
63+ let source_text = self . cell . borrow_owner ( ) ;
64+ let rope = self . rope . get_or_insert_with ( || Rope :: from_str ( source_text) ) ;
65+ let ( line, column) = get_line_column ( rope, offset, source_text) ;
66+ LineColumn { line, column }
67+ }
68+
4869 #[ napi]
4970 pub fn length ( & self ) -> u32 {
5071 self . cell . borrow_dependent ( ) . len ( ) as u32
0 commit comments