Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active January 10, 2025 16:31
Show Gist options
  • Save RandyMcMillan/2605f3e7971d7cf0f88abd22cc1c703c to your computer and use it in GitHub Desktop.
Save RandyMcMillan/2605f3e7971d7cf0f88abd22cc1c703c to your computer and use it in GitHub Desktop.
chunk_slice.rs
fn foo(slice: &[u8]) -> (&str, Option<&[u8]>) {
let mut iter = slice.utf8_chunks();
// Annoying behavior of this iterator
let Some(chunk) = iter.next() else {
return (std::str::from_utf8(slice).unwrap(), None)
};
let head = chunk.valid();
if head.len() < slice.len() {
(head, Some(&slice[head.len()..]))
} else {
(head, None)
}
}
fn main() {
dbg!(foo("".as_ref()));
dbg!(foo("hi".as_ref()));
dbg!(foo(b"foo\xF1\x80bar"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment