@@ -278,7 +278,7 @@ impl AsciiStr {
278278 /// assert_eq!("white \tspace", example.trim());
279279 /// ```
280280 #[ must_use]
281- pub fn trim ( & self ) -> & Self {
281+ pub const fn trim ( & self ) -> & Self {
282282 self . trim_start ( ) . trim_end ( )
283283 }
284284
@@ -291,14 +291,16 @@ impl AsciiStr {
291291 /// assert_eq!("white \tspace \t", example.trim_start());
292292 /// ```
293293 #[ 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)
302304 }
303305
304306 /// Returns an ASCII string slice with trailing whitespace removed.
@@ -310,20 +312,16 @@ impl AsciiStr {
310312 /// assert_eq!(" \twhite \tspace", example.trim_end());
311313 /// ```
312314 #[ 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+ }
326323 }
324+ AsciiStr :: new ( trimmed)
327325 }
328326
329327 /// Compares two strings case-insensitively.
0 commit comments