@@ -277,7 +277,7 @@ impl AsciiStr {
277
277
/// assert_eq!("white \tspace", example.trim());
278
278
/// ```
279
279
#[ must_use]
280
- pub fn trim ( & self ) -> & Self {
280
+ pub const fn trim ( & self ) -> & Self {
281
281
self . trim_start ( ) . trim_end ( )
282
282
}
283
283
@@ -290,14 +290,16 @@ impl AsciiStr {
290
290
/// assert_eq!("white \tspace \t", example.trim_start());
291
291
/// ```
292
292
#[ must_use]
293
- pub fn trim_start ( & self ) -> & Self {
294
- let whitespace_len = self
295
- . chars ( )
296
- . position ( |ch| !ch. is_whitespace ( ) )
297
- . unwrap_or_else ( || self . len ( ) ) ;
298
-
299
- // SAFETY: `whitespace_len` is `0..=len`, which is at most `len`, which is a valid empty slice.
300
- unsafe { self . as_slice ( ) . get_unchecked ( whitespace_len..) . into ( ) }
293
+ pub const fn trim_start ( & self ) -> & Self {
294
+ let mut trimmed = & self . slice ;
295
+ while let Some ( ( first, rest) ) = trimmed. split_first ( ) {
296
+ if first. is_whitespace ( ) {
297
+ trimmed = rest;
298
+ } else {
299
+ break ;
300
+ }
301
+ }
302
+ AsciiStr :: new ( trimmed)
301
303
}
302
304
303
305
/// Returns an ASCII string slice with trailing whitespace removed.
@@ -309,20 +311,16 @@ impl AsciiStr {
309
311
/// assert_eq!(" \twhite \tspace", example.trim_end());
310
312
/// ```
311
313
#[ must_use]
312
- pub fn trim_end ( & self ) -> & Self {
313
- // Number of whitespace characters counting from the end
314
- let whitespace_len = self
315
- . chars ( )
316
- . rev ( )
317
- . position ( |ch| !ch. is_whitespace ( ) )
318
- . unwrap_or_else ( || self . len ( ) ) ;
319
-
320
- // SAFETY: `whitespace_len` is `0..=len`, which is at most `len`, which is a valid empty slice, and at least `0`, which is the whole slice.
321
- unsafe {
322
- self . as_slice ( )
323
- . get_unchecked ( ..self . len ( ) - whitespace_len)
324
- . into ( )
314
+ pub const fn trim_end ( & self ) -> & Self {
315
+ let mut trimmed = & self . slice ;
316
+ while let Some ( ( last, rest) ) = trimmed. split_last ( ) {
317
+ if last. is_whitespace ( ) {
318
+ trimmed = rest;
319
+ } else {
320
+ break ;
321
+ }
325
322
}
323
+ AsciiStr :: new ( trimmed)
326
324
}
327
325
328
326
/// Compares two strings case-insensitively.
0 commit comments