diff --git a/tower/src/buffer/layer.rs b/tower/src/buffer/layer.rs index 17cfef834..d410faa01 100644 --- a/tower/src/buffer/layer.rs +++ b/tower/src/buffer/layer.rs @@ -20,6 +20,12 @@ impl BufferLayer { /// `bound` gives the maximal number of requests that can be queued for the service before /// backpressure is applied to callers. /// + /// + /// # Panics + /// + /// Panics if `bound` is zero. + /// + /// /// # A note on choosing a `bound` /// /// When [`Buffer`]'s implementation of [`poll_ready`] returns [`Poll::Ready`], it reserves a @@ -34,6 +40,7 @@ impl BufferLayer { /// [`call`]: crate::Service::call /// [`poll_ready`]: crate::Service::poll_ready pub const fn new(bound: usize) -> Self { + assert!(bound > 0, "buffer bound must be greater than zero"); BufferLayer { bound, _p: PhantomData, diff --git a/tower/src/buffer/service.rs b/tower/src/buffer/service.rs index 9493f1074..a356b540e 100644 --- a/tower/src/buffer/service.rs +++ b/tower/src/buffer/service.rs @@ -33,6 +33,10 @@ where /// The default Tokio executor is used to run the given service, which means that this method /// must be called while on the Tokio runtime. /// + /// # Panics + /// + /// Panics if `bound` is zero. + /// /// # A note on choosing a `bound` /// /// When [`Buffer`]'s implementation of [`poll_ready`] returns [`Poll::Ready`], it reserves a @@ -63,6 +67,10 @@ where /// This is useful if you do not want to spawn directly onto the tokio runtime /// but instead want to use your own executor. This will return the [`Buffer`] and /// the background `Worker` that you can then spawn. + /// + /// # Panics + /// + /// Panics if `bound` is zero. pub fn pair(service: S, bound: usize) -> (Self, Worker) where S: Service + Send + 'static, @@ -70,6 +78,7 @@ where S::Error: Into + Send + Sync, Req: Send + 'static, { + assert!(bound > 0, "buffer bound must be greater than zero"); let (tx, rx) = mpsc::channel(bound); let (handle, worker) = Worker::new(service, rx); let buffer = Self { diff --git a/tower/tests/buffer/main.rs b/tower/tests/buffer/main.rs index ee238f11c..d9f83d90c 100644 --- a/tower/tests/buffer/main.rs +++ b/tower/tests/buffer/main.rs @@ -457,3 +457,20 @@ fn new_service_with_bound(bound: usize) -> (mock::Spawn, Handle) { svc }) } + +#[test] +#[should_panic(expected = "buffer bound must be greater than zero")] +fn buffer_new_zero_bound_panics() { + let (service, _handle) = mock::pair::<(), ()>(); + let _ = Buffer::new(service, 0); +} + +#[test] +#[should_panic(expected = "buffer bound must be greater than zero")] +fn buffer_layer_zero_bound_panics() { + use tower::Layer; + + let (service, _handle) = mock::pair::<(), ()>(); + let layer = tower::buffer::BufferLayer::new(0); + let _ = layer.layer(service); +}