@@ -219,18 +219,15 @@ impl FileObj {
219
219
}
220
220
}
221
221
222
- /// Gets the line and column number from a given `offset` (of bytes) for given
223
- /// `file_path `.
222
+ /// Gets the line number for a given `offset` (of bytes) from the given
223
+ /// buffer `contents `.
224
224
///
225
- /// This computes the line and column numbers from a buffer of bytes read from the
226
- /// `file_path`. In non-UTF-8 encoded files, this does not guarantee that a word
227
- /// boundary exists at the returned column number. However, the `offset` given to this
228
- /// function is expected to originate from diagnostic information provided by
229
- /// clang-format or clang-tidy.
225
+ /// The `offset` given to this function is expected to originate from
226
+ /// diagnostic information provided by clang-format. Any `offset` out of
227
+ /// bounds is clamped to the given `contents` buffer's length.
230
228
pub fn get_line_count_from_offset ( contents : & [ u8 ] , offset : u32 ) -> u32 {
231
229
let offset = ( offset as usize ) . min ( contents. len ( ) ) ;
232
230
let lines = contents[ 0 ..offset] . split ( |byte| byte == & b'\n' ) ;
233
-
234
231
lines. count ( ) as u32
235
232
}
236
233
@@ -316,6 +313,20 @@ mod test {
316
313
assert_eq ! ( lines, 13 ) ;
317
314
}
318
315
316
+ #[ test]
317
+ fn get_line_count_edge_cases ( ) {
318
+ // Empty content
319
+ assert_eq ! ( get_line_count_from_offset( & [ ] , 0 ) , 1 ) ;
320
+
321
+ // No newlines
322
+ assert_eq ! ( get_line_count_from_offset( b"abc" , 3 ) , 1 ) ;
323
+
324
+ // Consecutive newlines
325
+ assert_eq ! ( get_line_count_from_offset( b"a\n \n b" , 3 ) , 3 ) ;
326
+
327
+ // Offset beyond content length
328
+ assert_eq ! ( get_line_count_from_offset( b"a\n b\n " , 10 ) , 3 ) ;
329
+ }
319
330
// *********************** tests for FileObj::get_ranges()
320
331
321
332
#[ test]
0 commit comments