1
0
mirror of https://github.com/shimunn/gitredditor.git synced 2023-11-17 18:42:43 +01:00

init buffer

This commit is contained in:
shimunn 2019-05-05 17:56:05 +02:00
parent e26ee189d7
commit fe2db9b8dc

View File

@ -16,11 +16,21 @@ pub struct Comment {
pub struct Comments { pub struct Comments {
pub url: String, pub url: String,
continuation: Option<String>, continuation: Option<String>,
buffer: Box<Iterator<Item = Result<Comment, Box<Error>>>>, buffer: Option<Box<Iterator<Item = Result<Comment, Box<Error>>>>>,
}
impl Comments {
fn new<T: ToString>(url: T) -> Comments {
let url = url.to_string();
Comments {
url: url,
continuation: None,
buffer: None,
}
}
} }
impl Iterator for Comments { impl Iterator for Comments {
type Item = Result<Comment, Box<Error>>; type Item = Result<Comment, Box<Error>>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
@ -32,20 +42,34 @@ impl Iterator for Comments {
return Ok((comments, continuation)); return Ok((comments, continuation));
} }
if let Some(comment) = self.buffer.next() { if let (Some(ref mut buffer), ref mut continuation, ref url) =
(&mut self.buffer, &mut self.continuation, &self.url)
{
if let Some(comment) = buffer.next() {
Some(comment) Some(comment)
} else { } else {
self.continuation.clone().and_then(|cont| { continuation.clone().and_then(|cont| {
let page = request_paged(&(url.to_string() + "?after=" + &cont[..]));
match page {
Ok((comments, cont)) => {
**continuation = cont;
*buffer = Box::new(comments.into_iter().map(Ok))
}
Err(e) => *buffer = Box::new(iter::once(Err(e))),
};
buffer.next()
})
}
} else {
let page = request_paged(&self.url); let page = request_paged(&self.url);
match page { match page {
Ok((comments, cont)) => { Ok((comments, cont)) => {
self.continuation = cont; self.continuation = cont;
self.buffer = Box::new(comments.into_iter().map(Ok)) self.buffer = Some(Box::new(comments.into_iter().map(Ok)))
} }
Err(e) => self.buffer = Box::new(iter::once(Err(e))), Err(e) => self.buffer = Some(Box::new(iter::once(Err(e)))),
}; };
self.buffer.next() self.buffer.as_mut().and_then(|it| it.next())
})
} }
} }
} }