Debian Codegraph @

debian/missing-sources/nom_locate/src/tests.rs

raw
1 mod lib {
2 #[cfg(feature = "std")]
3 pub mod std {
4 pub use std::string::ToString;
5 pub use std::vec::Vec;
6 }
7 #[cfg(all(not(feature = "std"), feature = "alloc"))]
8 pub mod std {
9 pub use alloc::string::ToString;
10 pub use alloc::vec::Vec;
11 }
12 }
13
14 #[cfg(feature = "alloc")]
15 use lib::std::*;
16
17 use super::LocatedSpan;
18 #[cfg(feature = "alloc")]
19 use nom::ParseTo;
20 use nom::{error::ErrorKind, Compare, CompareResult, FindSubstring, FindToken, Input, Offset};
21
22 type StrSpan<'a> = LocatedSpan<&'a str>;
23 type BytesSpan<'a> = LocatedSpan<&'a [u8]>;
24 type StrSpanEx<'a, 'b> = LocatedSpan<&'a str, &'b str>;
25 type BytesSpanEx<'a, 'b> = LocatedSpan<&'a [u8], &'b str>;
26
27 #[test]
28 fn new_sould_be_the_same_as_new_extra() {
29 let byteinput = &b"foobar"[..];
30 assert_eq!(
31 BytesSpan::new(byteinput),
32 LocatedSpan::new_extra(byteinput, ())
33 );
34 let strinput = "foobar";
35 assert_eq!(StrSpan::new(strinput), LocatedSpan::new_extra(strinput, ()));
36 }
37
38 #[test]
39 fn it_should_call_new_for_u8_successfully() {
40 let input = &b"foobar"[..];
41 let output = BytesSpan {
42 offset: 0,
43 line: 1,
44 fragment: input,
45 extra: (),
46 };
47
48 assert_eq!(BytesSpan::new(input), output);
49 }
50
51 #[test]
52 fn it_should_convert_from_u8_successfully() {
53 let input = &b"foobar"[..];
54 assert_eq!(BytesSpan::new(input), input.into());
55 assert_eq!(BytesSpanEx::new_extra(input, "extra"), input.into());
56 }
57
58 #[test]
59 fn it_should_call_new_for_str_successfully() {
60 let input = &"foobar"[..];
61 let output = StrSpan {
62 offset: 0,
63 line: 1,
64 fragment: input,
65 extra: (),
66 };
67
68 assert_eq!(StrSpan::new(input), output);
69 }
70
71 #[test]
72 fn it_should_convert_from_str_successfully() {
73 let input = &"foobar"[..];
74 assert_eq!(StrSpan::new(input), input.into());
75 assert_eq!(StrSpanEx::new_extra(input, "extra"), input.into());
76 }
77
78 #[test]
79 fn it_should_ignore_extra_for_equality() {
80 let input = &"foobar"[..];
81
82 assert_eq!(
83 StrSpanEx::new_extra(input, "foo"),
84 StrSpanEx::new_extra(input, "bar")
85 );
86 }
87
88 #[cfg(feature = "std")]
89 #[test]
90 fn it_should_ignore_extra_for_hash() {
91 use std::collections::hash_map::DefaultHasher;
92 use std::hash::{Hash, Hasher};
93
94 fn calculate_hash<T: Hash>(t: &T) -> u64 {
95 let mut s = DefaultHasher::new();
96 t.hash(&mut s);
97 s.finish()
98 }
99
100 let input = &"foobar"[..];
101
102 assert_eq!(
103 calculate_hash(&StrSpanEx::new_extra(input, "foo")),
104 calculate_hash(&StrSpanEx::new_extra(input, "bar"))
105 );
106 }
107
108 #[test]
109 fn it_should_slice_for_str() {
110 let str_slice = StrSpanEx::new_extra("foobar", "extra");
111 assert_eq!(
112 str_slice.take_from(1),
113 StrSpanEx {
114 offset: 1,
115 line: 1,
116 fragment: "oobar",
117 extra: "extra",
118 }
119 );
120 assert_eq!(
121 str_slice.take(3).take_from(1),
122 StrSpanEx {
123 offset: 1,
124 line: 1,
125 fragment: "oo",
126 extra: "extra",
127 }
128 );
129 assert_eq!(
130 str_slice.take(3),
131 StrSpanEx {
132 offset: 0,
133 line: 1,
134 fragment: "foo",
135 extra: "extra",
136 }
137 );
138 assert_eq!(str_slice.take_from(0), str_slice);
139 }
140
141 #[test]
142 fn it_should_slice_for_u8() {
143 let bytes_slice = BytesSpanEx::new_extra(b"foobar", "extra");
144 assert_eq!(
145 bytes_slice.take_from(1),
146 BytesSpanEx {
147 offset: 1,
148 line: 1,
149 fragment: b"oobar",
150 extra: "extra",
151 }
152 );
153 assert_eq!(
154 bytes_slice.take(3).take_from(1),
155 BytesSpanEx {
156 offset: 1,
157 line: 1,
158 fragment: b"oo",
159 extra: "extra",
160 }
161 );
162 assert_eq!(
163 bytes_slice.take(3),
164 BytesSpanEx {
165 offset: 0,
166 line: 1,
167 fragment: b"foo",
168 extra: "extra",
169 }
170 );
171 assert_eq!(bytes_slice.take_from(0), bytes_slice);
172 }
173
174 #[test]
175 fn it_should_calculate_columns() {
176 let input = StrSpan::new(
177 "foo
178 bar",
179 );
180
181 let bar_idx = input.find_substring("bar").unwrap();
182 assert_eq!(input.take_from(bar_idx).get_column(), 9);
183 }
184
185 #[test]
186 fn it_should_calculate_columns_accurately_with_non_ascii_chars() {
187 let s = StrSpan::new("メカジキ");
188 assert_eq!(s.take_from(6).get_utf8_column(), 3);
189 }
190
191 #[test]
192 #[should_panic(expected = "offset is too big")]
193 fn it_should_panic_when_getting_column_if_offset_is_too_big() {
194 let s = StrSpanEx {
195 offset: usize::max_value(),
196 fragment: "",
197 line: 1,
198 extra: "",
199 };
200 s.get_column();
201 }
202
203 #[cfg(feature = "alloc")]
204 #[test]
205 fn it_should_iterate_indices() {
206 let str_slice = StrSpan::new("foobar");
207 assert_eq!(
208 str_slice.iter_indices().collect::<Vec<(usize, char)>>(),
209 vec![(0, 'f'), (1, 'o'), (2, 'o'), (3, 'b'), (4, 'a'), (5, 'r')]
210 );
211 assert_eq!(
212 StrSpan::new("")
213 .iter_indices()
214 .collect::<Vec<(usize, char)>>(),
215 vec![]
216 );
217 }
218
219 #[cfg(feature = "alloc")]
220 #[test]
221 fn it_should_iterate_elements() {
222 let str_slice = StrSpan::new("foobar");
223 assert_eq!(
224 str_slice.iter_elements().collect::<Vec<char>>(),
225 vec!['f', 'o', 'o', 'b', 'a', 'r']
226 );
227 assert_eq!(
228 StrSpan::new("").iter_elements().collect::<Vec<char>>(),
229 vec![]
230 );
231 }
232
233 #[test]
234 fn it_should_position_char() {
235 let str_slice = StrSpan::new("foobar");
236 assert_eq!(str_slice.position(|x| x == 'a'), Some(4));
237 assert_eq!(str_slice.position(|x| x == 'c'), None);
238 }
239
240 #[test]
241 fn it_should_compare_elements() {
242 assert_eq!(StrSpan::new("foobar").compare("foo"), CompareResult::Ok);
243 assert_eq!(StrSpan::new("foobar").compare("bar"), CompareResult::Error);
244 assert_eq!(StrSpan::new("foobar").compare("foobar"), CompareResult::Ok);
245 assert_eq!(
246 StrSpan::new("foobar").compare_no_case("fooBar"),
247 CompareResult::Ok
248 );
249 assert_eq!(
250 StrSpan::new("foobar").compare("foobarbaz"),
251 CompareResult::Incomplete
252 );
253 assert_eq!(
254 BytesSpan::new(b"foobar").compare(b"foo" as &[u8]),
255 CompareResult::Ok
256 );
257 }
258
259 #[test]
260 #[allow(unused_parens)]
261 fn it_should_find_token() {
262 assert!(StrSpan::new("foobar").find_token('a'));
263 assert!(StrSpan::new("foobar").find_token(b'a'));
264 assert!(StrSpan::new("foobar").find_token(&(b'a')));
265 assert!(!StrSpan::new("foobar").find_token('c'));
266 assert!(!StrSpan::new("foobar").find_token(b'c'));
267 assert!(!StrSpan::new("foobar").find_token((&b'c')));
268
269 assert!(BytesSpan::new(b"foobar").find_token(b'a'));
270 assert!(BytesSpan::new(b"foobar").find_token(&(b'a')));
271 assert!(!BytesSpan::new(b"foobar").find_token(b'c'));
272 assert!(!BytesSpan::new(b"foobar").find_token((&b'c')));
273 }
274
275 #[test]
276 fn it_should_find_substring() {
277 assert_eq!(StrSpan::new("foobar").find_substring("bar"), Some(3));
278 assert_eq!(StrSpan::new("foobar").find_substring("baz"), None);
279 assert_eq!(BytesSpan::new(b"foobar").find_substring("bar"), Some(3));
280 assert_eq!(BytesSpan::new(b"foobar").find_substring("baz"), None);
281 assert_eq!(
282 BytesSpan::new(b"foobar").find_substring(b"bar" as &[u8]),
283 Some(3)
284 );
285 assert_eq!(
286 BytesSpan::new(b"foobar").find_substring(b"baz" as &[u8]),
287 None
288 );
289 }
290
291 #[cfg(feature = "alloc")]
292 #[test]
293 fn it_should_parse_to_string() {
294 assert_eq!(
295 StrSpan::new("foobar").parse_to(),
296 Some("foobar".to_string())
297 );
298 assert_eq!(
299 BytesSpan::new(b"foobar").parse_to(),
300 Some("foobar".to_string())
301 );
302 }
303
304 // https://github.com/Geal/nom/blob/eee82832fafdfdd0505546d224caa466f7d39a15/src/util.rs#L710-L720
305 #[test]
306 fn it_should_calculate_offset_for_u8() {
307 let s = b"abcd123";
308 let a = &s[..];
309 let b = &a[2..];
310 let c = &a[..4];
311 let d = &a[3..5];
312 assert_eq!(a.offset(b), 2);
313 assert_eq!(a.offset(c), 0);
314 assert_eq!(a.offset(d), 3);
315 }
316
317 // https://github.com/Geal/nom/blob/eee82832fafdfdd0505546d224caa466f7d39a15/src/util.rs#L722-L732
318 #[test]
319 fn it_should_calculate_offset_for_str() {
320 let s = StrSpan::new("abcřèÂßÇd123");
321 let a = s.take_from(0);
322 let b = a.take_from(7);
323 let c = a.take(5);
324 let d = a.take(9).take_from(5);
325 assert_eq!(a.offset(&b), 7);
326 assert_eq!(a.offset(&c), 0);
327 assert_eq!(a.offset(&d), 5);
328 }
329
330 #[test]
331 fn it_should_take_chars() {
332 let s = StrSpanEx::new_extra("abcdefghij", "extra");
333 assert_eq!(
334 s.take(5),
335 StrSpanEx {
336 offset: 0,
337 line: 1,
338 fragment: "abcde",
339 extra: "extra",
340 }
341 );
342 }
343
344 #[test]
345 fn it_should_take_split_chars() {
346 let s = StrSpanEx::new_extra("abcdefghij", "extra");
347 assert_eq!(
348 s.take_split(5),
349 (
350 StrSpanEx {
351 offset: 5,
352 line: 1,
353 fragment: "fghij",
354 extra: "extra",
355 },
356 StrSpanEx {
357 offset: 0,
358 line: 1,
359 fragment: "abcde",
360 extra: "extra",
361 }
362 )
363 );
364 }
365
366 type TestError<'a, 'b> = (LocatedSpan<&'a str, &'b str>, nom::error::ErrorKind);
367
368 #[test]
369 fn it_should_split_at_position() {
370 let s = StrSpanEx::new_extra("abcdefghij", "extra");
371 assert_eq!(
372 s.split_at_position::<_, TestError>(|c| { c == 'f' }),
373 Ok((
374 StrSpanEx {
375 offset: 5,
376 line: 1,
377 fragment: "fghij",
378 extra: "extra",
379 },
380 StrSpanEx {
381 offset: 0,
382 line: 1,
383 fragment: "abcde",
384 extra: "extra",
385 }
386 ))
387 );
388 }
389
390 // TODO also test split_at_position with an error
391
392 #[test]
393 fn it_should_split_at_position1() {
394 let s = StrSpanEx::new_extra("abcdefghij", "extra");
395 assert_eq!(
396 s.split_at_position1::<_, TestError>(|c| { c == 'f' }, ErrorKind::Alpha),
397 s.split_at_position::<_, TestError>(|c| { c == 'f' }),
398 );
399 }
400
401 #[test]
402 fn it_should_capture_position() {
403 use super::position;
404 use nom::bytes::complete::{tag, take_until};
405 use nom::IResult;
406
407 fn parser<'a>(s: StrSpan<'a>) -> IResult<StrSpan<'a>, (StrSpan<'a>, &'a str)> {
408 let (s, _) = take_until("def")(s)?;
409 let (s, p) = position(s)?;
410 let (s, t) = tag("def")(s)?;
411 Ok((s, (p, t.fragment)))
412 }
413
414 let s = StrSpan::new("abc\ndefghij");
415 let (_, (s, t)) = parser(s).unwrap();
416 assert_eq!(s.offset, 4);
417 assert_eq!(s.line, 2);
418 assert_eq!(t, "def");
419 }
420
421 #[test]
422 fn it_should_deref_to_fragment() {
423 let input = &"foobar"[..];
424 assert_eq!(*StrSpanEx::new_extra(input, "extra"), input);
425 let input = &b"foobar"[..];
426 assert_eq!(*BytesSpanEx::new_extra(input, "extra"), input);
427 }
428
429 #[cfg(feature = "std")]
430 #[test]
431 fn it_should_display_hex() {
432 use nom::HexDisplay;
433 assert_eq!(
434 StrSpan::new(&"abc"[..]).to_hex(4),
435 "00000000\t61 62 63 \tabc\n".to_owned()
436 );
437 assert_eq!(
438 BytesSpanEx::new_extra(&b"abc"[..], "extra").to_hex(4),
439 "00000000\t61 62 63 \tabc\n".to_owned()
440 );
441 }
442
443 #[test]
444 fn line_of_empty_span_is_empty() {
445 assert_eq!(StrSpan::new("").get_line_beginning(), "".as_bytes());
446 }
447
448 #[test]
449 fn line_of_single_line_start_is_whole() {
450 assert_eq!(
451 StrSpan::new("A single line").get_line_beginning(),
452 "A single line".as_bytes(),
453 );
454 }
455 #[test]
456 fn line_of_single_line_end_is_whole() {
457 let data = "A single line";
458 assert_eq!(
459 StrSpan::new(data)
460 .take_from(data.len())
461 .get_line_beginning(),
462 "A single line".as_bytes(),
463 );
464 }
465
466 #[test]
467 fn line_of_start_is_first() {
468 assert_eq!(
469 StrSpan::new(
470 "One line of text\
471 \nFollowed by a second\
472 \nand a third\n"
473 )
474 .get_line_beginning(),
475 "One line of text".as_bytes(),
476 );
477 }
478
479 #[test]
480 fn line_of_nl_is_before() {
481 let data = "One line of text\
482 \nFollowed by a second\
483 \nand a third\n";
484 assert_eq!(
485 StrSpan::new(data)
486 .take_from(data.find('\n').unwrap())
487 .get_line_beginning(),
488 "One line of text".as_bytes(),
489 );
490 }
491
492 #[test]
493 fn line_of_end_after_nl_is_empty() {
494 let data = "One line of text\
495 \nFollowed by a second\
496 \nand a third\n";
497 assert_eq!(
498 StrSpan::new(data)
499 .take_from(data.len())
500 .get_line_beginning(),
501 "".as_bytes(),
502 );
503 }
504
505 #[test]
506 fn line_of_end_no_nl_is_last() {
507 let data = "One line of text\
508 \nFollowed by a second\
509 \nand a third";
510 assert_eq!(
511 StrSpan::new(data)
512 .take_from(data.len())
513 .get_line_beginning(),
514 "and a third".as_bytes(),
515 );
516 }
517
518 /// This test documents how `get_line_beginning()` differs from
519 /// a hypotetical `get_line()` method.
520 #[test]
521 fn line_begining_may_ot_be_entire_len() {
522 let data = "One line of text\
523 \nFollowed by a second\
524 \nand a third";
525 let by = "by";
526 let pos = data.find_substring(by).unwrap();
527 assert_eq!(
528 StrSpan::new(data)
529 .take(pos + by.len())
530 .take_from(pos)
531 .get_line_beginning(),
532 "Followed by".as_bytes(),
533 );
534 }
535
536 #[cfg(feature = "std")]
537 #[test]
538 fn line_for_non_ascii_chars() {
539 let data = StrSpan::new(
540 "Några rader text på Svenska.\
541 \nFörra raden var först, den här är i mitten\
542 \noch här är sista raden.\n",
543 );
544 let s = data.take_from(data.find_substring("först").unwrap());
545 assert_eq!(
546 format!(
547 "{line_no:3}: {line_text}\n {0:>lpos$}^- The match\n",
548 "",
549 line_no = s.location_line(),
550 line_text = core::str::from_utf8(s.get_line_beginning()).unwrap(),
551 lpos = s.get_utf8_column(),
552 ),
553 " 2: Förra raden var först, den här är i mitten\
554 \n ^- The match\n",
555 );
556 }
557
558 #[test]
559 fn it_should_implement_as_ref_for_the_underlying_type() {
560 // LocatedSpan<&str> should implement AsRef<str>.
561 {
562 fn function_accepting_str<S: AsRef<str>>(_s: S) {}
563 let str_data = StrSpan::new("some data");
564 function_accepting_str(str_data);
565 }
566
567 // LocatedSpan<&[u8]> should implement AsRef<[u8]>.
568 {
569 fn function_accepting_u8_slice<B: AsRef<[u8]>>(_data: B) {}
570 let bytes_data = BytesSpan::new(b"some binary data");
571 function_accepting_u8_slice(bytes_data);
572 }
573 }
574
575 #[cfg(feature = "std")]
576 #[test]
577 fn it_should_implement_as_ref_impls_for_the_underlying_type() {
578 // Since str implements AsRef<Path>, it's useful to have LocatedSpan<&str>
579 // implement AsRef<Path> as well.
580 fn function_accepting_path<P: AsRef<std::path::Path>>(_path: P) {}
581 let str_data = StrSpan::new("some data");
582 function_accepting_path(str_data);
583 }