tryReadTBMChan :: TBMChan a -> STM (Maybe (Maybe a))
tryReadTBMChan (TBMChan closed limit chan) = do
    b  <- isEmptyTChan chan
    b' <- readTVar closed
    if b && b'
        then return Nothing
        else do
            mx <- tryReadTChan chan
            case mx of
                Nothing -> return (Just Nothing)
                Just _x -> do
                    modifyTVar' limit (1 +)
                    return (Just mx)


-- | Get the next value from the @TBMChan@ without removing it,
-- retrying if the channel is empty.
tryReadTBMChan :: TBMChan a -> STM (Maybe (Maybe a))
tryReadTBMChan (TBMChan closed limit chan) = do
    b  <- isEmptyTChan chan
    b' <- readTVar closed
    if b && b'
        then return Nothing
        else do
            mx <- tryReadTChan chan
            case mx of
                Nothing -> return (Just Nothing)
                Just _x -> do
                    modifyTVar' limit (1 +)
                    return (Just mx)


-- | Get the next value from the @TBMChan@ without removing it,
-- retrying if the channel is empty.
tryReadTBMChan (TBMChan closed limit chan) = do
    b  <- isEmptyTChan chan
    b' <- readTVar closed
    if b && b'
        then return Nothing
        else do
            mx <- tryReadTChan chan
            case mx of
                Nothing -> return (Just Nothing)
                Just _x -> do
                    modifyTVar' limit (1 +)
                    return (Just mx)


-- | Get the next value from the @TBMChan@ without removing it,
-- retrying if the channel is empty.