Skip to content

Commit

Permalink
introduce the hold_max option
Browse files Browse the repository at this point in the history
  • Loading branch information
djugei committed May 2, 2024
1 parent 6c4637b commit b4e91f5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ where
pub struct ProgressBarIter<T> {
pub(crate) it: T,
pub progress: ProgressBar,
pub(crate) hold_max: bool,
}

impl<T> ProgressBarIter<T> {
Expand Down Expand Up @@ -192,6 +193,11 @@ impl<R: io::BufRead> io::BufRead for ProgressBarIter<R> {
impl<S: io::Seek> io::Seek for ProgressBarIter<S> {
fn seek(&mut self, f: io::SeekFrom) -> io::Result<u64> {
self.it.seek(f).map(|pos| {
let pos = if self.hold_max {
self.progress.position().max(pos)
} else {
pos
};
self.progress.set_position(pos);
pos
})
Expand All @@ -203,6 +209,21 @@ impl<S: io::Seek> io::Seek for ProgressBarIter<S> {
}
}

impl<S: io::Seek> ProgressBarIter<S> {
/// When random seeks are executed on the underlying io object the ProgressBar will jump harshly back and forth
/// setting hold_max to true keeps the progress to the maximum of the current and seeked-to position.
pub fn set_hold_max(&mut self, hold_max: bool) {
self.hold_max = hold_max
}
/// Builder-like function for holding the maximum reached position
///
/// See [`ProgressBarIter::set_hold_max()`].
pub fn with_hold_max(mut self, hold_max: bool) -> Self {
self.hold_max = hold_max;
self
}
}

#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
impl<W: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for ProgressBarIter<W> {
Expand Down Expand Up @@ -323,7 +344,11 @@ impl<W: io::Write> io::Write for ProgressBarIter<W> {

impl<S, T: Iterator<Item = S>> ProgressIterator for T {
fn progress_with(self, progress: ProgressBar) -> ProgressBarIter<Self> {
ProgressBarIter { it: self, progress }
ProgressBarIter {
it: self,
progress,
hold_max: false,
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/progress_bar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,7 @@ impl ProgressBar {
ProgressBarIter {
progress: self.clone(),
it: read,
hold_max: false,
}
}

Expand All @@ -468,6 +469,7 @@ impl ProgressBar {
ProgressBarIter {
progress: self.clone(),
it: write,
hold_max: false,
}
}

Expand Down

0 comments on commit b4e91f5

Please sign in to comment.