Repository: tokio-rs/tokio
File: tokio/src/sync/mpsc/bounded.rs (Rust)

Code before:
    ///     // Sending on the permit succeeds
    ///     permit.send(456);
    ///
    ///     // The value sent on the permit is received
    ///     assert_eq!(rx.recv().await.unwrap(), 456);
    ///
    /// }
    /// ```
    pub fn try_reserve(&self) -> Result<Permit<'_, T>, TrySendError<()>> {
        match self.chan.semaphore().semaphore.try_acquire(1) {
            Ok(()) => {}
            Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(())),
            Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(())),
        }

        Ok(Permit { chan: &self.chan })
    }

    /// Tries to acquire `n` slot in the channel without waiting for the slot to become
    /// available.
    ///
    /// If the channel is full this function will return a [`TrySendError`], otherwise
    /// A [`PermitIterator`] is returned to track the reserved capacity.
    /// You can call this [`Iterator`] until it is exhausted to
    /// get a [`Permit`] and then call [`Permit::send`]. This function is similar to
    /// [`reserve_many`] except it does not await for the slot to become available.
    ///
    /// Dropping [`PermitIterator`] without sending a message releases the capacity back
    /// to the channel.
    ///
    /// [`PermitIterator`]: PermitIterator
    /// [`send`]: Permit::send
    /// [`reserve_many`]: Sender::reserve_many
    ///
    /// # Examples
    ///
    /// ```
    /// use tokio::sync::mpsc;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let (tx, mut rx) = mpsc::channel(2);
    ///
    ///     // Reserve capacity
    ///     let mut permit = tx.try_reserve_many(2).unwrap();
    ///
    ///     // Trying to send directly on the `tx` will fail due to no
    ///     // available capacity.
    ///     assert!(tx.try_send(123).is_err());
    ///
    ///     // Trying to reserve an additional slot on the `tx` will

Review comment (bug):
A few notes on the wording here:

 * We should explain the normal case first, so start I would prefer to start the paragraph by talking about the case where you get a `PermitIterator`.
 * You say that it returns a `TrySendError` when the channel is full. That is not wrong, but imprecise. You should say which _kind_ of `TrySendError` it returns. (That is, `TrySendError::Full`.)
 * There are other cases than "channel is full" where you get the `TrySendError::Full` error. It also happens if there are fewer than `n` permits available, even if the number of available permits is non-zero.
 * You should mention that this can also fail with a `TrySendError::Closed` error.
 * If you make the other function panic on `n > self.max_capacity()`, then you should explicitly say that this method *doesn't* panic in that case, since we can just handle it by returning `TrySendError::Full`.

Code after:
    /// When multiple [`OwnedPermit`]s are needed, or the sender cannot be moved
    /// by value, it can be inexpensively cloned before calling `reserve_owned`:
    ///
    /// ```
    /// use tokio::sync::mpsc;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let (tx, mut rx) = mpsc::channel(1);
    ///
    ///     // Clone the sender and reserve capacity.
    ///     let permit = tx.clone().reserve_owned().await.unwrap();
    ///
    ///     // Trying to send directly on the `tx` will fail due to no
    ///     // available capacity.
    ///     assert!(tx.try_send(123).is_err());
    ///
    ///     // Sending on the permit succeeds.
    ///     permit.send(456);
    ///
    ///     // The value sent on the permit is received
    ///     assert_eq!(rx.recv().await.unwrap(), 456);
    /// }
    /// ```
    ///
    /// [`Sender::reserve`]: Sender::reserve
    /// [`OwnedPermit`]: OwnedPermit
    /// [`send`]: OwnedPermit::send
    /// [`Arc::clone`]: std::sync::Arc::clone
    pub async fn reserve_owned(self) -> Result<OwnedPermit<T>, SendError<()>> {
        self.reserve_inner(1).await?;
        Ok(OwnedPermit {
            chan: Some(self.chan),
        })
    }

    async fn reserve_inner(&self, n: usize) -> Result<(), SendError<()>> {
        crate::trace::async_trace_leaf().await;

        if n > self.max_capacity() {
            return Err(SendError(()));
        }
        match self.chan.semaphore().semaphore.acquire(n).await {
            Ok(()) => Ok(()),
            Err(_) => Err(SendError(())),
        }
    }

    /// Tries to acquire a slot in the channel without waiting for the slot to become
    /// available.
    ///