Skip to content

Commit

Permalink
refactor: replace .boxed() streams with Either
Browse files Browse the repository at this point in the history
This commit replaces `BoxStream`s with streams wrapped by an `Either` to
save an unnecessary allocation (respectively leaving it to client code).
  • Loading branch information
matyama committed Jul 27, 2024
1 parent 6966e75 commit 335aa84
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
15 changes: 11 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::borrow::Cow;
use std::future::Future;
use std::sync::{Arc, OnceLock};

use futures_util::stream::{BoxStream, Stream, StreamExt as _};
use futures_util::stream::{Stream, StreamExt as _};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use url::Url;
Expand Down Expand Up @@ -213,20 +213,27 @@ impl Client {
}
}

pub fn shorten<'a, S>(&self, urls: S, ordering: Ordering) -> BoxStream<'a, Result<Bitlink>>
pub fn shorten<'a, S>(
&self,
urls: S,
ordering: Ordering,
) -> impl Stream<Item = Result<Bitlink>> + 'a
where
S: Stream<Item = Url> + Send + 'a,
{
let client = Arc::clone(&self.inner);
let max_concurrent = client.cfg.max_concurrent;

match ordering {
Ordering::Ordered => client.shorten_all(urls).buffered(max_concurrent).boxed(),
Ordering::Ordered => client
.shorten_all(urls)
.buffered(max_concurrent)
.left_stream(),

Ordering::Unordered => client
.shorten_all(urls)
.buffer_unordered(max_concurrent)
.boxed(),
.right_stream(),
}
}
}
8 changes: 5 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::pin::pin;

use clap::Parser as _;
use futures_util::stream::{self, StreamExt as _};

Expand Down Expand Up @@ -42,12 +44,12 @@ async fn main() {
let Some(urls) = io::read_input::<url::Url>() else {
return;
};
urls.map(|url| crash_if_err!(url)).boxed()
urls.map(|url| crash_if_err!(url)).left_stream()
} else {
stream::iter(args.urls).boxed()
stream::iter(args.urls).right_stream()
};

let mut results = client.shorten(urls, args.ordering);
let mut results = pin!(client.shorten(urls, args.ordering));

match args.ordering {
Ordering::Ordered => {
Expand Down

0 comments on commit 335aa84

Please sign in to comment.