use alloc::{vec, vec::Vec};
use core::{fmt, iter::FusedIterator, num::NonZeroUsize};
use super::PollEvent;
#[derive(Debug)]
pub struct PollEvents {
capacity: NonZeroUsize,
events: Vec<PollEvent>,
}
impl PollEvents {
pub fn new(capacity: NonZeroUsize) -> Self {
Self {
capacity,
events: Vec::with_capacity(capacity.get()),
}
}
pub const fn capacity(&self) -> NonZeroUsize {
self.capacity
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn as_slice(&self) -> &[PollEvent] {
&self.events
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = &PollEvent> + '_ {
self.events.iter()
}
pub fn get(&self, index: usize) -> Option<&PollEvent> {
self.events.get(index)
}
pub fn clear(&mut self) {
self.events.clear();
}
pub fn try_push(&mut self, event: PollEvent) -> Result<(), PollEventsError> {
if self.events.len() >= self.capacity.get() {
return Err(PollEventsError {
event,
capacity: self.capacity,
});
}
self.events.push(event);
Ok(())
}
pub fn drain(&mut self) -> PollEventsDrain<'_> {
PollEventsDrain {
events: self.events.drain(..),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PollEventsError {
event: PollEvent,
capacity: NonZeroUsize,
}
impl PollEventsError {
pub const fn event(self) -> PollEvent {
self.event
}
pub const fn capacity(self) -> NonZeroUsize {
self.capacity
}
}
impl fmt::Display for PollEventsError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"readiness batch capacity of {} was reached",
self.capacity
)
}
}
impl core::error::Error for PollEventsError {}
pub struct PollEventsDrain<'a> {
events: vec::Drain<'a, PollEvent>,
}
impl fmt::Debug for PollEventsDrain<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PollEventsDrain")
.field("remaining", &self.events.len())
.finish()
}
}
impl Iterator for PollEventsDrain<'_> {
type Item = PollEvent;
fn next(&mut self) -> Option<Self::Item> {
self.events.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.events.size_hint()
}
}
impl ExactSizeIterator for PollEventsDrain<'_> {}
impl FusedIterator for PollEventsDrain<'_> {}
impl<'a> IntoIterator for &'a PollEvents {
type Item = &'a PollEvent;
type IntoIter = core::slice::Iter<'a, PollEvent>;
fn into_iter(self) -> Self::IntoIter {
self.events.iter()
}
}