@@ -160,6 +160,19 @@ pub trait Pattern: Sized {
160160 None
161161 }
162162 }
163+
164+ /// Returns the pattern as utf-8 bytes if possible.
165+ fn as_utf8_pattern ( & self ) -> Option < Utf8Pattern < ' _ > > ;
166+ }
167+ /// Result of calling [`Pattern::as_utf8_pattern()`].
168+ /// Can be used for inspecting the contents of a [`Pattern`] in cases
169+ /// where the underlying representation can be represented as UTF-8.
170+ #[ derive( Copy , Clone , Eq , PartialEq , Debug ) ]
171+ pub enum Utf8Pattern < ' a > {
172+ /// Type returned by String and str types.
173+ Slice ( & ' a [ u8 ] ) ,
174+ /// Type returned by char types.
175+ Char ( char ) ,
163176}
164177
165178// Searcher
@@ -599,6 +612,11 @@ impl Pattern for char {
599612 {
600613 self . encode_utf8 ( & mut [ 0u8 ; 4 ] ) . strip_suffix_of ( haystack)
601614 }
615+
616+ #[ inline]
617+ fn as_utf8_pattern ( & self ) -> Option < Utf8Pattern < ' _ > > {
618+ Some ( Utf8Pattern :: Char ( * self ) )
619+ }
602620}
603621
604622/////////////////////////////////////////////////////////////////////////////
@@ -657,6 +675,11 @@ impl<C: MultiCharEq> Pattern for MultiCharEqPattern<C> {
657675 fn into_searcher ( self , haystack : & str ) -> MultiCharEqSearcher < ' _ , C > {
658676 MultiCharEqSearcher { haystack, char_eq : self . 0 , char_indices : haystack. char_indices ( ) }
659677 }
678+
679+ #[ inline]
680+ fn as_utf8_pattern ( & self ) -> Option < Utf8Pattern < ' _ > > {
681+ None
682+ }
660683}
661684
662685unsafe impl < ' a , C : MultiCharEq > Searcher < ' a > for MultiCharEqSearcher < ' a , C > {
@@ -747,6 +770,11 @@ macro_rules! pattern_methods {
747770 {
748771 ( $pmap) ( self ) . strip_suffix_of( haystack)
749772 }
773+
774+ #[ inline]
775+ fn as_utf8_pattern( & self ) -> Option <Utf8Pattern <' _>> {
776+ None
777+ }
750778 } ;
751779}
752780
@@ -1022,6 +1050,11 @@ impl<'b> Pattern for &'b str {
10221050 None
10231051 }
10241052 }
1053+
1054+ #[ inline]
1055+ fn as_utf8_pattern ( & self ) -> Option < Utf8Pattern < ' _ > > {
1056+ Some ( Utf8Pattern :: Slice ( self . as_bytes ( ) ) )
1057+ }
10251058}
10261059
10271060/////////////////////////////////////////////////////////////////////////////
0 commit comments