Skip to content

Commit

Permalink
take_while for queues
Browse files Browse the repository at this point in the history
  • Loading branch information
TimLuq committed Aug 18, 2024
1 parent 3e8eb4e commit 92f878b
Showing 2 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/queue/byte_queue.rs
Original file line number Diff line number Diff line change
@@ -467,6 +467,21 @@ impl<'a> ByteQueue<'a> {
let (start, end) = self.check_range(range);
super::DrainBytes::new(self, start, end)
}

/// Move data to the returned `ByteQueue` until the byte predicate returns `false`.
#[inline]
#[must_use]
pub fn take_while<F: FnMut(u8) -> bool>(&mut self, mut fun: F) -> Self {
let Some(position) = self.find_byte(|bte| !fun(bte)) else {
return core::mem::replace(self, Self::new());
};
if position == 0 {
return Self::new();
}
let mut ret: Self = self.split_off(position);
core::mem::swap(self, &mut ret);
ret
}
}

impl<'a> From<ByteData<'a>> for ByteQueue<'a> {
22 changes: 22 additions & 0 deletions src/queue/string_queue.rs
Original file line number Diff line number Diff line change
@@ -365,6 +365,28 @@ impl<'a> StringQueue<'a> {
// SAFETY: The range is checked to be valid UTF-8.
unsafe { super::DrainChars::new(self, start, end) }
}

/// Find the first byte position of a char in the queue.
#[inline]
#[must_use]
pub fn find_char<F: FnMut(char) -> bool>(&mut self, mut fun: F) -> Option<usize> {
self.chars_indecies().find(|&(_, ch)| fun(ch)).map(|(position, _)| position)
}

/// Move data to the returned `StringQueue` until the char predicate returns `false`.
#[inline]
#[must_use]
pub fn take_while<F: FnMut(char) -> bool>(&mut self, mut fun: F) -> Self {
let Some(position) = self.find_char(|ch| !fun(ch)) else {
return core::mem::replace(self, Self::new());
};
if position == 0 {
return Self::new();
}
let mut ret = self.queue.split_off(position);
core::mem::swap(&mut self.queue, &mut ret);
Self { queue: ret }
}
}

impl<'a> From<StringData<'a>> for StringQueue<'a> {

0 comments on commit 92f878b

Please sign in to comment.