1use super::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
4use super::validations::{next_code_point, next_code_point_reverse};
5use super::{
6 BytesIsNotEmpty, CharEscapeDebug, CharEscapeDefault, CharEscapeUnicode, IsAsciiWhitespace,
7 IsNotEmpty, IsWhitespace, LinesMap, UnsafeBytesToStr, from_utf8_unchecked,
8};
9use crate::char as char_mod;
10use crate::fmt::{self, Write};
11use crate::iter::{
12 Copied, Filter, FlatMap, FusedIterator, Map, TrustedLen, TrustedRandomAccess,
13 TrustedRandomAccessNoCoerce,
14};
15use crate::num::NonZero;
16use crate::ops::Try;
17use crate::slice::{self, Split as SliceSplit};
18
19#[derive(Clone)]
28#[must_use = "iterators are lazy and do nothing unless consumed"]
29#[stable(feature = "rust1", since = "1.0.0")]
30pub struct Chars<'a> {
31 pub(super) iter: slice::Iter<'a, u8>,
32}
33
34#[stable(feature = "rust1", since = "1.0.0")]
35impl<'a> Iterator for Chars<'a> {
36 type Item = char;
37
38 #[inline]
39 fn next(&mut self) -> Option<char> {
40 unsafe { next_code_point(&mut self.iter).map(|ch| char::from_u32_unchecked(ch)) }
43 }
44
45 #[inline]
46 fn count(self) -> usize {
47 super::count::count_chars(self.as_str())
48 }
49
50 #[inline]
51 fn advance_by(&mut self, mut remainder: usize) -> Result<(), NonZero<usize>> {
52 const CHUNK_SIZE: usize = 32;
53
54 if remainder >= CHUNK_SIZE {
55 let mut chunks = self.iter.as_slice().as_chunks::<CHUNK_SIZE>().0.iter();
56 let mut bytes_skipped: usize = 0;
57
58 while remainder > CHUNK_SIZE
59 && let Some(chunk) = chunks.next()
60 {
61 bytes_skipped += CHUNK_SIZE;
62
63 let mut start_bytes = [false; CHUNK_SIZE];
64
65 for i in 0..CHUNK_SIZE {
66 start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]);
67 }
68
69 remainder -= start_bytes.into_iter().map(|i| i as u8).sum::<u8>() as usize;
70 }
71
72 unsafe { self.iter.advance_by(bytes_skipped).unwrap_unchecked() };
75
76 while self.iter.len() > 0 {
78 let b = self.iter.as_slice()[0];
79 if !super::validations::utf8_is_cont_byte(b) {
80 break;
81 }
82 unsafe { self.iter.advance_by(1).unwrap_unchecked() };
84 }
85 }
86
87 while (remainder > 0) && (self.iter.len() > 0) {
88 remainder -= 1;
89 let b = self.iter.as_slice()[0];
90 let slurp = super::validations::utf8_char_width(b);
91 unsafe { self.iter.advance_by(slurp).unwrap_unchecked() };
94 }
95
96 NonZero::new(remainder).map_or(Ok(()), Err)
97 }
98
99 #[inline]
100 fn size_hint(&self) -> (usize, Option<usize>) {
101 let len = self.iter.len();
102 (len.div_ceil(4), Some(len))
103 }
104
105 #[inline]
106 fn last(mut self) -> Option<char> {
107 self.next_back()
109 }
110}
111
112#[stable(feature = "chars_debug_impl", since = "1.38.0")]
113impl fmt::Debug for Chars<'_> {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 write!(f, "Chars(")?;
116 f.debug_list().entries(self.clone()).finish()?;
117 write!(f, ")")?;
118 Ok(())
119 }
120}
121
122#[stable(feature = "rust1", since = "1.0.0")]
123impl<'a> DoubleEndedIterator for Chars<'a> {
124 #[inline]
125 fn next_back(&mut self) -> Option<char> {
126 unsafe { next_code_point_reverse(&mut self.iter).map(|ch| char::from_u32_unchecked(ch)) }
129 }
130}
131
132#[stable(feature = "fused", since = "1.26.0")]
133impl FusedIterator for Chars<'_> {}
134
135impl<'a> Chars<'a> {
136 #[stable(feature = "iter_to_slice", since = "1.4.0")]
154 #[must_use]
155 #[inline]
156 pub fn as_str(&self) -> &'a str {
157 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
159 }
160}
161
162#[derive(Clone, Debug)]
170#[must_use = "iterators are lazy and do nothing unless consumed"]
171#[stable(feature = "rust1", since = "1.0.0")]
172pub struct CharIndices<'a> {
173 pub(super) front_offset: usize,
174 pub(super) iter: Chars<'a>,
175}
176
177#[stable(feature = "rust1", since = "1.0.0")]
178impl<'a> Iterator for CharIndices<'a> {
179 type Item = (usize, char);
180
181 #[inline]
182 fn next(&mut self) -> Option<(usize, char)> {
183 let pre_len = self.iter.iter.len();
184 match self.iter.next() {
185 None => None,
186 Some(ch) => {
187 let index = self.front_offset;
188 let len = self.iter.iter.len();
189 self.front_offset += pre_len - len;
190 Some((index, ch))
191 }
192 }
193 }
194
195 #[inline]
196 fn count(self) -> usize {
197 self.iter.count()
198 }
199
200 #[inline]
201 fn size_hint(&self) -> (usize, Option<usize>) {
202 self.iter.size_hint()
203 }
204
205 #[inline]
206 fn last(mut self) -> Option<(usize, char)> {
207 self.next_back()
209 }
210}
211
212#[stable(feature = "rust1", since = "1.0.0")]
213impl<'a> DoubleEndedIterator for CharIndices<'a> {
214 #[inline]
215 fn next_back(&mut self) -> Option<(usize, char)> {
216 self.iter.next_back().map(|ch| {
217 let index = self.front_offset + self.iter.iter.len();
218 (index, ch)
219 })
220 }
221}
222
223#[stable(feature = "fused", since = "1.26.0")]
224impl FusedIterator for CharIndices<'_> {}
225
226impl<'a> CharIndices<'a> {
227 #[stable(feature = "iter_to_slice", since = "1.4.0")]
232 #[must_use]
233 #[inline]
234 pub fn as_str(&self) -> &'a str {
235 self.iter.as_str()
236 }
237
238 #[inline]
268 #[must_use]
269 #[stable(feature = "char_indices_offset", since = "1.82.0")]
270 pub fn offset(&self) -> usize {
271 self.front_offset
272 }
273}
274
275#[must_use = "iterators are lazy and do nothing unless consumed"]
282#[stable(feature = "rust1", since = "1.0.0")]
283#[derive(Clone, Debug)]
284pub struct Bytes<'a>(pub(super) Copied<slice::Iter<'a, u8>>);
285
286#[stable(feature = "rust1", since = "1.0.0")]
287impl Iterator for Bytes<'_> {
288 type Item = u8;
289
290 #[inline]
291 fn next(&mut self) -> Option<u8> {
292 self.0.next()
293 }
294
295 #[inline]
296 fn size_hint(&self) -> (usize, Option<usize>) {
297 self.0.size_hint()
298 }
299
300 #[inline]
301 fn count(self) -> usize {
302 self.0.count()
303 }
304
305 #[inline]
306 fn last(self) -> Option<Self::Item> {
307 self.0.last()
308 }
309
310 #[inline]
311 fn nth(&mut self, n: usize) -> Option<Self::Item> {
312 self.0.nth(n)
313 }
314
315 #[inline]
316 fn all<F>(&mut self, f: F) -> bool
317 where
318 F: FnMut(Self::Item) -> bool,
319 {
320 self.0.all(f)
321 }
322
323 #[inline]
324 fn any<F>(&mut self, f: F) -> bool
325 where
326 F: FnMut(Self::Item) -> bool,
327 {
328 self.0.any(f)
329 }
330
331 #[inline]
332 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
333 where
334 P: FnMut(&Self::Item) -> bool,
335 {
336 self.0.find(predicate)
337 }
338
339 #[inline]
340 fn position<P>(&mut self, predicate: P) -> Option<usize>
341 where
342 P: FnMut(Self::Item) -> bool,
343 {
344 self.0.position(predicate)
345 }
346
347 #[inline]
348 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
349 where
350 P: FnMut(Self::Item) -> bool,
351 {
352 self.0.rposition(predicate)
353 }
354
355 #[inline]
356 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> u8 {
357 unsafe { self.0.__iterator_get_unchecked(idx) }
360 }
361}
362
363#[stable(feature = "rust1", since = "1.0.0")]
364impl DoubleEndedIterator for Bytes<'_> {
365 #[inline]
366 fn next_back(&mut self) -> Option<u8> {
367 self.0.next_back()
368 }
369
370 #[inline]
371 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
372 self.0.nth_back(n)
373 }
374
375 #[inline]
376 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
377 where
378 P: FnMut(&Self::Item) -> bool,
379 {
380 self.0.rfind(predicate)
381 }
382}
383
384#[stable(feature = "rust1", since = "1.0.0")]
385impl ExactSizeIterator for Bytes<'_> {
386 #[inline]
387 fn len(&self) -> usize {
388 self.0.len()
389 }
390
391 #[inline]
392 fn is_empty(&self) -> bool {
393 self.0.is_empty()
394 }
395}
396
397#[stable(feature = "fused", since = "1.26.0")]
398impl FusedIterator for Bytes<'_> {}
399
400#[unstable(feature = "trusted_len", issue = "37572")]
401unsafe impl TrustedLen for Bytes<'_> {}
402
403#[doc(hidden)]
404#[unstable(feature = "trusted_random_access", issue = "none")]
405unsafe impl TrustedRandomAccess for Bytes<'_> {}
406
407#[doc(hidden)]
408#[unstable(feature = "trusted_random_access", issue = "none")]
409unsafe impl TrustedRandomAccessNoCoerce for Bytes<'_> {
410 const MAY_HAVE_SIDE_EFFECT: bool = false;
411}
412
413macro_rules! derive_pattern_clone {
416 (clone $t:ident with |$s:ident| $e:expr) => {
417 impl<'a, P> Clone for $t<'a, P>
418 where
419 P: Pattern<Searcher<'a>: Clone>,
420 {
421 fn clone(&self) -> Self {
422 let $s = self;
423 $e
424 }
425 }
426 };
427}
428
429macro_rules! generate_pattern_iterators {
468 {
469 forward:
471 $(#[$forward_iterator_attribute:meta])*
472 struct $forward_iterator:ident;
473
474 reverse:
476 $(#[$reverse_iterator_attribute:meta])*
477 struct $reverse_iterator:ident;
478
479 stability:
481 $(#[$common_stability_attribute:meta])*
482
483 internal:
485 $internal_iterator:ident yielding ($iterty:ty);
486
487 delegate $($t:tt)*
489 } => {
490 $(#[$forward_iterator_attribute])*
491 $(#[$common_stability_attribute])*
492 pub struct $forward_iterator<'a, P: Pattern>(pub(super) $internal_iterator<'a, P>);
493
494 $(#[$common_stability_attribute])*
495 impl<'a, P> fmt::Debug for $forward_iterator<'a, P>
496 where
497 P: Pattern<Searcher<'a>: fmt::Debug>,
498 {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 f.debug_tuple(stringify!($forward_iterator))
501 .field(&self.0)
502 .finish()
503 }
504 }
505
506 $(#[$common_stability_attribute])*
507 impl<'a, P: Pattern> Iterator for $forward_iterator<'a, P> {
508 type Item = $iterty;
509
510 #[inline]
511 fn next(&mut self) -> Option<$iterty> {
512 self.0.next()
513 }
514 }
515
516 $(#[$common_stability_attribute])*
517 impl<'a, P> Clone for $forward_iterator<'a, P>
518 where
519 P: Pattern<Searcher<'a>: Clone>,
520 {
521 fn clone(&self) -> Self {
522 $forward_iterator(self.0.clone())
523 }
524 }
525
526 $(#[$reverse_iterator_attribute])*
527 $(#[$common_stability_attribute])*
528 pub struct $reverse_iterator<'a, P: Pattern>(pub(super) $internal_iterator<'a, P>);
529
530 $(#[$common_stability_attribute])*
531 impl<'a, P> fmt::Debug for $reverse_iterator<'a, P>
532 where
533 P: Pattern<Searcher<'a>: fmt::Debug>,
534 {
535 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536 f.debug_tuple(stringify!($reverse_iterator))
537 .field(&self.0)
538 .finish()
539 }
540 }
541
542 $(#[$common_stability_attribute])*
543 impl<'a, P> Iterator for $reverse_iterator<'a, P>
544 where
545 P: Pattern<Searcher<'a>: ReverseSearcher<'a>>,
546 {
547 type Item = $iterty;
548
549 #[inline]
550 fn next(&mut self) -> Option<$iterty> {
551 self.0.next_back()
552 }
553 }
554
555 $(#[$common_stability_attribute])*
556 impl<'a, P> Clone for $reverse_iterator<'a, P>
557 where
558 P: Pattern<Searcher<'a>: Clone>,
559 {
560 fn clone(&self) -> Self {
561 $reverse_iterator(self.0.clone())
562 }
563 }
564
565 #[stable(feature = "fused", since = "1.26.0")]
566 impl<'a, P: Pattern> FusedIterator for $forward_iterator<'a, P> {}
567
568 #[stable(feature = "fused", since = "1.26.0")]
569 impl<'a, P> FusedIterator for $reverse_iterator<'a, P>
570 where
571 P: Pattern<Searcher<'a>: ReverseSearcher<'a>>,
572 {}
573
574 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
575 $forward_iterator,
576 $reverse_iterator, $iterty);
577 };
578 {
579 double ended; with $(#[$common_stability_attribute:meta])*,
580 $forward_iterator:ident,
581 $reverse_iterator:ident, $iterty:ty
582 } => {
583 $(#[$common_stability_attribute])*
584 impl<'a, P> DoubleEndedIterator for $forward_iterator<'a, P>
585 where
586 P: Pattern<Searcher<'a>: DoubleEndedSearcher<'a>>,
587 {
588 #[inline]
589 fn next_back(&mut self) -> Option<$iterty> {
590 self.0.next_back()
591 }
592 }
593
594 $(#[$common_stability_attribute])*
595 impl<'a, P> DoubleEndedIterator for $reverse_iterator<'a, P>
596 where
597 P: Pattern<Searcher<'a>: DoubleEndedSearcher<'a>>,
598 {
599 #[inline]
600 fn next_back(&mut self) -> Option<$iterty> {
601 self.0.next()
602 }
603 }
604 };
605 {
606 single ended; with $(#[$common_stability_attribute:meta])*,
607 $forward_iterator:ident,
608 $reverse_iterator:ident, $iterty:ty
609 } => {}
610}
611
612derive_pattern_clone! {
613 clone SplitInternal
614 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
615}
616
617pub(super) struct SplitInternal<'a, P: Pattern> {
618 pub(super) start: usize,
619 pub(super) end: usize,
620 pub(super) matcher: P::Searcher<'a>,
621 pub(super) allow_trailing_empty: bool,
622 pub(super) finished: bool,
623}
624
625impl<'a, P> fmt::Debug for SplitInternal<'a, P>
626where
627 P: Pattern<Searcher<'a>: fmt::Debug>,
628{
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.debug_struct("SplitInternal")
631 .field("start", &self.start)
632 .field("end", &self.end)
633 .field("matcher", &self.matcher)
634 .field("allow_trailing_empty", &self.allow_trailing_empty)
635 .field("finished", &self.finished)
636 .finish()
637 }
638}
639
640impl<'a, P: Pattern> SplitInternal<'a, P> {
641 #[inline]
642 fn get_end(&mut self) -> Option<&'a str> {
643 if !self.finished {
644 self.finished = true;
645
646 if self.allow_trailing_empty || self.end - self.start > 0 {
647 let string = unsafe { self.matcher.haystack().get_unchecked(self.start..self.end) };
649 return Some(string);
650 }
651 }
652
653 None
654 }
655
656 #[inline]
657 fn next(&mut self) -> Option<&'a str> {
658 if self.finished {
659 return None;
660 }
661
662 let haystack = self.matcher.haystack();
663 match self.matcher.next_match() {
664 Some((a, b)) => unsafe {
668 let elt = haystack.get_unchecked(self.start..a);
669 self.start = b;
670 Some(elt)
671 },
672 None => self.get_end(),
673 }
674 }
675
676 #[inline]
677 fn next_inclusive(&mut self) -> Option<&'a str> {
678 if self.finished {
679 return None;
680 }
681
682 let haystack = self.matcher.haystack();
683 match self.matcher.next_match() {
684 Some((_, b)) => unsafe {
690 let elt = haystack.get_unchecked(self.start..b);
691 self.start = b;
692 Some(elt)
693 },
694 None => self.get_end(),
695 }
696 }
697
698 #[inline]
699 fn next_back(&mut self) -> Option<&'a str>
700 where
701 P::Searcher<'a>: ReverseSearcher<'a>,
702 {
703 if self.finished {
704 return None;
705 }
706
707 if !self.allow_trailing_empty {
708 self.allow_trailing_empty = true;
709 match self.next_back() {
710 Some(elt) if !elt.is_empty() => return Some(elt),
711 _ => {
712 if self.finished {
713 return None;
714 }
715 }
716 }
717 }
718
719 let haystack = self.matcher.haystack();
720 match self.matcher.next_match_back() {
721 Some((a, b)) => unsafe {
727 let elt = haystack.get_unchecked(b..self.end);
728 self.end = a;
729 Some(elt)
730 },
731 None => unsafe {
733 self.finished = true;
734 Some(haystack.get_unchecked(self.start..self.end))
735 },
736 }
737 }
738
739 #[inline]
740 fn next_back_inclusive(&mut self) -> Option<&'a str>
741 where
742 P::Searcher<'a>: ReverseSearcher<'a>,
743 {
744 if self.finished {
745 return None;
746 }
747
748 if !self.allow_trailing_empty {
749 self.allow_trailing_empty = true;
750 match self.next_back_inclusive() {
751 Some(elt) if !elt.is_empty() => return Some(elt),
752 _ => {
753 if self.finished {
754 return None;
755 }
756 }
757 }
758 }
759
760 let haystack = self.matcher.haystack();
761 match self.matcher.next_match_back() {
762 Some((_, b)) => unsafe {
768 let elt = haystack.get_unchecked(b..self.end);
769 self.end = b;
770 Some(elt)
771 },
772 None => unsafe {
778 self.finished = true;
779 Some(haystack.get_unchecked(self.start..self.end))
780 },
781 }
782 }
783
784 #[inline]
785 fn remainder(&self) -> Option<&'a str> {
786 if self.finished {
788 return None;
789 }
790
791 Some(unsafe { self.matcher.haystack().get_unchecked(self.start..self.end) })
793 }
794}
795
796generate_pattern_iterators! {
797 forward:
798 struct Split;
802 reverse:
803 struct RSplit;
807 stability:
808 #[stable(feature = "rust1", since = "1.0.0")]
809 internal:
810 SplitInternal yielding (&'a str);
811 delegate double ended;
812}
813
814impl<'a, P: Pattern> Split<'a, P> {
815 #[inline]
831 #[unstable(feature = "str_split_remainder", issue = "77998")]
832 pub fn remainder(&self) -> Option<&'a str> {
833 self.0.remainder()
834 }
835}
836
837impl<'a, P: Pattern> RSplit<'a, P> {
838 #[inline]
854 #[unstable(feature = "str_split_remainder", issue = "77998")]
855 pub fn remainder(&self) -> Option<&'a str> {
856 self.0.remainder()
857 }
858}
859
860generate_pattern_iterators! {
861 forward:
862 struct SplitTerminator;
866 reverse:
867 struct RSplitTerminator;
871 stability:
872 #[stable(feature = "rust1", since = "1.0.0")]
873 internal:
874 SplitInternal yielding (&'a str);
875 delegate double ended;
876}
877
878impl<'a, P: Pattern> SplitTerminator<'a, P> {
879 #[inline]
895 #[unstable(feature = "str_split_remainder", issue = "77998")]
896 pub fn remainder(&self) -> Option<&'a str> {
897 self.0.remainder()
898 }
899}
900
901impl<'a, P: Pattern> RSplitTerminator<'a, P> {
902 #[inline]
918 #[unstable(feature = "str_split_remainder", issue = "77998")]
919 pub fn remainder(&self) -> Option<&'a str> {
920 self.0.remainder()
921 }
922}
923
924derive_pattern_clone! {
925 clone SplitNInternal
926 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
927}
928
929pub(super) struct SplitNInternal<'a, P: Pattern> {
930 pub(super) iter: SplitInternal<'a, P>,
931 pub(super) count: usize,
933}
934
935impl<'a, P> fmt::Debug for SplitNInternal<'a, P>
936where
937 P: Pattern<Searcher<'a>: fmt::Debug>,
938{
939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 f.debug_struct("SplitNInternal")
941 .field("iter", &self.iter)
942 .field("count", &self.count)
943 .finish()
944 }
945}
946
947impl<'a, P: Pattern> SplitNInternal<'a, P> {
948 #[inline]
949 fn next(&mut self) -> Option<&'a str> {
950 match self.count {
951 0 => None,
952 1 => {
953 self.count = 0;
954 self.iter.get_end()
955 }
956 _ => {
957 self.count -= 1;
958 self.iter.next()
959 }
960 }
961 }
962
963 #[inline]
964 fn next_back(&mut self) -> Option<&'a str>
965 where
966 P::Searcher<'a>: ReverseSearcher<'a>,
967 {
968 match self.count {
969 0 => None,
970 1 => {
971 self.count = 0;
972 self.iter.get_end()
973 }
974 _ => {
975 self.count -= 1;
976 self.iter.next_back()
977 }
978 }
979 }
980
981 #[inline]
982 fn remainder(&self) -> Option<&'a str> {
983 self.iter.remainder()
984 }
985}
986
987generate_pattern_iterators! {
988 forward:
989 struct SplitN;
993 reverse:
994 struct RSplitN;
998 stability:
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 internal:
1001 SplitNInternal yielding (&'a str);
1002 delegate single ended;
1003}
1004
1005impl<'a, P: Pattern> SplitN<'a, P> {
1006 #[inline]
1022 #[unstable(feature = "str_split_remainder", issue = "77998")]
1023 pub fn remainder(&self) -> Option<&'a str> {
1024 self.0.remainder()
1025 }
1026}
1027
1028impl<'a, P: Pattern> RSplitN<'a, P> {
1029 #[inline]
1045 #[unstable(feature = "str_split_remainder", issue = "77998")]
1046 pub fn remainder(&self) -> Option<&'a str> {
1047 self.0.remainder()
1048 }
1049}
1050
1051derive_pattern_clone! {
1052 clone MatchIndicesInternal
1053 with |s| MatchIndicesInternal(s.0.clone())
1054}
1055
1056pub(super) struct MatchIndicesInternal<'a, P: Pattern>(pub(super) P::Searcher<'a>);
1057
1058impl<'a, P> fmt::Debug for MatchIndicesInternal<'a, P>
1059where
1060 P: Pattern<Searcher<'a>: fmt::Debug>,
1061{
1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063 f.debug_tuple("MatchIndicesInternal").field(&self.0).finish()
1064 }
1065}
1066
1067impl<'a, P: Pattern> MatchIndicesInternal<'a, P> {
1068 #[inline]
1069 fn next(&mut self) -> Option<(usize, &'a str)> {
1070 self.0
1071 .next_match()
1072 .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) })
1074 }
1075
1076 #[inline]
1077 fn next_back(&mut self) -> Option<(usize, &'a str)>
1078 where
1079 P::Searcher<'a>: ReverseSearcher<'a>,
1080 {
1081 self.0
1082 .next_match_back()
1083 .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) })
1085 }
1086}
1087
1088generate_pattern_iterators! {
1089 forward:
1090 struct MatchIndices;
1094 reverse:
1095 struct RMatchIndices;
1099 stability:
1100 #[stable(feature = "str_match_indices", since = "1.5.0")]
1101 internal:
1102 MatchIndicesInternal yielding ((usize, &'a str));
1103 delegate double ended;
1104}
1105
1106derive_pattern_clone! {
1107 clone MatchesInternal
1108 with |s| MatchesInternal(s.0.clone())
1109}
1110
1111pub(super) struct MatchesInternal<'a, P: Pattern>(pub(super) P::Searcher<'a>);
1112
1113impl<'a, P> fmt::Debug for MatchesInternal<'a, P>
1114where
1115 P: Pattern<Searcher<'a>: fmt::Debug>,
1116{
1117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1118 f.debug_tuple("MatchesInternal").field(&self.0).finish()
1119 }
1120}
1121
1122impl<'a, P: Pattern> MatchesInternal<'a, P> {
1123 #[inline]
1124 fn next(&mut self) -> Option<&'a str> {
1125 self.0.next_match().map(|(a, b)| unsafe {
1127 self.0.haystack().get_unchecked(a..b)
1129 })
1130 }
1131
1132 #[inline]
1133 fn next_back(&mut self) -> Option<&'a str>
1134 where
1135 P::Searcher<'a>: ReverseSearcher<'a>,
1136 {
1137 self.0.next_match_back().map(|(a, b)| unsafe {
1139 self.0.haystack().get_unchecked(a..b)
1141 })
1142 }
1143}
1144
1145generate_pattern_iterators! {
1146 forward:
1147 struct Matches;
1151 reverse:
1152 struct RMatches;
1156 stability:
1157 #[stable(feature = "str_matches", since = "1.2.0")]
1158 internal:
1159 MatchesInternal yielding (&'a str);
1160 delegate double ended;
1161}
1162
1163#[stable(feature = "rust1", since = "1.0.0")]
1170#[must_use = "iterators are lazy and do nothing unless consumed"]
1171#[derive(Clone, Debug)]
1172pub struct Lines<'a>(pub(super) Map<SplitInclusive<'a, char>, LinesMap>);
1173
1174#[stable(feature = "rust1", since = "1.0.0")]
1175impl<'a> Iterator for Lines<'a> {
1176 type Item = &'a str;
1177
1178 #[inline]
1179 fn next(&mut self) -> Option<&'a str> {
1180 self.0.next()
1181 }
1182
1183 #[inline]
1184 fn size_hint(&self) -> (usize, Option<usize>) {
1185 self.0.size_hint()
1186 }
1187
1188 #[inline]
1189 fn last(mut self) -> Option<&'a str> {
1190 self.next_back()
1191 }
1192}
1193
1194#[stable(feature = "rust1", since = "1.0.0")]
1195impl<'a> DoubleEndedIterator for Lines<'a> {
1196 #[inline]
1197 fn next_back(&mut self) -> Option<&'a str> {
1198 self.0.next_back()
1199 }
1200}
1201
1202#[stable(feature = "fused", since = "1.26.0")]
1203impl FusedIterator for Lines<'_> {}
1204
1205impl<'a> Lines<'a> {
1206 #[inline]
1223 #[must_use]
1224 #[unstable(feature = "str_lines_remainder", issue = "77998")]
1225 pub fn remainder(&self) -> Option<&'a str> {
1226 self.0.iter.remainder()
1227 }
1228}
1229
1230#[stable(feature = "rust1", since = "1.0.0")]
1234#[deprecated(since = "1.4.0", note = "use lines()/Lines instead now")]
1235#[must_use = "iterators are lazy and do nothing unless consumed"]
1236#[derive(Clone, Debug)]
1237#[allow(deprecated)]
1238pub struct LinesAny<'a>(pub(super) Lines<'a>);
1239
1240#[stable(feature = "rust1", since = "1.0.0")]
1241#[allow(deprecated)]
1242impl<'a> Iterator for LinesAny<'a> {
1243 type Item = &'a str;
1244
1245 #[inline]
1246 fn next(&mut self) -> Option<&'a str> {
1247 self.0.next()
1248 }
1249
1250 #[inline]
1251 fn size_hint(&self) -> (usize, Option<usize>) {
1252 self.0.size_hint()
1253 }
1254}
1255
1256#[stable(feature = "rust1", since = "1.0.0")]
1257#[allow(deprecated)]
1258impl<'a> DoubleEndedIterator for LinesAny<'a> {
1259 #[inline]
1260 fn next_back(&mut self) -> Option<&'a str> {
1261 self.0.next_back()
1262 }
1263}
1264
1265#[stable(feature = "fused", since = "1.26.0")]
1266#[allow(deprecated)]
1267impl FusedIterator for LinesAny<'_> {}
1268
1269#[stable(feature = "split_whitespace", since = "1.1.0")]
1277#[derive(Clone, Debug)]
1278pub struct SplitWhitespace<'a> {
1279 pub(super) inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
1280}
1281
1282#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1290#[derive(Clone, Debug)]
1291pub struct SplitAsciiWhitespace<'a> {
1292 pub(super) inner:
1293 Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
1294}
1295
1296#[stable(feature = "split_inclusive", since = "1.51.0")]
1306pub struct SplitInclusive<'a, P: Pattern>(pub(super) SplitInternal<'a, P>);
1307
1308#[stable(feature = "split_whitespace", since = "1.1.0")]
1309impl<'a> Iterator for SplitWhitespace<'a> {
1310 type Item = &'a str;
1311
1312 #[inline]
1313 fn next(&mut self) -> Option<&'a str> {
1314 self.inner.next()
1315 }
1316
1317 #[inline]
1318 fn size_hint(&self) -> (usize, Option<usize>) {
1319 self.inner.size_hint()
1320 }
1321
1322 #[inline]
1323 fn last(mut self) -> Option<&'a str> {
1324 self.next_back()
1325 }
1326}
1327
1328#[stable(feature = "split_whitespace", since = "1.1.0")]
1329impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
1330 #[inline]
1331 fn next_back(&mut self) -> Option<&'a str> {
1332 self.inner.next_back()
1333 }
1334}
1335
1336#[stable(feature = "fused", since = "1.26.0")]
1337impl FusedIterator for SplitWhitespace<'_> {}
1338
1339impl<'a> SplitWhitespace<'a> {
1340 #[inline]
1357 #[must_use]
1358 #[unstable(feature = "str_split_whitespace_remainder", issue = "77998")]
1359 pub fn remainder(&self) -> Option<&'a str> {
1360 self.inner.iter.remainder()
1361 }
1362}
1363
1364#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1365impl<'a> Iterator for SplitAsciiWhitespace<'a> {
1366 type Item = &'a str;
1367
1368 #[inline]
1369 fn next(&mut self) -> Option<&'a str> {
1370 self.inner.next()
1371 }
1372
1373 #[inline]
1374 fn size_hint(&self) -> (usize, Option<usize>) {
1375 self.inner.size_hint()
1376 }
1377
1378 #[inline]
1379 fn last(mut self) -> Option<&'a str> {
1380 self.next_back()
1381 }
1382}
1383
1384#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1385impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
1386 #[inline]
1387 fn next_back(&mut self) -> Option<&'a str> {
1388 self.inner.next_back()
1389 }
1390}
1391
1392#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1393impl FusedIterator for SplitAsciiWhitespace<'_> {}
1394
1395impl<'a> SplitAsciiWhitespace<'a> {
1396 #[inline]
1415 #[must_use]
1416 #[unstable(feature = "str_split_whitespace_remainder", issue = "77998")]
1417 pub fn remainder(&self) -> Option<&'a str> {
1418 if self.inner.iter.iter.finished {
1419 return None;
1420 }
1421
1422 Some(unsafe { crate::str::from_utf8_unchecked(self.inner.iter.iter.v) })
1424 }
1425}
1426
1427#[stable(feature = "split_inclusive", since = "1.51.0")]
1428impl<'a, P: Pattern> Iterator for SplitInclusive<'a, P> {
1429 type Item = &'a str;
1430
1431 #[inline]
1432 fn next(&mut self) -> Option<&'a str> {
1433 self.0.next_inclusive()
1434 }
1435}
1436
1437#[stable(feature = "split_inclusive", since = "1.51.0")]
1438impl<'a, P: Pattern<Searcher<'a>: fmt::Debug>> fmt::Debug for SplitInclusive<'a, P> {
1439 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1440 f.debug_struct("SplitInclusive").field("0", &self.0).finish()
1441 }
1442}
1443
1444#[stable(feature = "split_inclusive", since = "1.51.0")]
1446impl<'a, P: Pattern<Searcher<'a>: Clone>> Clone for SplitInclusive<'a, P> {
1447 fn clone(&self) -> Self {
1448 SplitInclusive(self.0.clone())
1449 }
1450}
1451
1452#[stable(feature = "split_inclusive", since = "1.51.0")]
1453impl<'a, P: Pattern<Searcher<'a>: DoubleEndedSearcher<'a>>> DoubleEndedIterator
1454 for SplitInclusive<'a, P>
1455{
1456 #[inline]
1457 fn next_back(&mut self) -> Option<&'a str> {
1458 self.0.next_back_inclusive()
1459 }
1460}
1461
1462#[stable(feature = "split_inclusive", since = "1.51.0")]
1463impl<'a, P: Pattern> FusedIterator for SplitInclusive<'a, P> {}
1464
1465impl<'a, P: Pattern> SplitInclusive<'a, P> {
1466 #[inline]
1482 #[unstable(feature = "str_split_inclusive_remainder", issue = "77998")]
1483 pub fn remainder(&self) -> Option<&'a str> {
1484 self.0.remainder()
1485 }
1486}
1487
1488#[derive(Clone)]
1495#[stable(feature = "encode_utf16", since = "1.8.0")]
1496pub struct EncodeUtf16<'a> {
1497 pub(super) chars: Chars<'a>,
1498 pub(super) extra: u16,
1499}
1500
1501#[stable(feature = "collection_debug", since = "1.17.0")]
1502impl fmt::Debug for EncodeUtf16<'_> {
1503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1504 f.debug_struct("EncodeUtf16").finish_non_exhaustive()
1505 }
1506}
1507
1508#[stable(feature = "encode_utf16", since = "1.8.0")]
1509impl<'a> Iterator for EncodeUtf16<'a> {
1510 type Item = u16;
1511
1512 #[inline]
1513 fn next(&mut self) -> Option<u16> {
1514 if self.extra != 0 {
1515 let tmp = self.extra;
1516 self.extra = 0;
1517 return Some(tmp);
1518 }
1519
1520 let mut buf = [0; 2];
1521 self.chars.next().map(|ch| {
1522 let n = ch.encode_utf16(&mut buf).len();
1523 if n == 2 {
1524 self.extra = buf[1];
1525 }
1526 buf[0]
1527 })
1528 }
1529
1530 #[inline]
1531 fn size_hint(&self) -> (usize, Option<usize>) {
1532 let len = self.chars.iter.len();
1533 if self.extra == 0 {
1539 (len.div_ceil(3), Some(len))
1540 } else {
1541 (len.div_ceil(3) + 1, Some(len + 1))
1544 }
1545 }
1546
1547 #[inline]
1548 fn count(self) -> usize {
1549 let extra = if self.extra == 0 { 0 } else { 1 };
1550 self.chars.as_str().as_bytes().iter().fold(extra, |acc, &byte| {
1562 acc.wrapping_add({
1563 if byte < 0b1000_0000 {
1564 1
1566 } else if byte < 0b1100_0000 {
1567 0
1569 } else if byte < 0b1111_0000 {
1570 1
1573 } else {
1574 2
1579 }
1580 })
1581 })
1582 }
1583}
1584
1585#[stable(feature = "fused", since = "1.26.0")]
1586impl FusedIterator for EncodeUtf16<'_> {}
1587
1588#[stable(feature = "str_escape", since = "1.34.0")]
1590#[derive(Clone, Debug)]
1591pub struct EscapeDebug<'a> {
1592 pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeDebug, CharEscapeDebug>,
1593}
1594
1595#[stable(feature = "str_escape", since = "1.34.0")]
1597#[derive(Clone, Debug)]
1598pub struct EscapeDefault<'a> {
1599 pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeDefault, CharEscapeDefault>,
1600}
1601
1602impl<'a> EscapeDefault<'a> {
1603 #[unstable(feature = "std_internals", issue = "none")]
1606 pub fn into_parts(
1607 self,
1608 ) -> (Option<impl Iterator<Item = char>>, Option<Chars<'a>>, Option<impl Iterator<Item = char>>)
1609 {
1610 self.inner.into_parts()
1611 }
1612}
1613
1614#[stable(feature = "str_escape", since = "1.34.0")]
1616#[derive(Clone, Debug)]
1617pub struct EscapeUnicode<'a> {
1618 pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeUnicode, CharEscapeUnicode>,
1619}
1620
1621macro_rules! escape_types_impls {
1622 ($( $Name: ident ),+) => {$(
1623 #[stable(feature = "str_escape", since = "1.34.0")]
1624 impl<'a> fmt::Display for $Name<'a> {
1625 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1626 self.clone().try_for_each(|c| f.write_char(c))
1627 }
1628 }
1629
1630 #[stable(feature = "str_escape", since = "1.34.0")]
1631 impl<'a> Iterator for $Name<'a> {
1632 type Item = char;
1633
1634 #[inline]
1635 fn next(&mut self) -> Option<char> { self.inner.next() }
1636
1637 #[inline]
1638 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1639
1640 #[inline]
1641 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
1642 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Output = Acc>
1643 {
1644 self.inner.try_fold(init, fold)
1645 }
1646
1647 #[inline]
1648 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1649 where Fold: FnMut(Acc, Self::Item) -> Acc,
1650 {
1651 self.inner.fold(init, fold)
1652 }
1653 }
1654
1655 #[stable(feature = "str_escape", since = "1.34.0")]
1656 impl<'a> FusedIterator for $Name<'a> {}
1657 )+}
1658}
1659
1660escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);