From fe2db9b8dcee580f2804372f604a138ebd2ff85d Mon Sep 17 00:00:00 2001 From: shimunn <> Date: Sun, 5 May 2019 17:56:05 +0200 Subject: [PATCH] init buffer --- src/model.rs | 54 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/src/model.rs b/src/model.rs index 043a11e..8013b08 100644 --- a/src/model.rs +++ b/src/model.rs @@ -16,11 +16,21 @@ pub struct Comment { pub struct Comments { pub url: String, continuation: Option, - buffer: Box>>>, + buffer: Option>>>>, +} + +impl Comments { + fn new(url: T) -> Comments { + let url = url.to_string(); + Comments { + url: url, + continuation: None, + buffer: None, + } + } } impl Iterator for Comments { - type Item = Result>; fn next(&mut self) -> Option { @@ -32,20 +42,34 @@ impl Iterator for Comments { return Ok((comments, continuation)); } - if let Some(comment) = self.buffer.next() { - Some(comment) + 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) + } else { + 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 { - self.continuation.clone().and_then(|cont| { - let page = request_paged(&self.url); - match page { - Ok((comments, cont)) => { - self.continuation = cont; - self.buffer = Box::new(comments.into_iter().map(Ok)) - } - Err(e) => self.buffer = Box::new(iter::once(Err(e))), - }; - self.buffer.next() - }) + let page = request_paged(&self.url); + match page { + Ok((comments, cont)) => { + self.continuation = cont; + self.buffer = Some(Box::new(comments.into_iter().map(Ok))) + } + Err(e) => self.buffer = Some(Box::new(iter::once(Err(e)))), + }; + self.buffer.as_mut().and_then(|it| it.next()) } } }