@@ -277,7 +277,7 @@ impl AsciiStr {
277277 /// assert_eq!("white \tspace", example.trim());
278278 /// ```
279279 #[ must_use]
280- pub fn trim ( & self ) -> & Self {
280+ pub const fn trim ( & self ) -> & Self {
281281 self . trim_start ( ) . trim_end ( )
282282 }
283283
@@ -290,14 +290,16 @@ impl AsciiStr {
290290 /// assert_eq!("white \tspace \t", example.trim_start());
291291 /// ```
292292 #[ 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)
301303 }
302304
303305 /// Returns an ASCII string slice with trailing whitespace removed.
@@ -309,20 +311,16 @@ impl AsciiStr {
309311 /// assert_eq!(" \twhite \tspace", example.trim_end());
310312 /// ```
311313 #[ 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+ }
325322 }
323+ AsciiStr :: new ( trimmed)
326324 }
327325
328326 /// Compares two strings case-insensitively.
0 commit comments