1use core::iter::Enumerate;
3use core::str::CharIndices;
4
5use crate::error::{ErrorKind, ParseError};
6use crate::internal::{Err, IResult, Needed};
7use crate::lib::std::iter::Copied;
8use crate::lib::std::ops::{
9 Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
10};
11use crate::lib::std::slice::Iter;
12use crate::lib::std::str::from_utf8;
13use crate::lib::std::str::Chars;
14use crate::lib::std::str::FromStr;
15use crate::IsStreaming;
16use crate::Mode;
17
18#[cfg(feature = "alloc")]
19use crate::lib::std::string::String;
20#[cfg(feature = "alloc")]
21use crate::lib::std::vec::Vec;
22
23pub trait Input: Clone + Sized {
25 type Item;
29
30 type Iter: Iterator<Item = Self::Item>;
32
33 type IterIndices: Iterator<Item = (usize, Self::Item)>;
37
38 fn input_len(&self) -> usize;
41
42 fn take(&self, index: usize) -> Self;
44 fn take_from(&self, index: usize) -> Self;
46 fn take_split(&self, index: usize) -> (Self, Self);
48
49 fn position<P>(&self, predicate: P) -> Option<usize>
51 where
52 P: Fn(Self::Item) -> bool;
53
54 fn iter_elements(&self) -> Self::Iter;
56 fn iter_indices(&self) -> Self::IterIndices;
58
59 fn slice_index(&self, count: usize) -> Result<usize, Needed>;
61
62 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
67 where
68 P: Fn(Self::Item) -> bool,
69 {
70 match self.position(predicate) {
71 Some(n) => Ok(self.take_split(n)),
72 None => Err(Err::Incomplete(Needed::new(1))),
73 }
74 }
75
76 fn split_at_position1<P, E: ParseError<Self>>(
83 &self,
84 predicate: P,
85 e: ErrorKind,
86 ) -> IResult<Self, Self, E>
87 where
88 P: Fn(Self::Item) -> bool,
89 {
90 match self.position(predicate) {
91 Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
92 Some(n) => Ok(self.take_split(n)),
93 None => Err(Err::Incomplete(Needed::new(1))),
94 }
95 }
96
97 fn split_at_position_complete<P, E: ParseError<Self>>(
102 &self,
103 predicate: P,
104 ) -> IResult<Self, Self, E>
105 where
106 P: Fn(Self::Item) -> bool,
107 {
108 match self.split_at_position(predicate) {
109 Err(Err::Incomplete(_)) => Ok(self.take_split(self.input_len())),
110 res => res,
111 }
112 }
113
114 fn split_at_position1_complete<P, E: ParseError<Self>>(
121 &self,
122 predicate: P,
123 e: ErrorKind,
124 ) -> IResult<Self, Self, E>
125 where
126 P: Fn(Self::Item) -> bool,
127 {
128 match self.split_at_position1(predicate, e) {
129 Err(Err::Incomplete(_)) => {
130 if self.input_len() == 0 {
131 Err(Err::Error(E::from_error_kind(self.clone(), e)))
132 } else {
133 Ok(self.take_split(self.input_len()))
134 }
135 }
136 res => res,
137 }
138 }
139
140 fn split_at_position_mode<OM: crate::OutputMode, P, E: ParseError<Self>>(
142 &self,
143 predicate: P,
144 ) -> crate::PResult<OM, Self, Self, E>
145 where
146 P: Fn(Self::Item) -> bool,
147 {
148 match self.position(predicate) {
149 Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),
150 None => {
151 if OM::Incomplete::is_streaming() {
152 Err(Err::Incomplete(Needed::new(1)))
153 } else {
154 let len = self.input_len();
155 Ok((self.take_from(len), OM::Output::bind(|| self.take(len))))
156 }
157 }
158 }
159 }
160
161 fn split_at_position_mode1<OM: crate::OutputMode, P, E: ParseError<Self>>(
163 &self,
164 predicate: P,
165 e: ErrorKind,
166 ) -> crate::PResult<OM, Self, Self, E>
167 where
168 P: Fn(Self::Item) -> bool,
169 {
170 match self.position(predicate) {
171 Some(0) => Err(Err::Error(OM::Error::bind(|| {
172 E::from_error_kind(self.clone(), e)
173 }))),
174 Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),
175 None => {
176 if OM::Incomplete::is_streaming() {
177 Err(Err::Incomplete(Needed::new(1)))
178 } else {
179 let len = self.input_len();
180 if len == 0 {
181 Err(Err::Error(OM::Error::bind(|| {
182 E::from_error_kind(self.clone(), e)
183 })))
184 } else {
185 Ok((self.take_from(len), OM::Output::bind(|| self.take(len))))
186 }
187 }
188 }
189 }
190 }
191}
192
193impl<'a> Input for &'a [u8] {
194 type Item = u8;
195 type Iter = Copied<Iter<'a, u8>>;
196 type IterIndices = Enumerate<Self::Iter>;
197
198 fn input_len(&self) -> usize {
199 self.len()
200 }
201
202 #[inline]
203 fn take(&self, index: usize) -> Self {
204 &self[0..index]
205 }
206
207 fn take_from(&self, index: usize) -> Self {
208 &self[index..]
209 }
210 #[inline]
211 fn take_split(&self, index: usize) -> (Self, Self) {
212 let (prefix, suffix) = self.split_at(index);
213 (suffix, prefix)
214 }
215
216 #[inline]
217 fn position<P>(&self, predicate: P) -> Option<usize>
218 where
219 P: Fn(Self::Item) -> bool,
220 {
221 self.iter().position(|b| predicate(*b))
222 }
223
224 #[inline]
225 fn iter_elements(&self) -> Self::Iter {
226 self.iter().copied()
227 }
228
229 #[inline]
230 fn iter_indices(&self) -> Self::IterIndices {
231 self.iter_elements().enumerate()
232 }
233
234 #[inline]
235 fn slice_index(&self, count: usize) -> Result<usize, Needed> {
236 if self.len() >= count {
237 Ok(count)
238 } else {
239 Err(Needed::new(count - self.len()))
240 }
241 }
242
243 #[inline(always)]
244 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
245 where
246 P: Fn(Self::Item) -> bool,
247 {
248 match self.iter().position(|c| predicate(*c)) {
249 Some(i) => Ok(self.take_split(i)),
250 None => Err(Err::Incomplete(Needed::new(1))),
251 }
252 }
253
254 #[inline(always)]
255 fn split_at_position1<P, E: ParseError<Self>>(
256 &self,
257 predicate: P,
258 e: ErrorKind,
259 ) -> IResult<Self, Self, E>
260 where
261 P: Fn(Self::Item) -> bool,
262 {
263 match self.iter().position(|c| predicate(*c)) {
264 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
265 Some(i) => Ok(self.take_split(i)),
266 None => Err(Err::Incomplete(Needed::new(1))),
267 }
268 }
269
270 fn split_at_position_complete<P, E: ParseError<Self>>(
271 &self,
272 predicate: P,
273 ) -> IResult<Self, Self, E>
274 where
275 P: Fn(Self::Item) -> bool,
276 {
277 match self.iter().position(|c| predicate(*c)) {
278 Some(i) => Ok(self.take_split(i)),
279 None => Ok(self.take_split(self.len())),
280 }
281 }
282
283 #[inline(always)]
284 fn split_at_position1_complete<P, E: ParseError<Self>>(
285 &self,
286 predicate: P,
287 e: ErrorKind,
288 ) -> IResult<Self, Self, E>
289 where
290 P: Fn(Self::Item) -> bool,
291 {
292 match self.iter().position(|c| predicate(*c)) {
293 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
294 Some(i) => Ok(self.take_split(i)),
295 None => {
296 if self.is_empty() {
297 Err(Err::Error(E::from_error_kind(self, e)))
298 } else {
299 Ok(self.take_split(self.len()))
300 }
301 }
302 }
303 }
304
305 #[inline(always)]
307 fn split_at_position_mode<OM: crate::OutputMode, P, E: ParseError<Self>>(
308 &self,
309 predicate: P,
310 ) -> crate::PResult<OM, Self, Self, E>
311 where
312 P: Fn(Self::Item) -> bool,
313 {
314 match self.iter().position(|c| predicate(*c)) {
315 Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),
316 None => {
317 if OM::Incomplete::is_streaming() {
318 Err(Err::Incomplete(Needed::new(1)))
319 } else {
320 Ok((
321 self.take_from(self.len()),
322 OM::Output::bind(|| self.take(self.len())),
323 ))
324 }
325 }
326 }
327 }
328
329 #[inline(always)]
331 fn split_at_position_mode1<OM: crate::OutputMode, P, E: ParseError<Self>>(
332 &self,
333 predicate: P,
334 e: ErrorKind,
335 ) -> crate::PResult<OM, Self, Self, E>
336 where
337 P: Fn(Self::Item) -> bool,
338 {
339 match self.iter().position(|c| predicate(*c)) {
340 Some(0) => Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e)))),
341 Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),
342 None => {
343 if OM::Incomplete::is_streaming() {
344 Err(Err::Incomplete(Needed::new(1)))
345 } else if self.is_empty() {
346 Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e))))
347 } else {
348 Ok((
349 self.take_from(self.len()),
350 OM::Output::bind(|| self.take(self.len())),
351 ))
352 }
353 }
354 }
355 }
356}
357
358impl<'a> Input for &'a str {
359 type Item = char;
360 type Iter = Chars<'a>;
361 type IterIndices = CharIndices<'a>;
362
363 fn input_len(&self) -> usize {
364 self.len()
365 }
366
367 #[inline]
368 fn take(&self, index: usize) -> Self {
369 &self[..index]
370 }
371
372 #[inline]
373 fn take_from(&self, index: usize) -> Self {
374 &self[index..]
375 }
376
377 #[inline]
379 fn take_split(&self, index: usize) -> (Self, Self) {
380 let (prefix, suffix) = self.split_at(index);
381 (suffix, prefix)
382 }
383
384 fn position<P>(&self, predicate: P) -> Option<usize>
385 where
386 P: Fn(Self::Item) -> bool,
387 {
388 self.find(predicate)
389 }
390
391 #[inline]
392 fn iter_elements(&self) -> Self::Iter {
393 self.chars()
394 }
395
396 #[inline]
397 fn iter_indices(&self) -> Self::IterIndices {
398 self.char_indices()
399 }
400
401 #[inline]
402 fn slice_index(&self, count: usize) -> Result<usize, Needed> {
403 let mut cnt = 0;
404 for (index, _) in self.char_indices() {
405 if cnt == count {
406 return Ok(index);
407 }
408 cnt += 1;
409 }
410 if cnt == count {
411 return Ok(self.len());
412 }
413 Err(Needed::Unknown)
414 }
415
416 #[inline(always)]
417 fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
418 where
419 P: Fn(Self::Item) -> bool,
420 {
421 match self.find(predicate) {
422 Some(i) => {
424 let (str1, str2) = self.split_at(i);
425 Ok((str2, str1))
426 }
427 None => Err(Err::Incomplete(Needed::new(1))),
428 }
429 }
430
431 #[inline(always)]
432 fn split_at_position1<P, E: ParseError<Self>>(
433 &self,
434 predicate: P,
435 e: ErrorKind,
436 ) -> IResult<Self, Self, E>
437 where
438 P: Fn(Self::Item) -> bool,
439 {
440 match self.find(predicate) {
441 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
442 Some(i) => {
444 let (str1, str2) = self.split_at(i);
445 Ok((str2, str1))
446 }
447 None => Err(Err::Incomplete(Needed::new(1))),
448 }
449 }
450
451 #[inline(always)]
452 fn split_at_position_complete<P, E: ParseError<Self>>(
453 &self,
454 predicate: P,
455 ) -> IResult<Self, Self, E>
456 where
457 P: Fn(Self::Item) -> bool,
458 {
459 match self.find(predicate) {
460 Some(i) => {
462 let (str1, str2) = self.split_at(i);
463 Ok((str2, str1))
464 }
465 None => Ok(self.split_at(0)),
466 }
467 }
468
469 #[inline(always)]
470 fn split_at_position1_complete<P, E: ParseError<Self>>(
471 &self,
472 predicate: P,
473 e: ErrorKind,
474 ) -> IResult<Self, Self, E>
475 where
476 P: Fn(Self::Item) -> bool,
477 {
478 match self.find(predicate) {
479 Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
480 Some(i) => {
482 let (str1, str2) = self.split_at(i);
483 Ok((str2, str1))
484 }
485 None => {
486 if self.is_empty() {
487 Err(Err::Error(E::from_error_kind(self, e)))
488 } else {
489 let (str1, str2) = self.split_at(self.len());
491 Ok((str2, str1))
492 }
493 }
494 }
495 }
496
497 #[inline(always)]
499 fn split_at_position_mode<OM: crate::OutputMode, P, E: ParseError<Self>>(
500 &self,
501 predicate: P,
502 ) -> crate::PResult<OM, Self, Self, E>
503 where
504 P: Fn(Self::Item) -> bool,
505 {
506 match self.find(predicate) {
507 Some(n) => unsafe {
508 Ok((
510 self.get_unchecked(n..),
511 OM::Output::bind(|| self.get_unchecked(..n)),
512 ))
513 },
514 None => {
515 if OM::Incomplete::is_streaming() {
516 Err(Err::Incomplete(Needed::new(1)))
517 } else {
518 unsafe {
520 Ok((
521 self.get_unchecked(self.len()..),
522 OM::Output::bind(|| self.get_unchecked(..self.len())),
523 ))
524 }
525 }
526 }
527 }
528 }
529
530 #[inline(always)]
532 fn split_at_position_mode1<OM: crate::OutputMode, P, E: ParseError<Self>>(
533 &self,
534 predicate: P,
535 e: ErrorKind,
536 ) -> crate::PResult<OM, Self, Self, E>
537 where
538 P: Fn(Self::Item) -> bool,
539 {
540 match self.find(predicate) {
541 Some(0) => Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e)))),
542 Some(n) => unsafe {
543 Ok((
545 self.get_unchecked(n..),
546 OM::Output::bind(|| self.get_unchecked(..n)),
547 ))
548 },
549 None => {
550 if OM::Incomplete::is_streaming() {
551 Err(Err::Incomplete(Needed::new(1)))
552 } else if self.is_empty() {
553 Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e))))
554 } else {
555 unsafe {
557 Ok((
558 self.get_unchecked(self.len()..),
559 OM::Output::bind(|| self.get_unchecked(..self.len())),
560 ))
561 }
562 }
563 }
564 }
565 }
566}
567
568pub trait Offset {
570 fn offset(&self, second: &Self) -> usize;
574}
575
576impl Offset for [u8] {
577 fn offset(&self, second: &Self) -> usize {
578 let fst = self.as_ptr();
579 let snd = second.as_ptr();
580
581 snd as usize - fst as usize
582 }
583}
584
585impl<'a> Offset for &'a [u8] {
586 fn offset(&self, second: &Self) -> usize {
587 let fst = self.as_ptr();
588 let snd = second.as_ptr();
589
590 snd as usize - fst as usize
591 }
592}
593
594impl Offset for str {
595 fn offset(&self, second: &Self) -> usize {
596 let fst = self.as_ptr();
597 let snd = second.as_ptr();
598
599 snd as usize - fst as usize
600 }
601}
602
603impl<'a> Offset for &'a str {
604 fn offset(&self, second: &Self) -> usize {
605 let fst = self.as_ptr();
606 let snd = second.as_ptr();
607
608 snd as usize - fst as usize
609 }
610}
611
612pub trait AsBytes {
614 fn as_bytes(&self) -> &[u8];
616}
617
618impl<'a> AsBytes for &'a str {
619 #[inline(always)]
620 fn as_bytes(&self) -> &[u8] {
621 (*self).as_bytes()
622 }
623}
624
625impl AsBytes for str {
626 #[inline(always)]
627 fn as_bytes(&self) -> &[u8] {
628 self.as_ref()
629 }
630}
631
632impl<'a> AsBytes for &'a [u8] {
633 #[inline(always)]
634 fn as_bytes(&self) -> &[u8] {
635 self
636 }
637}
638
639impl AsBytes for [u8] {
640 #[inline(always)]
641 fn as_bytes(&self) -> &[u8] {
642 self
643 }
644}
645
646impl<'a, const N: usize> AsBytes for &'a [u8; N] {
647 #[inline(always)]
648 fn as_bytes(&self) -> &[u8] {
649 self.as_slice()
650 }
651}
652
653impl<const N: usize> AsBytes for [u8; N] {
654 #[inline(always)]
655 fn as_bytes(&self) -> &[u8] {
656 self
657 }
658}
659
660#[allow(clippy::len_without_is_empty)]
662pub trait AsChar: Copy {
663 fn as_char(self) -> char;
665
666 fn is_alpha(self) -> bool;
671
672 fn is_alphanum(self) -> bool;
675 fn is_dec_digit(self) -> bool;
677 fn is_hex_digit(self) -> bool;
679 fn is_oct_digit(self) -> bool;
681 fn is_bin_digit(self) -> bool;
683 fn len(self) -> usize;
685 fn is_space(self) -> bool;
687 fn is_newline(self) -> bool;
689}
690
691impl AsChar for u8 {
692 #[inline]
693 fn as_char(self) -> char {
694 self as char
695 }
696 #[inline]
697 fn is_alpha(self) -> bool {
698 matches!(self, 0x41..=0x5A | 0x61..=0x7A)
699 }
700 #[inline]
701 fn is_alphanum(self) -> bool {
702 self.is_alpha() || self.is_dec_digit()
703 }
704 #[inline]
705 fn is_dec_digit(self) -> bool {
706 matches!(self, 0x30..=0x39)
707 }
708 #[inline]
709 fn is_hex_digit(self) -> bool {
710 matches!(self, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)
711 }
712 #[inline]
713 fn is_oct_digit(self) -> bool {
714 matches!(self, 0x30..=0x37)
715 }
716 #[inline]
717 fn is_bin_digit(self) -> bool {
718 matches!(self, 0x30..=0x31)
719 }
720 #[inline]
721 fn len(self) -> usize {
722 1
723 }
724 #[inline]
725 fn is_space(self) -> bool {
726 self == b' ' || self == b'\t'
727 }
728 fn is_newline(self) -> bool {
729 self == b'\n'
730 }
731}
732impl<'a> AsChar for &'a u8 {
733 #[inline]
734 fn as_char(self) -> char {
735 *self as char
736 }
737 #[inline]
738 fn is_alpha(self) -> bool {
739 matches!(*self, 0x41..=0x5A | 0x61..=0x7A)
740 }
741 #[inline]
742 fn is_alphanum(self) -> bool {
743 self.is_alpha() || self.is_dec_digit()
744 }
745 #[inline]
746 fn is_dec_digit(self) -> bool {
747 matches!(*self, 0x30..=0x39)
748 }
749 #[inline]
750 fn is_hex_digit(self) -> bool {
751 matches!(*self, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)
752 }
753 #[inline]
754 fn is_oct_digit(self) -> bool {
755 matches!(*self, 0x30..=0x37)
756 }
757 #[inline]
758 fn is_bin_digit(self) -> bool {
759 matches!(*self, 0x30..=0x31)
760 }
761 #[inline]
762 fn len(self) -> usize {
763 1
764 }
765 #[inline]
766 fn is_space(self) -> bool {
767 *self == b' ' || *self == b'\t'
768 }
769 fn is_newline(self) -> bool {
770 *self == b'\n'
771 }
772}
773
774impl AsChar for char {
775 #[inline]
776 fn as_char(self) -> char {
777 self
778 }
779 #[inline]
780 fn is_alpha(self) -> bool {
781 self.is_ascii_alphabetic()
782 }
783 #[inline]
784 fn is_alphanum(self) -> bool {
785 self.is_alpha() || self.is_dec_digit()
786 }
787 #[inline]
788 fn is_dec_digit(self) -> bool {
789 self.is_ascii_digit()
790 }
791 #[inline]
792 fn is_hex_digit(self) -> bool {
793 self.is_ascii_hexdigit()
794 }
795 #[inline]
796 fn is_oct_digit(self) -> bool {
797 self.is_digit(8)
798 }
799 #[inline]
800 fn is_bin_digit(self) -> bool {
801 self.is_digit(2)
802 }
803 #[inline]
804 fn len(self) -> usize {
805 self.len_utf8()
806 }
807 #[inline]
808 fn is_space(self) -> bool {
809 self == ' ' || self == '\t'
810 }
811 fn is_newline(self) -> bool {
812 self == '\n'
813 }
814}
815
816impl<'a> AsChar for &'a char {
817 #[inline]
818 fn as_char(self) -> char {
819 *self
820 }
821 #[inline]
822 fn is_alpha(self) -> bool {
823 self.is_ascii_alphabetic()
824 }
825 #[inline]
826 fn is_alphanum(self) -> bool {
827 self.is_alpha() || self.is_dec_digit()
828 }
829 #[inline]
830 fn is_dec_digit(self) -> bool {
831 self.is_ascii_digit()
832 }
833 #[inline]
834 fn is_hex_digit(self) -> bool {
835 self.is_ascii_hexdigit()
836 }
837 #[inline]
838 fn is_oct_digit(self) -> bool {
839 self.is_digit(8)
840 }
841 #[inline]
842 fn is_bin_digit(self) -> bool {
843 self.is_digit(2)
844 }
845 #[inline]
846 fn len(self) -> usize {
847 self.len_utf8()
848 }
849 #[inline]
850 fn is_space(self) -> bool {
851 *self == ' ' || *self == '\t'
852 }
853 fn is_newline(self) -> bool {
854 *self == '\n'
855 }
856}
857
858#[derive(Debug, Eq, PartialEq)]
861pub enum CompareResult {
862 Ok,
864 Incomplete,
866 Error,
868}
869
870pub trait Compare<T> {
872 fn compare(&self, t: T) -> CompareResult;
874 fn compare_no_case(&self, t: T) -> CompareResult;
882}
883
884fn lowercase_byte(c: u8) -> u8 {
885 match c {
886 b'A'..=b'Z' => c - b'A' + b'a',
887 _ => c,
888 }
889}
890
891impl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {
892 #[inline(always)]
893 fn compare(&self, t: &'b [u8]) -> CompareResult {
894 let pos = self.iter().zip(t.iter()).position(|(a, b)| a != b);
895
896 match pos {
897 Some(_) => CompareResult::Error,
898 None => {
899 if self.len() >= t.len() {
900 CompareResult::Ok
901 } else {
902 CompareResult::Incomplete
903 }
904 }
905 }
906 }
907
908 #[inline(always)]
909 fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
910 if self
911 .iter()
912 .zip(t)
913 .any(|(a, b)| lowercase_byte(*a) != lowercase_byte(*b))
914 {
915 CompareResult::Error
916 } else if self.len() < t.len() {
917 CompareResult::Incomplete
918 } else {
919 CompareResult::Ok
920 }
921 }
922}
923
924impl<'a, 'b> Compare<&'b str> for &'a [u8] {
925 #[inline(always)]
926 fn compare(&self, t: &'b str) -> CompareResult {
927 self.compare(AsBytes::as_bytes(t))
928 }
929 #[inline(always)]
930 fn compare_no_case(&self, t: &'b str) -> CompareResult {
931 self.compare_no_case(AsBytes::as_bytes(t))
932 }
933}
934
935impl<'a, 'b> Compare<&'b str> for &'a str {
936 #[inline(always)]
937 fn compare(&self, t: &'b str) -> CompareResult {
938 self.as_bytes().compare(t.as_bytes())
939 }
940
941 #[inline(always)]
943 fn compare_no_case(&self, t: &'b str) -> CompareResult {
944 let pos = self
945 .chars()
946 .zip(t.chars())
947 .position(|(a, b)| a.to_lowercase().ne(b.to_lowercase()));
948
949 match pos {
950 Some(_) => CompareResult::Error,
951 None => {
952 if self.len() >= t.len() {
953 CompareResult::Ok
954 } else {
955 CompareResult::Incomplete
956 }
957 }
958 }
959 }
960}
961
962impl<'a, 'b> Compare<&'b [u8]> for &'a str {
963 #[inline(always)]
964 fn compare(&self, t: &'b [u8]) -> CompareResult {
965 AsBytes::as_bytes(self).compare(t)
966 }
967 #[inline(always)]
968 fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
969 AsBytes::as_bytes(self).compare_no_case(t)
970 }
971}
972
973pub trait FindToken<T> {
975 fn find_token(&self, token: T) -> bool;
977}
978
979impl<'a> FindToken<u8> for &'a [u8] {
980 fn find_token(&self, token: u8) -> bool {
981 memchr::memchr(token, self).is_some()
982 }
983}
984
985impl<'a> FindToken<u8> for &'a str {
986 fn find_token(&self, token: u8) -> bool {
987 self.as_bytes().find_token(token)
988 }
989}
990
991impl<'a, 'b> FindToken<&'a u8> for &'b [u8] {
992 fn find_token(&self, token: &u8) -> bool {
993 self.find_token(*token)
994 }
995}
996
997impl<'a, 'b> FindToken<&'a u8> for &'b str {
998 fn find_token(&self, token: &u8) -> bool {
999 self.as_bytes().find_token(token)
1000 }
1001}
1002
1003impl<'a> FindToken<char> for &'a [u8] {
1004 fn find_token(&self, token: char) -> bool {
1005 self.iter().any(|i| *i == token as u8)
1006 }
1007}
1008
1009impl<'a> FindToken<char> for &'a str {
1010 fn find_token(&self, token: char) -> bool {
1011 self.chars().any(|i| i == token)
1012 }
1013}
1014
1015impl<'a> FindToken<char> for &'a [char] {
1016 fn find_token(&self, token: char) -> bool {
1017 self.iter().any(|i| *i == token)
1018 }
1019}
1020
1021impl<'a, 'b> FindToken<&'a char> for &'b [char] {
1022 fn find_token(&self, token: &char) -> bool {
1023 self.find_token(*token)
1024 }
1025}
1026
1027pub trait FindSubstring<T> {
1029 fn find_substring(&self, substr: T) -> Option<usize>;
1031}
1032
1033impl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {
1034 fn find_substring(&self, substr: &'b [u8]) -> Option<usize> {
1035 if substr.len() > self.len() {
1036 return None;
1037 }
1038
1039 let (&substr_first, substr_rest) = match substr.split_first() {
1040 Some(split) => split,
1041 None => return Some(0),
1044 };
1045
1046 if substr_rest.is_empty() {
1047 return memchr::memchr(substr_first, self);
1048 }
1049
1050 let mut offset = 0;
1051 let haystack = &self[..self.len() - substr_rest.len()];
1052
1053 while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {
1054 offset += position;
1055 let next_offset = offset + 1;
1056 if &self[next_offset..][..substr_rest.len()] == substr_rest {
1057 return Some(offset);
1058 }
1059
1060 offset = next_offset;
1061 }
1062
1063 None
1064 }
1065}
1066
1067impl<'a, 'b> FindSubstring<&'b str> for &'a [u8] {
1068 fn find_substring(&self, substr: &'b str) -> Option<usize> {
1069 self.find_substring(AsBytes::as_bytes(substr))
1070 }
1071}
1072
1073impl<'a, 'b> FindSubstring<&'b str> for &'a str {
1074 fn find_substring(&self, substr: &'b str) -> Option<usize> {
1076 self.find(substr)
1077 }
1078}
1079
1080pub trait ParseTo<R> {
1082 fn parse_to(&self) -> Option<R>;
1085}
1086
1087impl<'a, R: FromStr> ParseTo<R> for &'a [u8] {
1088 fn parse_to(&self) -> Option<R> {
1089 from_utf8(self).ok().and_then(|s| s.parse().ok())
1090 }
1091}
1092
1093impl<'a, R: FromStr> ParseTo<R> for &'a str {
1094 fn parse_to(&self) -> Option<R> {
1095 self.parse().ok()
1096 }
1097}
1098
1099impl<'a, const N: usize> Compare<[u8; N]> for &'a [u8] {
1100 #[inline(always)]
1101 fn compare(&self, t: [u8; N]) -> CompareResult {
1102 self.compare(&t[..])
1103 }
1104
1105 #[inline(always)]
1106 fn compare_no_case(&self, t: [u8; N]) -> CompareResult {
1107 self.compare_no_case(&t[..])
1108 }
1109}
1110
1111impl<'a, 'b, const N: usize> Compare<&'b [u8; N]> for &'a [u8] {
1112 #[inline(always)]
1113 fn compare(&self, t: &'b [u8; N]) -> CompareResult {
1114 self.compare(&t[..])
1115 }
1116
1117 #[inline(always)]
1118 fn compare_no_case(&self, t: &'b [u8; N]) -> CompareResult {
1119 self.compare_no_case(&t[..])
1120 }
1121}
1122
1123impl<const N: usize> FindToken<u8> for [u8; N] {
1124 fn find_token(&self, token: u8) -> bool {
1125 memchr::memchr(token, &self[..]).is_some()
1126 }
1127}
1128
1129impl<'a, const N: usize> FindToken<&'a u8> for [u8; N] {
1130 fn find_token(&self, token: &u8) -> bool {
1131 self.find_token(*token)
1132 }
1133}
1134
1135pub trait ExtendInto {
1138 type Item;
1142
1143 type Extender;
1145
1146 fn new_builder(&self) -> Self::Extender;
1148 fn extend_into(&self, acc: &mut Self::Extender);
1150}
1151
1152#[cfg(feature = "alloc")]
1153impl ExtendInto for [u8] {
1154 type Item = u8;
1155 type Extender = Vec<u8>;
1156
1157 #[inline]
1158 fn new_builder(&self) -> Vec<u8> {
1159 Vec::new()
1160 }
1161 #[inline]
1162 fn extend_into(&self, acc: &mut Vec<u8>) {
1163 acc.extend(self.iter().cloned());
1164 }
1165}
1166
1167#[cfg(feature = "alloc")]
1168impl ExtendInto for &[u8] {
1169 type Item = u8;
1170 type Extender = Vec<u8>;
1171
1172 #[inline]
1173 fn new_builder(&self) -> Vec<u8> {
1174 Vec::new()
1175 }
1176 #[inline]
1177 fn extend_into(&self, acc: &mut Vec<u8>) {
1178 acc.extend_from_slice(self);
1179 }
1180}
1181
1182#[cfg(feature = "alloc")]
1183impl ExtendInto for str {
1184 type Item = char;
1185 type Extender = String;
1186
1187 #[inline]
1188 fn new_builder(&self) -> String {
1189 String::new()
1190 }
1191 #[inline]
1192 fn extend_into(&self, acc: &mut String) {
1193 acc.push_str(self);
1194 }
1195}
1196
1197#[cfg(feature = "alloc")]
1198impl ExtendInto for &str {
1199 type Item = char;
1200 type Extender = String;
1201
1202 #[inline]
1203 fn new_builder(&self) -> String {
1204 String::new()
1205 }
1206 #[inline]
1207 fn extend_into(&self, acc: &mut String) {
1208 acc.push_str(self);
1209 }
1210}
1211
1212#[cfg(feature = "alloc")]
1213impl ExtendInto for char {
1214 type Item = char;
1215 type Extender = String;
1216
1217 #[inline]
1218 fn new_builder(&self) -> String {
1219 String::new()
1220 }
1221 #[inline]
1222 fn extend_into(&self, acc: &mut String) {
1223 acc.push(*self);
1224 }
1225}
1226
1227pub trait ToUsize {
1234 fn to_usize(&self) -> usize;
1236}
1237
1238impl ToUsize for u8 {
1239 #[inline]
1240 fn to_usize(&self) -> usize {
1241 *self as usize
1242 }
1243}
1244
1245impl ToUsize for u16 {
1246 #[inline]
1247 fn to_usize(&self) -> usize {
1248 *self as usize
1249 }
1250}
1251
1252impl ToUsize for usize {
1253 #[inline]
1254 fn to_usize(&self) -> usize {
1255 *self
1256 }
1257}
1258
1259#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
1260impl ToUsize for u32 {
1261 #[inline]
1262 fn to_usize(&self) -> usize {
1263 *self as usize
1264 }
1265}
1266
1267#[cfg(target_pointer_width = "64")]
1268impl ToUsize for u64 {
1269 #[inline]
1270 fn to_usize(&self) -> usize {
1271 *self as usize
1272 }
1273}
1274
1275pub trait ErrorConvert<E> {
1277 fn convert(self) -> E;
1279}
1280
1281impl<I> ErrorConvert<(I, ErrorKind)> for ((I, usize), ErrorKind) {
1282 fn convert(self) -> (I, ErrorKind) {
1283 ((self.0).0, self.1)
1284 }
1285}
1286
1287impl<I> ErrorConvert<((I, usize), ErrorKind)> for (I, ErrorKind) {
1288 fn convert(self) -> ((I, usize), ErrorKind) {
1289 ((self.0, 0), self.1)
1290 }
1291}
1292
1293use crate::error;
1294impl<I> ErrorConvert<error::Error<I>> for error::Error<(I, usize)> {
1295 fn convert(self) -> error::Error<I> {
1296 error::Error {
1297 input: self.input.0,
1298 code: self.code,
1299 }
1300 }
1301}
1302
1303impl<I> ErrorConvert<error::Error<(I, usize)>> for error::Error<I> {
1304 fn convert(self) -> error::Error<(I, usize)> {
1305 error::Error {
1306 input: (self.input, 0),
1307 code: self.code,
1308 }
1309 }
1310}
1311
1312impl ErrorConvert<()> for () {
1313 fn convert(self) {}
1314}
1315
1316#[cfg(feature = "std")]
1317#[cfg_attr(feature = "docsrs", doc(cfg(feature = "std")))]
1318pub trait HexDisplay {
1320 fn to_hex(&self, chunk_size: usize) -> String;
1323
1324 fn to_hex_from(&self, chunk_size: usize, from: usize) -> String;
1327}
1328
1329#[cfg(feature = "std")]
1330static CHARS: &[u8] = b"0123456789abcdef";
1331
1332#[cfg(feature = "std")]
1333impl HexDisplay for [u8] {
1334 #[allow(unused_variables)]
1335 fn to_hex(&self, chunk_size: usize) -> String {
1336 self.to_hex_from(chunk_size, 0)
1337 }
1338
1339 #[allow(unused_variables)]
1340 fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
1341 let mut v = Vec::with_capacity(self.len() * 3);
1342 let mut i = from;
1343 for chunk in self.chunks(chunk_size) {
1344 let s = format!("{:08x}", i);
1345 for &ch in s.as_bytes().iter() {
1346 v.push(ch);
1347 }
1348 v.push(b'\t');
1349
1350 i += chunk_size;
1351
1352 for &byte in chunk {
1353 v.push(CHARS[(byte >> 4) as usize]);
1354 v.push(CHARS[(byte & 0xf) as usize]);
1355 v.push(b' ');
1356 }
1357 if chunk_size > chunk.len() {
1358 for j in 0..(chunk_size - chunk.len()) {
1359 v.push(b' ');
1360 v.push(b' ');
1361 v.push(b' ');
1362 }
1363 }
1364 v.push(b'\t');
1365
1366 for &byte in chunk {
1367 if matches!(byte, 32..=126 | 128..=255) {
1368 v.push(byte);
1369 } else {
1370 v.push(b'.');
1371 }
1372 }
1373 v.push(b'\n');
1374 }
1375
1376 String::from_utf8_lossy(&v[..]).into_owned()
1377 }
1378}
1379
1380#[cfg(feature = "std")]
1381impl HexDisplay for str {
1382 #[allow(unused_variables)]
1383 fn to_hex(&self, chunk_size: usize) -> String {
1384 self.to_hex_from(chunk_size, 0)
1385 }
1386
1387 #[allow(unused_variables)]
1388 fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
1389 self.as_bytes().to_hex_from(chunk_size, from)
1390 }
1391}
1392
1393pub struct SaturatingIterator {
1395 count: usize,
1396}
1397
1398impl Iterator for SaturatingIterator {
1399 type Item = usize;
1400
1401 fn next(&mut self) -> Option<Self::Item> {
1402 let old_count = self.count;
1403 self.count = self.count.saturating_add(1);
1404 Some(old_count)
1405 }
1406}
1407
1408pub trait NomRange<Idx> {
1410 type Saturating: Iterator<Item = Idx>;
1412 type Bounded: Iterator<Item = Idx>;
1414
1415 fn contains(&self, item: &Idx) -> bool;
1417
1418 fn bounds(&self) -> (Bound<Idx>, Bound<Idx>);
1420
1421 fn is_inverted(&self) -> bool;
1423
1424 fn saturating_iter(&self) -> Self::Saturating;
1429
1430 fn bounded_iter(&self) -> Self::Bounded;
1435}
1436
1437impl NomRange<usize> for Range<usize> {
1438 type Saturating = Range<usize>;
1439 type Bounded = Range<usize>;
1440
1441 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1442 (Bound::Included(self.start), Bound::Excluded(self.end))
1443 }
1444
1445 fn contains(&self, item: &usize) -> bool {
1446 RangeBounds::contains(self, item)
1447 }
1448
1449 fn is_inverted(&self) -> bool {
1450 self.start >= self.end
1451 }
1452
1453 fn saturating_iter(&self) -> Self::Saturating {
1454 if self.end == 0 {
1455 Range::default()
1456 } else {
1457 0..self.end - 1
1458 }
1459 }
1460
1461 fn bounded_iter(&self) -> Self::Bounded {
1462 if self.end == 0 {
1463 Range::default()
1464 } else {
1465 0..self.end - 1
1466 }
1467 }
1468}
1469
1470impl NomRange<usize> for RangeInclusive<usize> {
1471 type Saturating = Range<usize>;
1472 type Bounded = Range<usize>;
1473
1474 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1475 (Bound::Included(*self.start()), Bound::Included(*self.end()))
1476 }
1477
1478 fn contains(&self, item: &usize) -> bool {
1479 RangeBounds::contains(self, item)
1480 }
1481
1482 fn is_inverted(&self) -> bool {
1483 !RangeInclusive::contains(self, self.start())
1484 }
1485
1486 fn saturating_iter(&self) -> Self::Saturating {
1487 0..*self.end()
1488 }
1489
1490 fn bounded_iter(&self) -> Self::Bounded {
1491 0..*self.end()
1492 }
1493}
1494
1495impl NomRange<usize> for RangeFrom<usize> {
1496 type Saturating = SaturatingIterator;
1497 type Bounded = Range<usize>;
1498
1499 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1500 (Bound::Included(self.start), Bound::Unbounded)
1501 }
1502
1503 fn contains(&self, item: &usize) -> bool {
1504 RangeBounds::contains(self, item)
1505 }
1506
1507 fn is_inverted(&self) -> bool {
1508 false
1509 }
1510
1511 fn saturating_iter(&self) -> Self::Saturating {
1512 SaturatingIterator { count: 0 }
1513 }
1514
1515 fn bounded_iter(&self) -> Self::Bounded {
1516 0..usize::MAX
1517 }
1518}
1519
1520impl NomRange<usize> for RangeTo<usize> {
1521 type Saturating = Range<usize>;
1522 type Bounded = Range<usize>;
1523
1524 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1525 (Bound::Unbounded, Bound::Excluded(self.end))
1526 }
1527
1528 fn contains(&self, item: &usize) -> bool {
1529 RangeBounds::contains(self, item)
1530 }
1531
1532 fn is_inverted(&self) -> bool {
1533 false
1534 }
1535
1536 fn saturating_iter(&self) -> Self::Saturating {
1537 if self.end == 0 {
1538 Range::default()
1539 } else {
1540 0..self.end - 1
1541 }
1542 }
1543
1544 fn bounded_iter(&self) -> Self::Bounded {
1545 if self.end == 0 {
1546 Range::default()
1547 } else {
1548 0..self.end - 1
1549 }
1550 }
1551}
1552
1553impl NomRange<usize> for RangeToInclusive<usize> {
1554 type Saturating = Range<usize>;
1555 type Bounded = Range<usize>;
1556
1557 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1558 (Bound::Unbounded, Bound::Included(self.end))
1559 }
1560
1561 fn contains(&self, item: &usize) -> bool {
1562 RangeBounds::contains(self, item)
1563 }
1564
1565 fn is_inverted(&self) -> bool {
1566 false
1567 }
1568
1569 fn saturating_iter(&self) -> Self::Saturating {
1570 0..self.end
1571 }
1572
1573 fn bounded_iter(&self) -> Self::Bounded {
1574 0..self.end
1575 }
1576}
1577
1578impl NomRange<usize> for RangeFull {
1579 type Saturating = SaturatingIterator;
1580 type Bounded = Range<usize>;
1581
1582 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1583 (Bound::Unbounded, Bound::Unbounded)
1584 }
1585
1586 fn contains(&self, item: &usize) -> bool {
1587 RangeBounds::contains(self, item)
1588 }
1589
1590 fn is_inverted(&self) -> bool {
1591 false
1592 }
1593
1594 fn saturating_iter(&self) -> Self::Saturating {
1595 SaturatingIterator { count: 0 }
1596 }
1597
1598 fn bounded_iter(&self) -> Self::Bounded {
1599 0..usize::MAX
1600 }
1601}
1602
1603impl NomRange<usize> for usize {
1604 type Saturating = Range<usize>;
1605 type Bounded = Range<usize>;
1606
1607 fn bounds(&self) -> (Bound<usize>, Bound<usize>) {
1608 (Bound::Included(*self), Bound::Included(*self))
1609 }
1610
1611 fn contains(&self, item: &usize) -> bool {
1612 self == item
1613 }
1614
1615 fn is_inverted(&self) -> bool {
1616 false
1617 }
1618
1619 fn saturating_iter(&self) -> Self::Saturating {
1620 0..*self
1621 }
1622
1623 fn bounded_iter(&self) -> Self::Bounded {
1624 0..*self
1625 }
1626}
1627
1628#[cfg(test)]
1629mod tests {
1630 use super::*;
1631
1632 #[test]
1633 fn test_offset_u8() {
1634 let s = b"abcd123";
1635 let a = &s[..];
1636 let b = &a[2..];
1637 let c = &a[..4];
1638 let d = &a[3..5];
1639 assert_eq!(a.offset(b), 2);
1640 assert_eq!(a.offset(c), 0);
1641 assert_eq!(a.offset(d), 3);
1642 }
1643
1644 #[test]
1645 fn test_offset_str() {
1646 let a = "abcřèÂßÇd123";
1647 let b = &a[7..];
1648 let c = &a[..5];
1649 let d = &a[5..9];
1650 assert_eq!(a.offset(b), 7);
1651 assert_eq!(a.offset(c), 0);
1652 assert_eq!(a.offset(d), 5);
1653 }
1654
1655 #[test]
1656 fn test_slice_index() {
1657 let a = "abcřèÂßÇd123";
1658 assert_eq!(a.slice_index(0), Ok(0));
1659 assert_eq!(a.slice_index(2), Ok(2));
1660 }
1661
1662 #[test]
1663 fn test_slice_index_utf8() {
1664 let a = "a¡€💢€¡a";
1665
1666 for (c, len) in a.chars().zip([1, 2, 3, 4, 3, 2, 1]) {
1667 assert_eq!(c.len(), len);
1668 }
1669
1670 assert_eq!(a.slice_index(0), Ok(0));
1671 assert_eq!(a.slice_index(1), Ok(1));
1672 assert_eq!(a.slice_index(2), Ok(3));
1673 assert_eq!(a.slice_index(3), Ok(6));
1674 assert_eq!(a.slice_index(4), Ok(10));
1675 assert_eq!(a.slice_index(5), Ok(13));
1676 assert_eq!(a.slice_index(6), Ok(15));
1677 assert_eq!(a.slice_index(7), Ok(16));
1678
1679 assert!(a.slice_index(8).is_err());
1680 }
1681}