1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
|
use std::{
cell::{RefCell, UnsafeCell},
cmp::Ordering,
pin::Pin,
task::Context,
task::Poll,
task::Waker,
};
use crate::generator::{BundleIterator, BundleStream};
use chunky_vec::ChunkyVec;
use futures::{ready, Stream};
use pin_cell::{PinCell, PinMut};
pub struct Cache<I, R>
where
I: Iterator,
{
iter: RefCell<I>,
items: UnsafeCell<ChunkyVec<I::Item>>,
res: std::marker::PhantomData<R>,
}
impl<I, R> Cache<I, R>
where
I: Iterator,
{
pub fn new(iter: I) -> Self {
Self {
iter: RefCell::new(iter),
items: Default::default(),
res: std::marker::PhantomData,
}
}
pub fn len(&self) -> usize {
unsafe {
let items = self.items.get();
(*items).len()
}
}
pub fn get(&self, index: usize) -> Option<&I::Item> {
unsafe {
let items = self.items.get();
(*items).get(index)
}
}
/// Push, immediately getting a reference to the element
pub fn push_get(&self, new_value: I::Item) -> &I::Item {
unsafe {
let items = self.items.get();
(*items).push_get(new_value)
}
}
}
impl<I, R> Cache<I, R>
where
I: BundleIterator + Iterator,
{
pub fn prefetch(&self) {
self.iter.borrow_mut().prefetch_sync();
}
}
pub struct CacheIter<'a, I, R>
where
I: Iterator,
{
cache: &'a Cache<I, R>,
curr: usize,
}
impl<'a, I, R> Iterator for CacheIter<'a, I, R>
where
I: Iterator,
{
type Item = &'a I::Item;
fn next(&mut self) -> Option<Self::Item> {
let cache_len = self.cache.len();
match self.curr.cmp(&cache_len) {
Ordering::Less => {
// Cached value
self.curr += 1;
self.cache.get(self.curr - 1)
}
Ordering::Equal => {
// Get the next item from the iterator
let item = self.cache.iter.borrow_mut().next();
self.curr += 1;
if let Some(item) = item {
Some(self.cache.push_get(item))
} else {
None
}
}
Ordering::Greater => {
// Ran off the end of the cache
None
}
}
}
}
impl<'a, I, R> IntoIterator for &'a Cache<I, R>
where
I: Iterator,
{
type Item = &'a I::Item;
type IntoIter = CacheIter<'a, I, R>;
fn into_iter(self) -> Self::IntoIter {
CacheIter {
cache: self,
curr: 0,
}
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct AsyncCache<S, R>
where
S: Stream,
{
stream: PinCell<S>,
items: UnsafeCell<ChunkyVec<S::Item>>,
// TODO: Should probably be an SmallVec<[Waker; 1]> or something? I guess
// multiple pending wakes are not really all that common.
pending_wakes: RefCell<Vec<Waker>>,
res: std::marker::PhantomData<R>,
}
impl<S, R> AsyncCache<S, R>
where
S: Stream,
{
pub fn new(stream: S) -> Self {
Self {
stream: PinCell::new(stream),
items: Default::default(),
pending_wakes: Default::default(),
res: std::marker::PhantomData,
}
}
pub fn len(&self) -> usize {
unsafe {
let items = self.items.get();
(*items).len()
}
}
pub fn get(&self, index: usize) -> Poll<Option<&S::Item>> {
unsafe {
let items = self.items.get();
(*items).get(index).into()
}
}
/// Push, immediately getting a reference to the element
pub fn push_get(&self, new_value: S::Item) -> &S::Item {
unsafe {
let items = self.items.get();
(*items).push_get(new_value)
}
}
pub fn stream(&self) -> AsyncCacheStream<'_, S, R> {
AsyncCacheStream {
cache: self,
curr: 0,
}
}
}
impl<S, R> AsyncCache<S, R>
where
S: BundleStream + Stream,
{
pub async fn prefetch(&self) {
let pin = unsafe { Pin::new_unchecked(&self.stream) };
unsafe { PinMut::as_mut(&mut pin.borrow_mut()).get_unchecked_mut() }
.prefetch_async()
.await;
}
}
impl<S, R> AsyncCache<S, R>
where
S: Stream,
{
// Helper function that gets the next value from wrapped stream.
fn poll_next_item(&self, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
let pin = unsafe { Pin::new_unchecked(&self.stream) };
let poll = PinMut::as_mut(&mut pin.borrow_mut()).poll_next(cx);
if poll.is_ready() {
let wakers = std::mem::take(&mut *self.pending_wakes.borrow_mut());
for waker in wakers {
waker.wake();
}
} else {
self.pending_wakes.borrow_mut().push(cx.waker().clone());
}
poll
}
}
pub struct AsyncCacheStream<'a, S, R>
where
S: Stream,
{
cache: &'a AsyncCache<S, R>,
curr: usize,
}
impl<'a, S, R> Stream for AsyncCacheStream<'a, S, R>
where
S: Stream,
{
type Item = &'a S::Item;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
let cache_len = self.cache.len();
match self.curr.cmp(&cache_len) {
Ordering::Less => {
// Cached value
self.curr += 1;
self.cache.get(self.curr - 1)
}
Ordering::Equal => {
// Get the next item from the stream
let item = ready!(self.cache.poll_next_item(cx));
self.curr += 1;
if let Some(item) = item {
Some(self.cache.push_get(item)).into()
} else {
None.into()
}
}
Ordering::Greater => {
// Ran off the end of the cache
None.into()
}
}
}
}
|