Implement slice_shift_char using the std library

I would like to use the &str slice_shift_char , but it is marked as unstable in the documentation:

Unstable: waiting for offset and slice conventions and may not be warranted by the presence of characters and / or char_indices iterators

What would be a good way to implement this method using Rust current std library? So far, I:

 fn slice_shift_char(s: &str) -> Option<(char, &str)> { let mut ixs = s.char_indices(); let next = ixs.next(); match next { Some((next_pos, ch)) => { let rest = unsafe { s.slice_unchecked(next_pos, s.len()) }; Some((ch, rest)) }, None => None } } 

I would like to avoid calling slice_unchecked . I am using Rust 1.1.

+6
source share
2 answers

Ok, you can see the source code and you will get https://github.com/rust-lang/rust/blob/master/src/libcollections/str.rs#L776-L778 and https://github.com/rust -lang / rust / blob / master / src / libcore / str / mod.rs # L1531-L1539 . Second:

 fn slice_shift_char(&self) -> Option<(char, &str)> { if self.is_empty() { None } else { let ch = self.char_at(0); let next_s = unsafe { self.slice_unchecked(ch.len_utf8(), self.len()) }; Some((ch, next_s)) } } 

If you do not want this to be unsafe, you can simply use a regular slice:

 fn slice_shift_char(&self) -> Option<(char, &str)> { if self.is_empty() { None } else { let ch = self.char_at(0); let len = self.len(); let next_s = &self[ch.len_utf8().. len]; Some((ch, next_s)) } } 
+4
source

The unstable slice_shift_char function has slice_shift_char deprecated since Rust 1.9.0 and has been completely removed in Rust 1.11.0.

Starting with Rust 1.4.0, the recommended approach is :

  • Use .chars() to get char content iterator
  • Iterate on this iterator once to get the first character.
  • Call .as_str() on this iterator to restore the remaining concatenated string.
 fn slice_shift_char(a: &str) -> Option<(char, &str)> { let mut chars = a.chars(); chars.next().map(|c| (c, chars.as_str())) } fn main() { assert_eq!(slice_shift_char("hello"), Some(('h', "ello"))); assert_eq!(slice_shift_char("ĺḿńóṕ"), Some(('ĺ', "ḿńóṕ"))); assert_eq!(slice_shift_char(""), None); } 
+3
source

All Articles