@@ -11,6 +11,7 @@ use std::{fmt, ops, iter};
11
11
pub struct TextUnit ( u32 ) ;
12
12
13
13
impl TextUnit {
14
+ //TODO: rename to `from_char`: this is not ocaml!
14
15
/// `TextUnit` equal to the length of this char.
15
16
#[ inline( always) ]
16
17
pub fn of_char ( c : char ) -> TextUnit {
@@ -33,6 +34,21 @@ impl TextUnit {
33
34
pub fn checked_sub ( self , other : TextUnit ) -> Option < TextUnit > {
34
35
self . 0 . checked_sub ( other. 0 ) . map ( TextUnit )
35
36
}
37
+
38
+ #[ inline( always) ]
39
+ pub fn from_usize ( size : usize ) -> TextUnit {
40
+ #[ cfg( debug_assertions) ] {
41
+ if size > u32:: max_value ( ) as usize {
42
+ panic ! ( "overflow when converting to TextUnit: {}" , size)
43
+ }
44
+ }
45
+ ( size as u32 ) . into ( )
46
+ }
47
+
48
+ #[ inline( always) ]
49
+ pub fn to_usize ( self ) -> usize {
50
+ u32:: from ( self ) as usize
51
+ }
36
52
}
37
53
38
54
impl fmt:: Debug for TextUnit {
@@ -244,6 +260,7 @@ impl TextRange {
244
260
TextRange :: from_to ( offset, offset + len)
245
261
}
246
262
263
+ // TODO: pass by value
247
264
/// The inclusive start of this range
248
265
#[ inline( always) ]
249
266
pub fn start ( & self ) -> TextUnit {
@@ -267,6 +284,12 @@ impl TextRange {
267
284
pub fn is_empty ( & self ) -> bool {
268
285
self . start ( ) == self . end ( )
269
286
}
287
+
288
+ #[ inline( always) ]
289
+ pub fn is_subrange ( & self , other : & TextRange ) -> bool {
290
+ other. start ( ) <= self . start ( )
291
+ && self . end ( ) <= other. end ( )
292
+ }
270
293
}
271
294
272
295
impl ops:: Index < TextRange > for str {
@@ -352,4 +375,13 @@ mod tests {
352
375
assert_eq ! ( r. checked_sub( 1 . into( ) ) , Some ( TextRange :: from_to( 0 . into( ) , 1 . into( ) ) ) ) ;
353
376
assert_eq ! ( x. checked_sub( 2 . into( ) ) , None ) ;
354
377
}
378
+
379
+ #[ test]
380
+ fn test_subrange ( ) {
381
+ let r1 = TextRange :: from_to ( 2 . into ( ) , 4 . into ( ) ) ;
382
+ let r2 = TextRange :: from_to ( 2 . into ( ) , 3 . into ( ) ) ;
383
+ let r3 = TextRange :: from_to ( 1 . into ( ) , 3 . into ( ) ) ;
384
+ assert ! ( r2. is_subrange( & r1) ) ;
385
+ assert ! ( !r3. is_subrange( & r1) ) ;
386
+ }
355
387
}
0 commit comments