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