1 //! Traits input types have to implement to work with nom combinators
2 use crate::error::{ErrorKind, ParseError};
3 use crate::internal::{Err, IResult, Needed};
4 use crate::lib::std::iter::{Copied, Enumerate};
5 use crate::lib::std::ops::{Range, RangeFrom, RangeFull, RangeTo};
6 use crate::lib::std::slice::Iter;
7 use crate::lib::std::str::from_utf8;
8 use crate::lib::std::str::CharIndices;
9 use crate::lib::std::str::Chars;
10 use crate::lib::std::str::FromStr;
11
12 #[cfg(feature = "alloc")]
13 use crate::lib::std::string::String;
14 #[cfg(feature = "alloc")]
15 use crate::lib::std::vec::Vec;
16
17 #[cfg(feature = "bitvec")]
18 use bitvec::prelude::*;
19
20 /// Abstract method to calculate the input length
21 pub trait InputLength {
22 /// Calculates the input length, as indicated by its name,
23 /// and the name of the trait itself
input_len(&self) -> usize24 fn input_len(&self) -> usize;
25 }
26
27 impl<'a, T> InputLength for &'a [T] {
28 #[inline]
input_len(&self) -> usize29 fn input_len(&self) -> usize {
30 self.len()
31 }
32 }
33
34 impl<'a> InputLength for &'a str {
35 #[inline]
input_len(&self) -> usize36 fn input_len(&self) -> usize {
37 self.len()
38 }
39 }
40
41 impl<'a> InputLength for (&'a [u8], usize) {
42 #[inline]
input_len(&self) -> usize43 fn input_len(&self) -> usize {
44 //println!("bit input length for ({:?}, {}):", self.0, self.1);
45 //println!("-> {}", self.0.len() * 8 - self.1);
46 self.0.len() * 8 - self.1
47 }
48 }
49
50 #[cfg(feature = "bitvec")]
51 impl<'a, O, T> InputLength for &'a BitSlice<O, T>
52 where
53 O: BitOrder,
54 T: 'a + BitStore,
55 {
56 #[inline]
input_len(&self) -> usize57 fn input_len(&self) -> usize {
58 self.len()
59 }
60 }
61
62 /// Useful functions to calculate the offset between slices and show a hexdump of a slice
63 pub trait Offset {
64 /// Offset between the first byte of self and the first byte of the argument
offset(&self, second: &Self) -> usize65 fn offset(&self, second: &Self) -> usize;
66 }
67
68 impl Offset for [u8] {
offset(&self, second: &Self) -> usize69 fn offset(&self, second: &Self) -> usize {
70 let fst = self.as_ptr();
71 let snd = second.as_ptr();
72
73 snd as usize - fst as usize
74 }
75 }
76
77 impl<'a> Offset for &'a [u8] {
offset(&self, second: &Self) -> usize78 fn offset(&self, second: &Self) -> usize {
79 let fst = self.as_ptr();
80 let snd = second.as_ptr();
81
82 snd as usize - fst as usize
83 }
84 }
85
86 impl Offset for str {
offset(&self, second: &Self) -> usize87 fn offset(&self, second: &Self) -> usize {
88 let fst = self.as_ptr();
89 let snd = second.as_ptr();
90
91 snd as usize - fst as usize
92 }
93 }
94
95 impl<'a> Offset for &'a str {
offset(&self, second: &Self) -> usize96 fn offset(&self, second: &Self) -> usize {
97 let fst = self.as_ptr();
98 let snd = second.as_ptr();
99
100 snd as usize - fst as usize
101 }
102 }
103
104 #[cfg(feature = "bitvec")]
105 impl<O, T> Offset for BitSlice<O, T>
106 where
107 O: BitOrder,
108 T: BitStore,
109 {
110 #[inline(always)]
offset(&self, second: &Self) -> usize111 fn offset(&self, second: &Self) -> usize {
112 second.offset_from(self) as usize
113 }
114 }
115
116 #[cfg(feature = "bitvec")]
117 impl<'a, O, T> Offset for &'a BitSlice<O, T>
118 where
119 O: BitOrder,
120 T: 'a + BitStore,
121 {
122 #[inline(always)]
offset(&self, second: &Self) -> usize123 fn offset(&self, second: &Self) -> usize {
124 second.offset_from(self) as usize
125 }
126 }
127
128 /// Helper trait for types that can be viewed as a byte slice
129 pub trait AsBytes {
130 /// Casts the input type to a byte slice
as_bytes(&self) -> &[u8]131 fn as_bytes(&self) -> &[u8];
132 }
133
134 impl<'a> AsBytes for &'a str {
135 #[inline(always)]
as_bytes(&self) -> &[u8]136 fn as_bytes(&self) -> &[u8] {
137 (*self).as_bytes()
138 }
139 }
140
141 impl AsBytes for str {
142 #[inline(always)]
as_bytes(&self) -> &[u8]143 fn as_bytes(&self) -> &[u8] {
144 self.as_ref()
145 }
146 }
147
148 impl<'a> AsBytes for &'a [u8] {
149 #[inline(always)]
as_bytes(&self) -> &[u8]150 fn as_bytes(&self) -> &[u8] {
151 *self
152 }
153 }
154
155 impl AsBytes for [u8] {
156 #[inline(always)]
as_bytes(&self) -> &[u8]157 fn as_bytes(&self) -> &[u8] {
158 self
159 }
160 }
161
162 #[cfg(feature = "bitvec")]
163 impl<'a, O> AsBytes for &'a BitSlice<O, u8>
164 where
165 O: BitOrder,
166 {
167 #[inline(always)]
as_bytes(&self) -> &[u8]168 fn as_bytes(&self) -> &[u8] {
169 self.as_slice()
170 }
171 }
172
173 #[cfg(feature = "bitvec")]
174 impl<O> AsBytes for BitSlice<O, u8>
175 where
176 O: BitOrder,
177 {
178 #[inline(always)]
as_bytes(&self) -> &[u8]179 fn as_bytes(&self) -> &[u8] {
180 self.as_slice()
181 }
182 }
183
184 macro_rules! as_bytes_array_impls {
185 ($($N:expr)+) => {
186 $(
187 impl<'a> AsBytes for &'a [u8; $N] {
188 #[inline(always)]
189 fn as_bytes(&self) -> &[u8] {
190 *self
191 }
192 }
193
194 impl AsBytes for [u8; $N] {
195 #[inline(always)]
196 fn as_bytes(&self) -> &[u8] {
197 self
198 }
199 }
200
201 #[cfg(feature = "bitvec")]
202 impl<'a, O> AsBytes for &'a BitArray<O, [u8; $N]>
203 where O: BitOrder {
204 #[inline(always)]
205 fn as_bytes(&self) -> &[u8] {
206 self.as_slice()
207 }
208 }
209
210 #[cfg(feature = "bitvec")]
211 impl<O> AsBytes for BitArray<O, [u8; $N]>
212 where O: BitOrder {
213 #[inline(always)]
214 fn as_bytes(&self) -> &[u8] {
215 self.as_slice()
216 }
217 }
218 )+
219 };
220 }
221
222 as_bytes_array_impls! {
223 0 1 2 3 4 5 6 7 8 9
224 10 11 12 13 14 15 16 17 18 19
225 20 21 22 23 24 25 26 27 28 29
226 30 31 32
227 }
228
229 /// Transforms common types to a char for basic token parsing
230 pub trait AsChar {
231 /// makes a char from self
as_char(self) -> char232 fn as_char(self) -> char;
233
234 /// Tests that self is an alphabetic character
235 ///
236 /// Warning: for `&str` it recognizes alphabetic
237 /// characters outside of the 52 ASCII letters
is_alpha(self) -> bool238 fn is_alpha(self) -> bool;
239
240 /// Tests that self is an alphabetic character
241 /// or a decimal digit
is_alphanum(self) -> bool242 fn is_alphanum(self) -> bool;
243 /// Tests that self is a decimal digit
is_dec_digit(self) -> bool244 fn is_dec_digit(self) -> bool;
245 /// Tests that self is an hex digit
is_hex_digit(self) -> bool246 fn is_hex_digit(self) -> bool;
247 /// Tests that self is an octal digit
is_oct_digit(self) -> bool248 fn is_oct_digit(self) -> bool;
249 /// Gets the len in bytes for self
len(self) -> usize250 fn len(self) -> usize;
251 }
252
253 impl AsChar for u8 {
254 #[inline]
as_char(self) -> char255 fn as_char(self) -> char {
256 self as char
257 }
258 #[inline]
is_alpha(self) -> bool259 fn is_alpha(self) -> bool {
260 (self >= 0x41 && self <= 0x5A) || (self >= 0x61 && self <= 0x7A)
261 }
262 #[inline]
is_alphanum(self) -> bool263 fn is_alphanum(self) -> bool {
264 self.is_alpha() || self.is_dec_digit()
265 }
266 #[inline]
is_dec_digit(self) -> bool267 fn is_dec_digit(self) -> bool {
268 self >= 0x30 && self <= 0x39
269 }
270 #[inline]
is_hex_digit(self) -> bool271 fn is_hex_digit(self) -> bool {
272 (self >= 0x30 && self <= 0x39)
273 || (self >= 0x41 && self <= 0x46)
274 || (self >= 0x61 && self <= 0x66)
275 }
276 #[inline]
is_oct_digit(self) -> bool277 fn is_oct_digit(self) -> bool {
278 self >= 0x30 && self <= 0x37
279 }
280 #[inline]
len(self) -> usize281 fn len(self) -> usize {
282 1
283 }
284 }
285 impl<'a> AsChar for &'a u8 {
286 #[inline]
as_char(self) -> char287 fn as_char(self) -> char {
288 *self as char
289 }
290 #[inline]
is_alpha(self) -> bool291 fn is_alpha(self) -> bool {
292 (*self >= 0x41 && *self <= 0x5A) || (*self >= 0x61 && *self <= 0x7A)
293 }
294 #[inline]
is_alphanum(self) -> bool295 fn is_alphanum(self) -> bool {
296 self.is_alpha() || self.is_dec_digit()
297 }
298 #[inline]
is_dec_digit(self) -> bool299 fn is_dec_digit(self) -> bool {
300 *self >= 0x30 && *self <= 0x39
301 }
302 #[inline]
is_hex_digit(self) -> bool303 fn is_hex_digit(self) -> bool {
304 (*self >= 0x30 && *self <= 0x39)
305 || (*self >= 0x41 && *self <= 0x46)
306 || (*self >= 0x61 && *self <= 0x66)
307 }
308 #[inline]
is_oct_digit(self) -> bool309 fn is_oct_digit(self) -> bool {
310 *self >= 0x30 && *self <= 0x37
311 }
312 #[inline]
len(self) -> usize313 fn len(self) -> usize {
314 1
315 }
316 }
317
318 impl AsChar for char {
319 #[inline]
as_char(self) -> char320 fn as_char(self) -> char {
321 self
322 }
323 #[inline]
is_alpha(self) -> bool324 fn is_alpha(self) -> bool {
325 self.is_ascii_alphabetic()
326 }
327 #[inline]
is_alphanum(self) -> bool328 fn is_alphanum(self) -> bool {
329 self.is_alpha() || self.is_dec_digit()
330 }
331 #[inline]
is_dec_digit(self) -> bool332 fn is_dec_digit(self) -> bool {
333 self.is_ascii_digit()
334 }
335 #[inline]
is_hex_digit(self) -> bool336 fn is_hex_digit(self) -> bool {
337 self.is_ascii_hexdigit()
338 }
339 #[inline]
is_oct_digit(self) -> bool340 fn is_oct_digit(self) -> bool {
341 self.is_digit(8)
342 }
343 #[inline]
len(self) -> usize344 fn len(self) -> usize {
345 self.len_utf8()
346 }
347 }
348
349 impl<'a> AsChar for &'a char {
350 #[inline]
as_char(self) -> char351 fn as_char(self) -> char {
352 *self
353 }
354 #[inline]
is_alpha(self) -> bool355 fn is_alpha(self) -> bool {
356 self.is_ascii_alphabetic()
357 }
358 #[inline]
is_alphanum(self) -> bool359 fn is_alphanum(self) -> bool {
360 self.is_alpha() || self.is_dec_digit()
361 }
362 #[inline]
is_dec_digit(self) -> bool363 fn is_dec_digit(self) -> bool {
364 self.is_ascii_digit()
365 }
366 #[inline]
is_hex_digit(self) -> bool367 fn is_hex_digit(self) -> bool {
368 self.is_ascii_hexdigit()
369 }
370 #[inline]
is_oct_digit(self) -> bool371 fn is_oct_digit(self) -> bool {
372 self.is_digit(8)
373 }
374 #[inline]
len(self) -> usize375 fn len(self) -> usize {
376 self.len_utf8()
377 }
378 }
379
380 /// Abstracts common iteration operations on the input type
381 pub trait InputIter {
382 /// The current input type is a sequence of that `Item` type.
383 ///
384 /// Example: `u8` for `&[u8]` or `char` for `&str`
385 type Item;
386 /// An iterator over the input type, producing the item and its position
387 /// for use with [Slice]. If we're iterating over `&str`, the position
388 /// corresponds to the byte index of the character
389 type Iter: Iterator<Item = (usize, Self::Item)>;
390
391 /// An iterator over the input type, producing the item
392 type IterElem: Iterator<Item = Self::Item>;
393
394 /// Returns an iterator over the elements and their byte offsets
iter_indices(&self) -> Self::Iter395 fn iter_indices(&self) -> Self::Iter;
396 /// Returns an iterator over the elements
iter_elements(&self) -> Self::IterElem397 fn iter_elements(&self) -> Self::IterElem;
398 /// Finds the byte position of the element
position<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Item) -> bool399 fn position<P>(&self, predicate: P) -> Option<usize>
400 where
401 P: Fn(Self::Item) -> bool;
402 /// Get the byte offset from the element's position in the stream
slice_index(&self, count: usize) -> Result<usize, Needed>403 fn slice_index(&self, count: usize) -> Result<usize, Needed>;
404 }
405
406 /// Abstracts slicing operations
407 pub trait InputTake: Sized {
408 /// Returns a slice of `count` bytes. panics if count > length
take(&self, count: usize) -> Self409 fn take(&self, count: usize) -> Self;
410 /// Split the stream at the `count` byte offset. panics if count > length
take_split(&self, count: usize) -> (Self, Self)411 fn take_split(&self, count: usize) -> (Self, Self);
412 }
413
414 impl<'a> InputIter for &'a [u8] {
415 type Item = u8;
416 type Iter = Enumerate<Self::IterElem>;
417 type IterElem = Copied<Iter<'a, u8>>;
418
419 #[inline]
iter_indices(&self) -> Self::Iter420 fn iter_indices(&self) -> Self::Iter {
421 self.iter_elements().enumerate()
422 }
423 #[inline]
iter_elements(&self) -> Self::IterElem424 fn iter_elements(&self) -> Self::IterElem {
425 self.iter().copied()
426 }
427 #[inline]
position<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Item) -> bool,428 fn position<P>(&self, predicate: P) -> Option<usize>
429 where
430 P: Fn(Self::Item) -> bool,
431 {
432 self.iter().position(|b| predicate(*b))
433 }
434 #[inline]
slice_index(&self, count: usize) -> Result<usize, Needed>435 fn slice_index(&self, count: usize) -> Result<usize, Needed> {
436 if self.len() >= count {
437 Ok(count)
438 } else {
439 Err(Needed::new(count - self.len()))
440 }
441 }
442 }
443
444 impl<'a> InputTake for &'a [u8] {
445 #[inline]
take(&self, count: usize) -> Self446 fn take(&self, count: usize) -> Self {
447 &self[0..count]
448 }
449 #[inline]
take_split(&self, count: usize) -> (Self, Self)450 fn take_split(&self, count: usize) -> (Self, Self) {
451 let (prefix, suffix) = self.split_at(count);
452 (suffix, prefix)
453 }
454 }
455
456 impl<'a> InputIter for &'a str {
457 type Item = char;
458 type Iter = CharIndices<'a>;
459 type IterElem = Chars<'a>;
460 #[inline]
iter_indices(&self) -> Self::Iter461 fn iter_indices(&self) -> Self::Iter {
462 self.char_indices()
463 }
464 #[inline]
iter_elements(&self) -> Self::IterElem465 fn iter_elements(&self) -> Self::IterElem {
466 self.chars()
467 }
position<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Item) -> bool,468 fn position<P>(&self, predicate: P) -> Option<usize>
469 where
470 P: Fn(Self::Item) -> bool,
471 {
472 for (o, c) in self.char_indices() {
473 if predicate(c) {
474 return Some(o);
475 }
476 }
477 None
478 }
479 #[inline]
slice_index(&self, count: usize) -> Result<usize, Needed>480 fn slice_index(&self, count: usize) -> Result<usize, Needed> {
481 let mut cnt = 0;
482 for (index, _) in self.char_indices() {
483 if cnt == count {
484 return Ok(index);
485 }
486 cnt += 1;
487 }
488 if cnt == count {
489 return Ok(self.len());
490 }
491 Err(Needed::Unknown)
492 }
493 }
494
495 impl<'a> InputTake for &'a str {
496 #[inline]
take(&self, count: usize) -> Self497 fn take(&self, count: usize) -> Self {
498 &self[..count]
499 }
500
501 // return byte index
502 #[inline]
take_split(&self, count: usize) -> (Self, Self)503 fn take_split(&self, count: usize) -> (Self, Self) {
504 (&self[count..], &self[..count])
505 }
506 }
507
508 #[cfg(feature = "bitvec")]
509 impl<'a, O, T> InputIter for &'a BitSlice<O, T>
510 where
511 O: BitOrder,
512 T: 'a + BitStore,
513 {
514 type Item = bool;
515 type Iter = Enumerate<Self::IterElem>;
516 type IterElem = Copied<bitvec::slice::Iter<'a, O, T>>;
517
518 #[inline]
iter_indices(&self) -> Self::Iter519 fn iter_indices(&self) -> Self::Iter {
520 self.iter_elements().enumerate()
521 }
522
523 #[inline]
iter_elements(&self) -> Self::IterElem524 fn iter_elements(&self) -> Self::IterElem {
525 self.iter().copied()
526 }
527
528 #[inline]
position<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Item) -> bool,529 fn position<P>(&self, predicate: P) -> Option<usize>
530 where
531 P: Fn(Self::Item) -> bool,
532 {
533 self.iter_elements().position(predicate)
534 }
535
536 #[inline]
slice_index(&self, count: usize) -> Result<usize, Needed>537 fn slice_index(&self, count: usize) -> Result<usize, Needed> {
538 if self.len() >= count {
539 Ok(count)
540 } else {
541 Err(Needed::new(count - self.len()))
542 }
543 }
544 }
545
546 #[cfg(feature = "bitvec")]
547 impl<'a, O, T> InputTake for &'a BitSlice<O, T>
548 where
549 O: BitOrder,
550 T: 'a + BitStore,
551 {
552 #[inline]
take(&self, count: usize) -> Self553 fn take(&self, count: usize) -> Self {
554 &self[..count]
555 }
556
557 #[inline]
take_split(&self, count: usize) -> (Self, Self)558 fn take_split(&self, count: usize) -> (Self, Self) {
559 let (a, b) = self.split_at(count);
560 (b, a)
561 }
562 }
563
564 /// Dummy trait used for default implementations (currently only used for `InputTakeAtPosition` and `Compare`).
565 ///
566 /// When implementing a custom input type, it is possible to use directly the
567 /// default implementation: If the input type implements `InputLength`, `InputIter`,
568 /// `InputTake` and `Clone`, you can implement `UnspecializedInput` and get
569 /// a default version of `InputTakeAtPosition` and `Compare`.
570 ///
571 /// For performance reasons, you might want to write a custom implementation of
572 /// `InputTakeAtPosition` (like the one for `&[u8]`).
573 pub trait UnspecializedInput {}
574
575 /// Methods to take as much input as possible until the provided function returns true for the current element.
576 ///
577 /// A large part of nom's basic parsers are built using this trait.
578 pub trait InputTakeAtPosition: Sized {
579 /// The current input type is a sequence of that `Item` type.
580 ///
581 /// Example: `u8` for `&[u8]` or `char` for `&str`
582 type Item;
583
584 /// Looks for the first element of the input type for which the condition returns true,
585 /// and returns the input up to this position.
586 ///
587 /// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool588 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
589 where
590 P: Fn(Self::Item) -> bool;
591
592 /// Looks for the first element of the input type for which the condition returns true
593 /// and returns the input up to this position.
594 ///
595 /// Fails if the produced slice is empty.
596 ///
597 /// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
split_at_position1<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool598 fn split_at_position1<P, E: ParseError<Self>>(
599 &self,
600 predicate: P,
601 e: ErrorKind,
602 ) -> IResult<Self, Self, E>
603 where
604 P: Fn(Self::Item) -> bool;
605
606 /// Looks for the first element of the input type for which the condition returns true,
607 /// and returns the input up to this position.
608 ///
609 /// *complete version*: If no element is found matching the condition, this will return the whole input
split_at_position_complete<P, E: ParseError<Self>>( &self, predicate: P, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool610 fn split_at_position_complete<P, E: ParseError<Self>>(
611 &self,
612 predicate: P,
613 ) -> IResult<Self, Self, E>
614 where
615 P: Fn(Self::Item) -> bool;
616
617 /// Looks for the first element of the input type for which the condition returns true
618 /// and returns the input up to this position.
619 ///
620 /// Fails if the produced slice is empty.
621 ///
622 /// *complete version*: If no element is found matching the condition, this will return the whole input
split_at_position1_complete<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool623 fn split_at_position1_complete<P, E: ParseError<Self>>(
624 &self,
625 predicate: P,
626 e: ErrorKind,
627 ) -> IResult<Self, Self, E>
628 where
629 P: Fn(Self::Item) -> bool;
630 }
631
632 impl<T: InputLength + InputIter + InputTake + Clone + UnspecializedInput> InputTakeAtPosition
633 for T
634 {
635 type Item = <T as InputIter>::Item;
636
split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,637 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
638 where
639 P: Fn(Self::Item) -> bool,
640 {
641 match self.position(predicate) {
642 Some(n) => Ok(self.take_split(n)),
643 None => Err(Err::Incomplete(Needed::new(1))),
644 }
645 }
646
split_at_position1<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,647 fn split_at_position1<P, E: ParseError<Self>>(
648 &self,
649 predicate: P,
650 e: ErrorKind,
651 ) -> IResult<Self, Self, E>
652 where
653 P: Fn(Self::Item) -> bool,
654 {
655 match self.position(predicate) {
656 Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
657 Some(n) => Ok(self.take_split(n)),
658 None => Err(Err::Incomplete(Needed::new(1))),
659 }
660 }
661
split_at_position_complete<P, E: ParseError<Self>>( &self, predicate: P, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,662 fn split_at_position_complete<P, E: ParseError<Self>>(
663 &self,
664 predicate: P,
665 ) -> IResult<Self, Self, E>
666 where
667 P: Fn(Self::Item) -> bool,
668 {
669 match self.split_at_position(predicate) {
670 Err(Err::Incomplete(_)) => Ok(self.take_split(self.input_len())),
671 res => res,
672 }
673 }
674
split_at_position1_complete<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,675 fn split_at_position1_complete<P, E: ParseError<Self>>(
676 &self,
677 predicate: P,
678 e: ErrorKind,
679 ) -> IResult<Self, Self, E>
680 where
681 P: Fn(Self::Item) -> bool,
682 {
683 match self.split_at_position1(predicate, e) {
684 Err(Err::Incomplete(_)) => {
685 if self.input_len() == 0 {
686 Err(Err::Error(E::from_error_kind(self.clone(), e)))
687 } else {
688 Ok(self.take_split(self.input_len()))
689 }
690 }
691 res => res,
692 }
693 }
694 }
695
696 impl<'a> InputTakeAtPosition for &'a [u8] {
697 type Item = u8;
698
split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,699 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
700 where
701 P: Fn(Self::Item) -> bool,
702 {
703 match (0..self.len()).find(|b| predicate(self[*b])) {
704 Some(i) => Ok((&self[i..], &self[..i])),
705 None => Err(Err::Incomplete(Needed::new(1))),
706 }
707 }
708
split_at_position1<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,709 fn split_at_position1<P, E: ParseError<Self>>(
710 &self,
711 predicate: P,
712 e: ErrorKind,
713 ) -> IResult<Self, Self, E>
714 where
715 P: Fn(Self::Item) -> bool,
716 {
717 match (0..self.len()).find(|b| predicate(self[*b])) {
718 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
719 Some(i) => Ok((&self[i..], &self[..i])),
720 None => Err(Err::Incomplete(Needed::new(1))),
721 }
722 }
723
split_at_position_complete<P, E: ParseError<Self>>( &self, predicate: P, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,724 fn split_at_position_complete<P, E: ParseError<Self>>(
725 &self,
726 predicate: P,
727 ) -> IResult<Self, Self, E>
728 where
729 P: Fn(Self::Item) -> bool,
730 {
731 match (0..self.len()).find(|b| predicate(self[*b])) {
732 Some(i) => Ok((&self[i..], &self[..i])),
733 None => Ok(self.take_split(self.input_len())),
734 }
735 }
736
split_at_position1_complete<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,737 fn split_at_position1_complete<P, E: ParseError<Self>>(
738 &self,
739 predicate: P,
740 e: ErrorKind,
741 ) -> IResult<Self, Self, E>
742 where
743 P: Fn(Self::Item) -> bool,
744 {
745 match (0..self.len()).find(|b| predicate(self[*b])) {
746 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
747 Some(i) => Ok((&self[i..], &self[..i])),
748 None => {
749 if self.is_empty() {
750 Err(Err::Error(E::from_error_kind(self, e)))
751 } else {
752 Ok(self.take_split(self.input_len()))
753 }
754 }
755 }
756 }
757 }
758
759 impl<'a> InputTakeAtPosition for &'a str {
760 type Item = char;
761
split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,762 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
763 where
764 P: Fn(Self::Item) -> bool,
765 {
766 match self.find(predicate) {
767 Some(i) => Ok((&self[i..], &self[..i])),
768 None => Err(Err::Incomplete(Needed::new(1))),
769 }
770 }
771
split_at_position1<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,772 fn split_at_position1<P, E: ParseError<Self>>(
773 &self,
774 predicate: P,
775 e: ErrorKind,
776 ) -> IResult<Self, Self, E>
777 where
778 P: Fn(Self::Item) -> bool,
779 {
780 match self.find(predicate) {
781 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
782 Some(i) => Ok((&self[i..], &self[..i])),
783 None => Err(Err::Incomplete(Needed::new(1))),
784 }
785 }
786
split_at_position_complete<P, E: ParseError<Self>>( &self, predicate: P, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,787 fn split_at_position_complete<P, E: ParseError<Self>>(
788 &self,
789 predicate: P,
790 ) -> IResult<Self, Self, E>
791 where
792 P: Fn(Self::Item) -> bool,
793 {
794 match self.find(predicate) {
795 Some(i) => Ok((&self[i..], &self[..i])),
796 None => Ok(self.take_split(self.input_len())),
797 }
798 }
799
split_at_position1_complete<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,800 fn split_at_position1_complete<P, E: ParseError<Self>>(
801 &self,
802 predicate: P,
803 e: ErrorKind,
804 ) -> IResult<Self, Self, E>
805 where
806 P: Fn(Self::Item) -> bool,
807 {
808 match self.find(predicate) {
809 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
810 Some(i) => Ok((&self[i..], &self[..i])),
811 None => {
812 if self.is_empty() {
813 Err(Err::Error(E::from_error_kind(self, e)))
814 } else {
815 Ok(self.take_split(self.input_len()))
816 }
817 }
818 }
819 }
820 }
821
822 #[cfg(feature = "bitvec")]
823 impl<'a, O, T> InputTakeAtPosition for &'a BitSlice<O, T>
824 where
825 O: BitOrder,
826 T: 'a + BitStore,
827 {
828 type Item = bool;
829
split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,830 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
831 where
832 P: Fn(Self::Item) -> bool,
833 {
834 self
835 .iter()
836 .copied()
837 .position(predicate)
838 .map(|i| self.split_at(i))
839 .ok_or_else(|| Err::Incomplete(Needed::new(1)))
840 }
841
split_at_position1<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,842 fn split_at_position1<P, E: ParseError<Self>>(
843 &self,
844 predicate: P,
845 e: ErrorKind,
846 ) -> IResult<Self, Self, E>
847 where
848 P: Fn(Self::Item) -> bool,
849 {
850 match self.iter().copied().position(predicate) {
851 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
852 Some(i) => Ok(self.split_at(i)),
853 None => Err(Err::Incomplete(Needed::new(1))),
854 }
855 }
856
split_at_position_complete<P, E: ParseError<Self>>( &self, predicate: P, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,857 fn split_at_position_complete<P, E: ParseError<Self>>(
858 &self,
859 predicate: P,
860 ) -> IResult<Self, Self, E>
861 where
862 P: Fn(Self::Item) -> bool,
863 {
864 self
865 .iter()
866 .position(|b| predicate(*b))
867 .map(|i| self.split_at(i))
868 .or_else(|| Some((self, Self::default())))
869 .ok_or_else(|| unreachable!())
870 }
871
split_at_position1_complete<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool,872 fn split_at_position1_complete<P, E: ParseError<Self>>(
873 &self,
874 predicate: P,
875 e: ErrorKind,
876 ) -> IResult<Self, Self, E>
877 where
878 P: Fn(Self::Item) -> bool,
879 {
880 match self.iter().copied().position(predicate) {
881 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
882 Some(i) => Ok(self.split_at(i)),
883 None => {
884 if self.is_empty() {
885 Err(Err::Error(E::from_error_kind(self, e)))
886 } else {
887 Ok((self, Self::default()))
888 }
889 }
890 }
891 }
892 }
893
894 /// Indicates wether a comparison was successful, an error, or
895 /// if more data was needed
896 #[derive(Debug, PartialEq)]
897 pub enum CompareResult {
898 /// Comparison was successful
899 Ok,
900 /// We need more data to be sure
901 Incomplete,
902 /// Comparison failed
903 Error,
904 }
905
906 /// Abstracts comparison operations
907 pub trait Compare<T> {
908 /// Compares self to another value for equality
compare(&self, t: T) -> CompareResult909 fn compare(&self, t: T) -> CompareResult;
910 /// Compares self to another value for equality
911 /// independently of the case.
912 ///
913 /// Warning: for `&str`, the comparison is done
914 /// by lowercasing both strings and comparing
915 /// the result. This is a temporary solution until
916 /// a better one appears
compare_no_case(&self, t: T) -> CompareResult917 fn compare_no_case(&self, t: T) -> CompareResult;
918 }
919
lowercase_byte(c: u8) -> u8920 fn lowercase_byte(c: u8) -> u8 {
921 match c {
922 b'A'..=b'Z' => c - b'A' + b'a',
923 _ => c,
924 }
925 }
926
927 impl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {
928 #[inline(always)]
compare(&self, t: &'b [u8]) -> CompareResult929 fn compare(&self, t: &'b [u8]) -> CompareResult {
930 let pos = self.iter().zip(t.iter()).position(|(a, b)| a != b);
931
932 match pos {
933 Some(_) => CompareResult::Error,
934 None => {
935 if self.len() >= t.len() {
936 CompareResult::Ok
937 } else {
938 CompareResult::Incomplete
939 }
940 }
941 }
942
943 /*
944 let len = self.len();
945 let blen = t.len();
946 let m = if len < blen { len } else { blen };
947 let reduced = &self[..m];
948 let b = &t[..m];
949
950 if reduced != b {
951 CompareResult::Error
952 } else if m < blen {
953 CompareResult::Incomplete
954 } else {
955 CompareResult::Ok
956 }
957 */
958 }
959
960 #[inline(always)]
compare_no_case(&self, t: &'b [u8]) -> CompareResult961 fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
962 if self
963 .iter()
964 .zip(t)
965 .any(|(a, b)| lowercase_byte(*a) != lowercase_byte(*b))
966 {
967 CompareResult::Error
968 } else if self.len() < t.len() {
969 CompareResult::Incomplete
970 } else {
971 CompareResult::Ok
972 }
973 }
974 }
975
976 impl<
977 T: InputLength + InputIter<Item = u8> + InputTake + UnspecializedInput,
978 O: InputLength + InputIter<Item = u8> + InputTake,
979 > Compare<O> for T
980 {
981 #[inline(always)]
compare(&self, t: O) -> CompareResult982 fn compare(&self, t: O) -> CompareResult {
983 let pos = self
984 .iter_elements()
985 .zip(t.iter_elements())
986 .position(|(a, b)| a != b);
987
988 match pos {
989 Some(_) => CompareResult::Error,
990 None => {
991 if self.input_len() >= t.input_len() {
992 CompareResult::Ok
993 } else {
994 CompareResult::Incomplete
995 }
996 }
997 }
998 }
999
1000 #[inline(always)]
compare_no_case(&self, t: O) -> CompareResult1001 fn compare_no_case(&self, t: O) -> CompareResult {
1002 if self
1003 .iter_elements()
1004 .zip(t.iter_elements())
1005 .any(|(a, b)| lowercase_byte(a) != lowercase_byte(b))
1006 {
1007 CompareResult::Error
1008 } else if self.input_len() < t.input_len() {
1009 CompareResult::Incomplete
1010 } else {
1011 CompareResult::Ok
1012 }
1013 }
1014 }
1015
1016 impl<'a, 'b> Compare<&'b str> for &'a [u8] {
1017 #[inline(always)]
compare(&self, t: &'b str) -> CompareResult1018 fn compare(&self, t: &'b str) -> CompareResult {
1019 self.compare(AsBytes::as_bytes(t))
1020 }
1021 #[inline(always)]
compare_no_case(&self, t: &'b str) -> CompareResult1022 fn compare_no_case(&self, t: &'b str) -> CompareResult {
1023 self.compare_no_case(AsBytes::as_bytes(t))
1024 }
1025 }
1026
1027 impl<'a, 'b> Compare<&'b str> for &'a str {
1028 #[inline(always)]
compare(&self, t: &'b str) -> CompareResult1029 fn compare(&self, t: &'b str) -> CompareResult {
1030 self.as_bytes().compare(t.as_bytes())
1031 }
1032
1033 //FIXME: this version is too simple and does not use the current locale
1034 #[inline(always)]
compare_no_case(&self, t: &'b str) -> CompareResult1035 fn compare_no_case(&self, t: &'b str) -> CompareResult {
1036 let pos = self
1037 .chars()
1038 .zip(t.chars())
1039 .position(|(a, b)| a.to_lowercase().ne(b.to_lowercase()));
1040
1041 match pos {
1042 Some(_) => CompareResult::Error,
1043 None => {
1044 if self.len() >= t.len() {
1045 CompareResult::Ok
1046 } else {
1047 CompareResult::Incomplete
1048 }
1049 }
1050 }
1051 }
1052 }
1053
1054 #[cfg(feature = "bitvec")]
1055 impl<'a, 'b, O1, O2, T1, T2> Compare<&'b BitSlice<O2, T2>> for &'a BitSlice<O1, T1>
1056 where
1057 O1: BitOrder,
1058 O2: BitOrder,
1059 T1: 'a + BitStore,
1060 T2: 'a + BitStore,
1061 {
1062 #[inline]
compare(&self, other: &'b BitSlice<O2, T2>) -> CompareResult1063 fn compare(&self, other: &'b BitSlice<O2, T2>) -> CompareResult {
1064 match self.iter().zip(other.iter()).position(|(a, b)| a != b) {
1065 Some(_) => CompareResult::Error,
1066 None => {
1067 if self.len() >= other.len() {
1068 CompareResult::Ok
1069 } else {
1070 CompareResult::Incomplete
1071 }
1072 }
1073 }
1074 }
1075
1076 #[inline(always)]
compare_no_case(&self, other: &'b BitSlice<O2, T2>) -> CompareResult1077 fn compare_no_case(&self, other: &'b BitSlice<O2, T2>) -> CompareResult {
1078 self.compare(other)
1079 }
1080 }
1081
1082 /// Look for a token in self
1083 pub trait FindToken<T> {
1084 /// Returns true if self contains the token
find_token(&self, token: T) -> bool1085 fn find_token(&self, token: T) -> bool;
1086 }
1087
1088 impl<'a> FindToken<u8> for &'a [u8] {
find_token(&self, token: u8) -> bool1089 fn find_token(&self, token: u8) -> bool {
1090 memchr::memchr(token, self).is_some()
1091 }
1092 }
1093
1094 impl<'a> FindToken<u8> for &'a str {
find_token(&self, token: u8) -> bool1095 fn find_token(&self, token: u8) -> bool {
1096 self.as_bytes().find_token(token)
1097 }
1098 }
1099
1100 impl<'a, 'b> FindToken<&'a u8> for &'b [u8] {
find_token(&self, token: &u8) -> bool1101 fn find_token(&self, token: &u8) -> bool {
1102 self.find_token(*token)
1103 }
1104 }
1105
1106 impl<'a, 'b> FindToken<&'a u8> for &'b str {
find_token(&self, token: &u8) -> bool1107 fn find_token(&self, token: &u8) -> bool {
1108 self.as_bytes().find_token(token)
1109 }
1110 }
1111
1112 impl<'a> FindToken<char> for &'a [u8] {
find_token(&self, token: char) -> bool1113 fn find_token(&self, token: char) -> bool {
1114 self.iter().any(|i| *i == token as u8)
1115 }
1116 }
1117
1118 impl<'a> FindToken<char> for &'a str {
find_token(&self, token: char) -> bool1119 fn find_token(&self, token: char) -> bool {
1120 self.chars().any(|i| i == token)
1121 }
1122 }
1123
1124 #[cfg(feature = "bitvec")]
1125 impl<'a, O, T> FindToken<bool> for &'a BitSlice<O, T>
1126 where
1127 O: BitOrder,
1128 T: 'a + BitStore,
1129 {
find_token(&self, token: bool) -> bool1130 fn find_token(&self, token: bool) -> bool {
1131 self.iter().copied().any(|i| i == token)
1132 }
1133 }
1134
1135 #[cfg(feature = "bitvec")]
1136 impl<'a, O, T> FindToken<(usize, bool)> for &'a BitSlice<O, T>
1137 where
1138 O: BitOrder,
1139 T: 'a + BitStore,
1140 {
find_token(&self, token: (usize, bool)) -> bool1141 fn find_token(&self, token: (usize, bool)) -> bool {
1142 self.iter().copied().enumerate().any(|i| i == token)
1143 }
1144 }
1145
1146 /// Look for a substring in self
1147 pub trait FindSubstring<T> {
1148 /// Returns the byte position of the substring if it is found
find_substring(&self, substr: T) -> Option<usize>1149 fn find_substring(&self, substr: T) -> Option<usize>;
1150 }
1151
1152 impl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {
find_substring(&self, substr: &'b [u8]) -> Option<usize>1153 fn find_substring(&self, substr: &'b [u8]) -> Option<usize> {
1154 if substr.len() > self.len() {
1155 return None;
1156 }
1157
1158 let (&substr_first, substr_rest) = match substr.split_first() {
1159 Some(split) => split,
1160 // an empty substring is found at position 0
1161 // This matches the behavior of str.find("").
1162 None => return Some(0),
1163 };
1164
1165 if substr_rest.is_empty() {
1166 return memchr::memchr(substr_first, self);
1167 }
1168
1169 let mut offset = 0;
1170 let haystack = &self[..self.len() - substr_rest.len()];
1171
1172 while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {
1173 offset += position;
1174 let next_offset = offset + 1;
1175 if &self[next_offset..][..substr_rest.len()] == substr_rest {
1176 return Some(offset);
1177 }
1178
1179 offset = next_offset;
1180 }
1181
1182 None
1183 }
1184 }
1185
1186 impl<'a, 'b> FindSubstring<&'b str> for &'a [u8] {
find_substring(&self, substr: &'b str) -> Option<usize>1187 fn find_substring(&self, substr: &'b str) -> Option<usize> {
1188 self.find_substring(AsBytes::as_bytes(substr))
1189 }
1190 }
1191
1192 impl<'a, 'b> FindSubstring<&'b str> for &'a str {
1193 //returns byte index
find_substring(&self, substr: &'b str) -> Option<usize>1194 fn find_substring(&self, substr: &'b str) -> Option<usize> {
1195 self.find(substr)
1196 }
1197 }
1198
1199 #[cfg(feature = "bitvec")]
1200 impl<'a, 'b, O1, O2, T1, T2> FindSubstring<&'b BitSlice<O2, T2>> for &'a BitSlice<O1, T1>
1201 where
1202 O1: BitOrder,
1203 O2: BitOrder,
1204 T1: 'a + BitStore,
1205 T2: 'b + BitStore,
1206 {
find_substring(&self, substr: &'b BitSlice<O2, T2>) -> Option<usize>1207 fn find_substring(&self, substr: &'b BitSlice<O2, T2>) -> Option<usize> {
1208 if substr.len() > self.len() {
1209 return None;
1210 }
1211
1212 if substr.is_empty() {
1213 return Some(0);
1214 }
1215
1216 self
1217 .windows(substr.len())
1218 .position(|window| window == substr)
1219 }
1220 }
1221
1222 /// Used to integrate `str`'s `parse()` method
1223 pub trait ParseTo<R> {
1224 /// Succeeds if `parse()` succeeded. The byte slice implementation
1225 /// will first convert it to a `&str`, then apply the `parse()` function
parse_to(&self) -> Option<R>1226 fn parse_to(&self) -> Option<R>;
1227 }
1228
1229 impl<'a, R: FromStr> ParseTo<R> for &'a [u8] {
parse_to(&self) -> Option<R>1230 fn parse_to(&self) -> Option<R> {
1231 from_utf8(self).ok().and_then(|s| s.parse().ok())
1232 }
1233 }
1234
1235 impl<'a, R: FromStr> ParseTo<R> for &'a str {
parse_to(&self) -> Option<R>1236 fn parse_to(&self) -> Option<R> {
1237 self.parse().ok()
1238 }
1239 }
1240
1241 /// Slicing operations using ranges.
1242 ///
1243 /// This trait is loosely based on
1244 /// `Index`, but can actually return
1245 /// something else than a `&[T]` or `&str`
1246 pub trait Slice<R> {
1247 /// Slices self according to the range argument
slice(&self, range: R) -> Self1248 fn slice(&self, range: R) -> Self;
1249 }
1250
1251 macro_rules! impl_fn_slice {
1252 ( $ty:ty ) => {
1253 fn slice(&self, range: $ty) -> Self {
1254 &self[range]
1255 }
1256 };
1257 }
1258
1259 macro_rules! slice_range_impl {
1260 ( BitSlice, $ty:ty ) => {
1261 impl<'a, O, T> Slice<$ty> for &'a BitSlice<O, T>
1262 where
1263 O: BitOrder,
1264 T: BitStore,
1265 {
1266 impl_fn_slice!($ty);
1267 }
1268 };
1269 ( [ $for_type:ident ], $ty:ty ) => {
1270 impl<'a, $for_type> Slice<$ty> for &'a [$for_type] {
1271 impl_fn_slice!($ty);
1272 }
1273 };
1274 ( $for_type:ty, $ty:ty ) => {
1275 impl<'a> Slice<$ty> for &'a $for_type {
1276 impl_fn_slice!($ty);
1277 }
1278 };
1279 }
1280
1281 macro_rules! slice_ranges_impl {
1282 ( BitSlice ) => {
1283 slice_range_impl! {BitSlice, Range<usize>}
1284 slice_range_impl! {BitSlice, RangeTo<usize>}
1285 slice_range_impl! {BitSlice, RangeFrom<usize>}
1286 slice_range_impl! {BitSlice, RangeFull}
1287 };
1288 ( [ $for_type:ident ] ) => {
1289 slice_range_impl! {[$for_type], Range<usize>}
1290 slice_range_impl! {[$for_type], RangeTo<usize>}
1291 slice_range_impl! {[$for_type], RangeFrom<usize>}
1292 slice_range_impl! {[$for_type], RangeFull}
1293 };
1294 ( $for_type:ty ) => {
1295 slice_range_impl! {$for_type, Range<usize>}
1296 slice_range_impl! {$for_type, RangeTo<usize>}
1297 slice_range_impl! {$for_type, RangeFrom<usize>}
1298 slice_range_impl! {$for_type, RangeFull}
1299 };
1300 }
1301
1302 slice_ranges_impl! {str}
1303 slice_ranges_impl! {[T]}
1304
1305 #[cfg(feature = "bitvec")]
1306 slice_ranges_impl! {BitSlice}
1307
1308 macro_rules! array_impls {
1309 ($($N:expr)+) => {
1310 $(
1311 impl InputLength for [u8; $N] {
1312 #[inline]
1313 fn input_len(&self) -> usize {
1314 self.len()
1315 }
1316 }
1317
1318 impl<'a> InputLength for &'a [u8; $N] {
1319 #[inline]
1320 fn input_len(&self) -> usize {
1321 self.len()
1322 }
1323 }
1324
1325 impl<'a> InputIter for &'a [u8; $N] {
1326 type Item = u8;
1327 type Iter = Enumerate<Self::IterElem>;
1328 type IterElem = Copied<Iter<'a, u8>>;
1329
1330 fn iter_indices(&self) -> Self::Iter {
1331 (&self[..]).iter_indices()
1332 }
1333
1334 fn iter_elements(&self) -> Self::IterElem {
1335 (&self[..]).iter_elements()
1336 }
1337
1338 fn position<P>(&self, predicate: P) -> Option<usize>
1339 where P: Fn(Self::Item) -> bool {
1340 (&self[..]).position(predicate)
1341 }
1342
1343 fn slice_index(&self, count: usize) -> Result<usize, Needed> {
1344 (&self[..]).slice_index(count)
1345 }
1346 }
1347
1348 impl<'a> Compare<[u8; $N]> for &'a [u8] {
1349 #[inline(always)]
1350 fn compare(&self, t: [u8; $N]) -> CompareResult {
1351 self.compare(&t[..])
1352 }
1353
1354 #[inline(always)]
1355 fn compare_no_case(&self, t: [u8;$N]) -> CompareResult {
1356 self.compare_no_case(&t[..])
1357 }
1358 }
1359
1360 impl<'a,'b> Compare<&'b [u8; $N]> for &'a [u8] {
1361 #[inline(always)]
1362 fn compare(&self, t: &'b [u8; $N]) -> CompareResult {
1363 self.compare(&t[..])
1364 }
1365
1366 #[inline(always)]
1367 fn compare_no_case(&self, t: &'b [u8;$N]) -> CompareResult {
1368 self.compare_no_case(&t[..])
1369 }
1370 }
1371
1372 impl FindToken<u8> for [u8; $N] {
1373 fn find_token(&self, token: u8) -> bool {
1374 memchr::memchr(token, &self[..]).is_some()
1375 }
1376 }
1377
1378 impl<'a> FindToken<&'a u8> for [u8; $N] {
1379 fn find_token(&self, token: &u8) -> bool {
1380 self.find_token(*token)
1381 }
1382 }
1383 )+
1384 };
1385 }
1386
1387 array_impls! {
1388 0 1 2 3 4 5 6 7 8 9
1389 10 11 12 13 14 15 16 17 18 19
1390 20 21 22 23 24 25 26 27 28 29
1391 30 31 32
1392 }
1393
1394 /// Abstracts something which can extend an `Extend`.
1395 /// Used to build modified input slices in `escaped_transform`
1396 pub trait ExtendInto {
1397 /// The current input type is a sequence of that `Item` type.
1398 ///
1399 /// Example: `u8` for `&[u8]` or `char` for `&str`
1400 type Item;
1401
1402 /// The type that will be produced
1403 type Extender;
1404
1405 /// Create a new `Extend` of the correct type
new_builder(&self) -> Self::Extender1406 fn new_builder(&self) -> Self::Extender;
1407 /// Accumulate the input into an accumulator
extend_into(&self, acc: &mut Self::Extender)1408 fn extend_into(&self, acc: &mut Self::Extender);
1409 }
1410
1411 #[cfg(feature = "alloc")]
1412 impl ExtendInto for [u8] {
1413 type Item = u8;
1414 type Extender = Vec<u8>;
1415
1416 #[inline]
new_builder(&self) -> Vec<u8>1417 fn new_builder(&self) -> Vec<u8> {
1418 Vec::new()
1419 }
1420 #[inline]
extend_into(&self, acc: &mut Vec<u8>)1421 fn extend_into(&self, acc: &mut Vec<u8>) {
1422 acc.extend(self.iter().cloned());
1423 }
1424 }
1425
1426 #[cfg(feature = "alloc")]
1427 impl ExtendInto for &[u8] {
1428 type Item = u8;
1429 type Extender = Vec<u8>;
1430
1431 #[inline]
new_builder(&self) -> Vec<u8>1432 fn new_builder(&self) -> Vec<u8> {
1433 Vec::new()
1434 }
1435 #[inline]
extend_into(&self, acc: &mut Vec<u8>)1436 fn extend_into(&self, acc: &mut Vec<u8>) {
1437 acc.extend_from_slice(self);
1438 }
1439 }
1440
1441 #[cfg(feature = "alloc")]
1442 impl ExtendInto for str {
1443 type Item = char;
1444 type Extender = String;
1445
1446 #[inline]
new_builder(&self) -> String1447 fn new_builder(&self) -> String {
1448 String::new()
1449 }
1450 #[inline]
extend_into(&self, acc: &mut String)1451 fn extend_into(&self, acc: &mut String) {
1452 acc.push_str(self);
1453 }
1454 }
1455
1456 #[cfg(feature = "alloc")]
1457 impl ExtendInto for &str {
1458 type Item = char;
1459 type Extender = String;
1460
1461 #[inline]
new_builder(&self) -> String1462 fn new_builder(&self) -> String {
1463 String::new()
1464 }
1465 #[inline]
extend_into(&self, acc: &mut String)1466 fn extend_into(&self, acc: &mut String) {
1467 acc.push_str(self);
1468 }
1469 }
1470
1471 #[cfg(feature = "alloc")]
1472 impl ExtendInto for char {
1473 type Item = char;
1474 type Extender = String;
1475
1476 #[inline]
new_builder(&self) -> String1477 fn new_builder(&self) -> String {
1478 String::new()
1479 }
1480 #[inline]
extend_into(&self, acc: &mut String)1481 fn extend_into(&self, acc: &mut String) {
1482 acc.push(*self);
1483 }
1484 }
1485
1486 #[cfg(all(feature = "alloc", feature = "bitvec"))]
1487 impl<O, T> ExtendInto for BitSlice<O, T>
1488 where
1489 O: BitOrder,
1490 T: BitStore,
1491 {
1492 type Item = bool;
1493 type Extender = BitVec<O, T>;
1494
1495 #[inline]
new_builder(&self) -> BitVec<O, T>1496 fn new_builder(&self) -> BitVec<O, T> {
1497 BitVec::new()
1498 }
1499
1500 #[inline]
extend_into(&self, acc: &mut Self::Extender)1501 fn extend_into(&self, acc: &mut Self::Extender) {
1502 acc.extend(self.iter());
1503 }
1504 }
1505
1506 #[cfg(all(feature = "alloc", feature = "bitvec"))]
1507 impl<'a, O, T> ExtendInto for &'a BitSlice<O, T>
1508 where
1509 O: BitOrder,
1510 T: 'a + BitStore,
1511 {
1512 type Item = bool;
1513 type Extender = BitVec<O, T>;
1514
1515 #[inline]
new_builder(&self) -> BitVec<O, T>1516 fn new_builder(&self) -> BitVec<O, T> {
1517 BitVec::new()
1518 }
1519
1520 #[inline]
extend_into(&self, acc: &mut Self::Extender)1521 fn extend_into(&self, acc: &mut Self::Extender) {
1522 acc.extend(self.iter());
1523 }
1524 }
1525
1526 /// Helper trait to convert numbers to usize.
1527 ///
1528 /// By default, usize implements `From<u8>` and `From<u16>` but not
1529 /// `From<u32>` and `From<u64>` because that would be invalid on some
1530 /// platforms. This trait implements the conversion for platforms
1531 /// with 32 and 64 bits pointer platforms
1532 pub trait ToUsize {
1533 /// converts self to usize
to_usize(&self) -> usize1534 fn to_usize(&self) -> usize;
1535 }
1536
1537 impl ToUsize for u8 {
1538 #[inline]
to_usize(&self) -> usize1539 fn to_usize(&self) -> usize {
1540 *self as usize
1541 }
1542 }
1543
1544 impl ToUsize for u16 {
1545 #[inline]
to_usize(&self) -> usize1546 fn to_usize(&self) -> usize {
1547 *self as usize
1548 }
1549 }
1550
1551 impl ToUsize for usize {
1552 #[inline]
to_usize(&self) -> usize1553 fn to_usize(&self) -> usize {
1554 *self
1555 }
1556 }
1557
1558 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
1559 impl ToUsize for u32 {
1560 #[inline]
to_usize(&self) -> usize1561 fn to_usize(&self) -> usize {
1562 *self as usize
1563 }
1564 }
1565
1566 #[cfg(target_pointer_width = "64")]
1567 impl ToUsize for u64 {
1568 #[inline]
to_usize(&self) -> usize1569 fn to_usize(&self) -> usize {
1570 *self as usize
1571 }
1572 }
1573
1574 /// Equivalent From implementation to avoid orphan rules in bits parsers
1575 pub trait ErrorConvert<E> {
1576 /// Transform to another error type
convert(self) -> E1577 fn convert(self) -> E;
1578 }
1579
1580 impl<I> ErrorConvert<(I, ErrorKind)> for ((I, usize), ErrorKind) {
convert(self) -> (I, ErrorKind)1581 fn convert(self) -> (I, ErrorKind) {
1582 ((self.0).0, self.1)
1583 }
1584 }
1585
1586 impl<I> ErrorConvert<((I, usize), ErrorKind)> for (I, ErrorKind) {
convert(self) -> ((I, usize), ErrorKind)1587 fn convert(self) -> ((I, usize), ErrorKind) {
1588 ((self.0, 0), self.1)
1589 }
1590 }
1591
1592 use crate::error;
1593 impl<I> ErrorConvert<error::Error<I>> for error::Error<(I, usize)> {
convert(self) -> error::Error<I>1594 fn convert(self) -> error::Error<I> {
1595 error::Error {
1596 input: self.input.0,
1597 code: self.code,
1598 }
1599 }
1600 }
1601
1602 impl<I> ErrorConvert<error::Error<(I, usize)>> for error::Error<I> {
convert(self) -> error::Error<(I, usize)>1603 fn convert(self) -> error::Error<(I, usize)> {
1604 error::Error {
1605 input: (self.input, 0),
1606 code: self.code,
1607 }
1608 }
1609 }
1610
1611 #[cfg(feature = "alloc")]
1612 #[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
1613 impl<I> ErrorConvert<error::VerboseError<I>> for error::VerboseError<(I, usize)> {
convert(self) -> error::VerboseError<I>1614 fn convert(self) -> error::VerboseError<I> {
1615 error::VerboseError {
1616 errors: self.errors.into_iter().map(|(i, e)| (i.0, e)).collect(),
1617 }
1618 }
1619 }
1620
1621 #[cfg(feature = "alloc")]
1622 #[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
1623 impl<I> ErrorConvert<error::VerboseError<(I, usize)>> for error::VerboseError<I> {
convert(self) -> error::VerboseError<(I, usize)>1624 fn convert(self) -> error::VerboseError<(I, usize)> {
1625 error::VerboseError {
1626 errors: self.errors.into_iter().map(|(i, e)| ((i, 0), e)).collect(),
1627 }
1628 }
1629 }
1630
1631 #[cfg(test)]
1632 mod tests {
1633 use super::*;
1634
1635 #[test]
test_offset_u8()1636 fn test_offset_u8() {
1637 let s = b"abcd123";
1638 let a = &s[..];
1639 let b = &a[2..];
1640 let c = &a[..4];
1641 let d = &a[3..5];
1642 assert_eq!(a.offset(b), 2);
1643 assert_eq!(a.offset(c), 0);
1644 assert_eq!(a.offset(d), 3);
1645 }
1646
1647 #[test]
test_offset_str()1648 fn test_offset_str() {
1649 let s = "abcřèÂßÇd123";
1650 let a = &s[..];
1651 let b = &a[7..];
1652 let c = &a[..5];
1653 let d = &a[5..9];
1654 assert_eq!(a.offset(b), 7);
1655 assert_eq!(a.offset(c), 0);
1656 assert_eq!(a.offset(d), 5);
1657 }
1658 }
1659