mod.rs - source
Skip to main content core/str/ mod.rs 1 //! String manipulation. 2 //! 3 //! For more details, see the [`std::str`] module. 4 //! 5 //! [`std::str`]: ../../std/str/index.html 6 7 #![stable(feature = "rust1" , since = "1.0.0" )] 8 9 mod converts ; 10 mod count ; 11 mod error ; 12 mod iter ; 13 mod traits ; 14 mod validations ; 15 16 use self ::pattern::{ DoubleEndedSearcher , Pattern , ReverseSearcher , Searcher }; 17 use crate ::char::{ self , EscapeDebugExtArgs }; 18 use crate ::hint::assert_unchecked ; 19 use crate ::range::Range ; 20 use crate ::slice::{ self , SliceIndex }; 21 use crate ::ub_checks::assert_unsafe_precondition ; 22 use crate ::{ ascii , mem }; 23 24 pub mod pattern ; 25 26 mod lossy ; 27 #[unstable(feature = "str_from_raw_parts" , issue = "119206" )] 28 pub use converts::{ from_raw_parts , from_raw_parts_mut }; 29 #[stable(feature = "rust1" , since = "1.0.0" )] 30 pub use converts::{ from_utf8 , from_utf8_unchecked }; 31 #[stable(feature = "str_mut_extras" , since = "1.20.0" )] 32 pub use converts::{ from_utf8_mut , from_utf8_unchecked_mut }; 33 #[stable(feature = "rust1" , since = "1.0.0" )] 34 pub use error::{ ParseBoolError , Utf8Error }; 35 #[stable(feature = "encode_utf16" , since = "1.8.0" )] 36 pub use iter::EncodeUtf16 ; 37 #[stable(feature = "rust1" , since = "1.0.0" )] 38 #[allow(deprecated)] 39 pub use iter::LinesAny ; 40 #[stable(feature = "split_ascii_whitespace" , since = "1.34.0" )] 41 pub use iter::SplitAsciiWhitespace ; 42 #[stable(feature = "split_inclusive" , since = "1.51.0" )] 43 pub use iter::SplitInclusive ; 44 #[stable(feature = "rust1" , since = "1.0.0" )] 45 pub use iter::{ Bytes , CharIndices , Chars , Lines , SplitWhitespace }; 46 #[stable(feature = "str_escape" , since = "1.34.0" )] 47 pub use iter::{ EscapeDebug , EscapeDefault , EscapeUnicode }; 48 #[stable(feature = "str_match_indices" , since = "1.5.0" )] 49 pub use iter::{ MatchIndices , RMatchIndices }; 50 use iter::{ MatchIndicesInternal , MatchesInternal , SplitInternal , SplitNInternal }; 51 #[stable(feature = "str_matches" , since = "1.2.0" )] 52 pub use iter::{ Matches , RMatches }; 53 #[stable(feature = "rust1" , since = "1.0.0" )] 54 pub use iter::{ RSplit , RSplitTerminator , Split , SplitTerminator }; 55 #[stable(feature = "rust1" , since = "1.0.0" )] 56 pub use iter::{ RSplitN , SplitN }; 57 #[stable(feature = "utf8_chunks" , since = "1.79.0" )] 58 pub use lossy::{ Utf8Chunk , Utf8Chunks }; 59 #[stable(feature = "rust1" , since = "1.0.0" )] 60 pub use traits::FromStr ; 61 #[unstable(feature = "str_internals" , issue = "none" )] 62 pub use validations::{ next_code_point , utf8_char_width }; 63 64 #[inline(never)] 65 #[cold] 66 #[track_caller] 67 #[rustc_allow_const_fn_unstable(const_eval_select)] 68 #[cfg(not(panic = "immediate-abort" ))] 69 const fn slice_error_fail(s: & str , begin: usize , end: usize ) -> ! { 70 crate ::intrinsics:: const_eval_select (( s , begin , end ), slice_error_fail_ct , slice_error_fail_rt ) 71 } 72 73 #[cfg(panic = "immediate-abort" )] 74 const fn slice_error_fail(s: & str, begin: usize, end: usize) -> ! { 75 slice_error_fail_ct(s, begin, end) 76 } 77 78 #[track_caller] 79 const fn slice_error_fail_ct( _ : & str , _ : usize , _ : usize ) -> ! { 80 panic! ( "failed to slice string" ); 81 } 82 83 #[track_caller] 84 fn slice_error_fail_rt(s: & str , begin: usize , end: usize ) -> ! { 85 let len = s . len (); 86 87 // 1. begin is OOB.
88 if begin > len { 89 panic! ( "start byte index {begin} is out of bounds for string of length {len}" ); 90 } 91 92 // 2. end is OOB. 93 if end > len { 94 panic! ( "end byte index {end} is out of bounds for string of length {len}" ); 95 } 96 97 // 3. range is backwards. 98 if begin > end { 99 panic! ( "byte range starts at {begin} but ends at {end}" ); 100 } 101 102 // 4. begin is inside a character. 103 if ! s . is_char_boundary ( begin ) { 104 let floor = s . floor_char_boundary ( begin ); 105 let ceil = s . ceil_char_boundary ( begin ); 106 let range = floor..ceil; 107 let ch = s [floor..ceil]. chars (). next (). unwrap (); 108 panic! ( 109 "start byte index {begin} is not a char boundary; it is inside {ch:?} (bytes {range:?} of string)" 110 ) 111 } 112 113 // 5. end is inside a character.
114 if ! s . is_char_boundary ( end ) { 115 let floor = s . floor_char_boundary ( end ); 116 let ceil = s . ceil_char_boundary ( end ); 117 let range = floor..ceil; 118 let ch = s [floor..ceil]. chars (). next (). unwrap (); 119 panic! ( 120 "end byte index {end} is not a char boundary; it is inside {ch:?} (bytes {range:?} of string)" 121 ) 122 } 123 124 // 6. end is OOB and range is inclusive (end == len). 125 // This test cannot be combined with 2. above because for cases like 126 // `"abcαβγ"[4..9]` the error is that 4 is inside 'α', not that 9 is OOB.
127 debug_assert_eq! (end, len); 128 panic! ( "end byte index {end} is out of bounds for string of length {len}" ); 129 } 130 131 impl str { 132 /// Returns the length of `self`. 133 /// 134 /// This length is in bytes, not [`char`]s or graphemes. In other words, 135 /// it might not be what a human considers the length of the string. 136 /// 137 /// [`char`]: prim@char 138 /// 139 /// # Examples 140 /// 141 /// ``` 142 /// let len = "foo".len(); 143 /// assert_eq!(3, len); 144 /// 145 /// assert_eq!("ƒoo".len(), 4); // fancy f!
146 /// assert_eq!("ƒoo".chars().count(), 3); 147 /// ``` 148 #[stable(feature = "rust1" , since = "1.0.0" )] 149 #[rustc_const_stable(feature = "const_str_len" , since = "1.39.0" )] 150 #[rustc_diagnostic_item = "str_len" ] 151 #[rustc_no_implicit_autorefs] 152 #[must_use] 153 #[inline] 154 #[allow(clippy::needless_as_bytes)] 155 pub const fn len( & self ) -> usize { 156 self . as_bytes (). len () 157 } 158 159 /// Returns `true` if `self` has a length of zero bytes.
160 /// 161 /// # Examples 162 /// 163 /// ``` 164 /// let s = ""; 165 /// assert!(s.is_empty()); 166 /// 167 /// let s = "not empty"; 168 /// assert!(!s.is_empty()); 169 /// ``` 170 #[stable(feature = "rust1" , since = "1.0.0" )] 171 #[rustc_const_stable(feature = "const_str_is_empty" , since = "1.39.0" )] 172 #[rustc_no_implicit_autorefs] 173 #[must_use] 174 #[inline] 175 pub const fn is_empty( & self ) -> bool { 176 self . len () == 0 177 } 178 179 /// Converts a slice of bytes to a string slice.
180 /// 181 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice 182 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between 183 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires 184 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid 185 /// UTF-8, and then does the conversion. 186 /// 187 /// [`&str`]: str 188 /// [byteslice]: prim@slice 189 /// 190 /// If you are sure that the byte slice is valid UTF-8, and you don't want to 191 /// incur the overhead of the validity check, there is an unsafe version of 192 /// this function, [`from_utf8_unchecked`], which has the same 193 /// behavior but skips the check.
194 /// 195 /// If you need a `String` instead of a `&str`, consider 196 /// [`String::from_utf8`][string]. 197 /// 198 /// [string]: ../std/string/struct.String.html#method.from_utf8 199 /// 200 /// Because you can stack-allocate a `[u8; N]`, and you can take a 201 /// [`&[u8]`][byteslice] of it, this function is one way to have a 202 /// stack-allocated string. There is an example of this in the 203 /// examples section below.
204 /// 205 /// [byteslice]: slice 206 /// 207 /// # Errors 208 /// 209 /// Returns `Err` if the slice is not UTF-8 with a description as to why the 210 /// provided slice is not UTF-8. 211 /// 212 /// # Examples 213 /// 214 /// Basic usage: 215 /// 216 /// ``` 217 /// // some bytes, in a vector 218 /// let sparkle_heart = vec![240, 159, 146, 150]; 219 /// 220 /// // We can use the ? (try) operator to check if the bytes are valid 221 /// let sparkle_heart = str::from_utf8(&sparkle_heart)?; 222 /// 223 /// assert_e
The rest of this page is on the live site.