<commit_before>"""Queues"""

__all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'JoinableQueue']

import collections
import concurrent.futures
import heapq
import queue

from . import events
from . import futures
from . import locks
from .tasks import coroutine


class Queue:
    """A queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "yield from put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded Tulip application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    """

    def __init__(self, maxsize=0):
        self._event_loop = events.get_event_loop()
        self._maxsize = maxsize

        # Futures.
        self._getters = collections.deque([])
        # Pairs of (item, Future).
        self._putters = collections.deque([])
        self._init(maxsize)

    def _init(self, maxsize):
        self._queue = collections.deque()

    def _get(self):
        return self._queue.popleft()

    def _put(self, item):
        self._queue.append(item)

    def __repr__(self):
        return '<%s at %s %s>' % (
            type(self).__name__, hex(id(self)), self._format())

    def __str__(self):
        return '<%s %s>' % (type(self).__name__, self._format())

    def _format(self):
        result = 'maxsize=%r' % (self._maxsize, )
        if getattr(self, '_queue', None):
            result += ' _queue=%r' % list(self._queue)
        if self._getters:
            result += ' _getters[%s]' % len(self._getters)
        if self._putters:
            result += ' _putters[%s]' % len(self._putters)
        return result

    def _consume_done_getters(self, waiters):
        # Delete waiters at the head of the get() queue who've timed out.
        while waiters and waiters[0].done():
            waiters.popleft()

    def _consume_done_putters(self):
        # Delete waiters at the head of the put() queue who've timed out.
        while self._putters and self._putters[0][1].done():
            self._putters.popleft()

    def qsize(self):
        """Number of items in the queue."""
        return len(self._queue)

    @property
    def maxsize(self):
        """Number of items allowed in the queue."""
        return self._maxsize

    def empty(self):
        """Return True if the queue is empty, False otherwise."""
        return not self._queue

    def full(self):
        """Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        """
        if self._maxsize <= 0:
            return False
        else:
            return self.qsize() == self._maxsize

    @coroutine
    def put(self, item, timeout=None):
        """Put an item into the queue.

        If you yield from put() and timeout is None (the default), wait until a
        free slot is available before adding item.

        If a timeout is provided, raise queue.Full if no free slot becomes
        available before the timeout.
        """
        self._consume_done_getters(self._getters)
        if self._getters:
            assert not self._queue, (
                'queue non-empty, why are getters waiting?')

            getter = self._getters.popleft()

            # Use _put and _get instead of passing item straight to getter, in
            # case a subclass has logic that must run (e.g. JoinableQueue).
            self._put(item)
            getter.set_result(self._get())

        elif self._maxsize > 0 and self._maxsize == self.qsize():
            waiter = futures.Future(
                event_loop=self._event_loop, timeout=timeout)

            self._putters.append((item, waiter))
            try:
                yield from waiter
            except concurrent.futures.CancelledError:
                raise queue.Full

        else:
            self._put(item)

    def put_nowait(self, item):
        """Put an item into the queue without blocking.

        If no free slot is immediately available, raise queue.Full.
        """
        self._consume_done_getters(self._getters)
        if self._getters:
            assert not self._queue, (
                'queue non-empty, why are getters waiting?')

            getter = self._getters.popleft()

            # Use _put and _get instead of passing item straight to getter, in
            # case a subclass has logic that must run (e.g. JoinableQueue).
            self._put(item)
            getter.set_result(self._get())

        elif self._maxsize > 0 and self._maxsize == self.qsize():
            raise queue.Full
        else:
            self._put(item)

    @coroutine
    def get(self, timeout=None):
        """Remove and return an item from the queue.

        If you yield from get() and timeout is None (the default), wait until a
        item is available.

        If a timeout is provided, raise queue.Empty if no item is available
        before the timeout.
        """
        self._consume_done_putters()
        if self._putters:
            assert self.full(), 'queue not full, why are putters waiting?'
            item, putter = self._putters.popleft()
            self._put(item)

            # When a getter runs and frees up a slot so this putter can
            # run, we need to defer the put for a tick to ensure that
            # getters and putters alternate perfectly. See
            # ChannelTest.test_wait.
            self._event_loop.call_soon(putter.set_result, None)

            return self._get()

        elif self.qsize():
            return self._get()
        else:
            waiter = futures.Future(
                event_loop=self._event_loop, timeout=timeout)

            self._getters.append(waiter)
            try:
                return (yield from waiter)
            except concurrent.futures.CancelledError:
                raise queue.Empty

    def get_nowait(self):
        """Remove and return an item from the queue.

        Return an item if one is immediately available, else raise queue.Full.
        """
        self._consume_done_putters()
        if self._putters:
            assert self.full(), 'queue not full, why are putters waiting?'
            item, putter = self._putters.popleft()
            self._put(item)
            # Wake putter on next tick.
            putter.set_result(None)

            return self._get()

        elif self.qsize():
            return self._get()
        else:
            raise queue.Empty


class PriorityQueue(Queue):
    """A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    """

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item, heappush=heapq.heappush):
        heappush(self._queue, item)

    def _get(self, heappop=heapq.heappop):
        return heappop(self._queue)


class LifoQueue(Queue):
    """A subclass of Queue that retrieves most recently added entries first."""

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item):
        self._queue.append(item)

    def _get(self):
        return self._queue.pop()


class JoinableQueue(Queue):
    """A subclass of Queue with task_done() and join() methods."""

    def __init__(self, maxsize=0):
        self._unfinished_tasks = 0
        self._finished = locks.EventWaiter()
        self._finished.set()
        super(JoinableQueue, self).__init__(maxsize=maxsize)

    def _format(self):
        result = Queue._format(self)
        if self._unfinished_tasks:
            result += ' tasks=%s' % self._unfinished_tasks
        return result

    def _put(self, item):
        super(JoinableQueue, self)._put(item)
        self._unfinished_tasks += 1
        self._finished.clear()

    def task_done(self):
        """Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).<commit_msg>Use new-style super() in queues<commit_after>"""Queues"""

__all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'JoinableQueue']

import collections
import concurrent.futures
import heapq
import queue

from . import events
from . import futures
from . import locks
from .tasks import coroutine


class Queue:
    """A queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "yield from put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded Tulip application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    """

    def __init__(self, maxsize=0):
        self._event_loop = events.get_event_loop()
        self._maxsize = maxsize

        # Futures.
        self._getters = collections.deque([])
        # Pairs of (item, Future).
        self._putters = collections.deque([])
        self._init(maxsize)

    def _init(self, maxsize):
        self._queue = collections.deque()

    def _get(self):
        return self._queue.popleft()

    def _put(self, item):
        self._queue.append(item)

    def __repr__(self):
        return '<%s at %s %s>' % (
            type(self).__name__, hex(id(self)), self._format())

    def __str__(self):
        return '<%s %s>' % (type(self).__name__, self._format())

    def _format(self):
        result = 'maxsize=%r' % (self._maxsize, )
        if getattr(self, '_queue', None):
            result += ' _queue=%r' % list(self._queue)
        if self._getters:
            result += ' _getters[%s]' % len(self._getters)
        if self._putters:
            result += ' _putters[%s]' % len(self._putters)
        return result

    def _consume_done_getters(self, waiters):
        # Delete waiters at the head of the get() queue who've timed out.
        while waiters and waiters[0].done():
            waiters.popleft()

    def _consume_done_putters(self):
        # Delete waiters at the head of the put() queue who've timed out.
        while self._putters and self._putters[0][1].done():
            self._putters.popleft()

    def qsize(self):
        """Number of items in the queue."""
        return len(self._queue)

    @property
    def maxsize(self):
        """Number of items allowed in the queue."""
        return self._maxsize

    def empty(self):
        """Return True if the queue is empty, False otherwise."""
        return not self._queue

    def full(self):
        """Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        """
        if self._maxsize <= 0:
            return False
        else:
            return self.qsize() == self._maxsize

    @coroutine
    def put(self, item, timeout=None):
        """Put an item into the queue.

        If you yield from put() and timeout is None (the default), wait until a
        free slot is available before adding item.

        If a timeout is provided, raise queue.Full if no free slot becomes
        available before the timeout.
        """
        self._consume_done_getters(self._getters)
        if self._getters:
            assert not self._queue, (
                'queue non-empty, why are getters waiting?')

            getter = self._getters.popleft()

            # Use _put and _get instead of passing item straight to getter, in
            # case a subclass has logic that must run (e.g. JoinableQueue).
            self._put(item)
            getter.set_result(self._get())

        elif self._maxsize > 0 and self._maxsize == self.qsize():
            waiter = futures.Future(
                event_loop=self._event_loop, timeout=timeout)

            self._putters.append((item, waiter))
            try:
                yield from waiter
            except concurrent.futures.CancelledError:
                raise queue.Full

        else:
            self._put(item)

    def put_nowait(self, item):
        """Put an item into the queue without blocking.

        If no free slot is immediately available, raise queue.Full.
        """
        self._consume_done_getters(self._getters)
        if self._getters:
            assert not self._queue, (
                'queue non-empty, why are getters waiting?')

            getter = self._getters.popleft()

            # Use _put and _get instead of passing item straight to getter, in
            # case a subclass has logic that must run (e.g. JoinableQueue).
            self._put(item)
            getter.set_result(self._get())

        elif self._maxsize > 0 and self._maxsize == self.qsize():
            raise queue.Full
        else:
            self._put(item)

    @coroutine
    def get(self, timeout=None):
        """Remove and return an item from the queue.

        If you yield from get() and timeout is None (the default), wait until a
        item is available.

        If a timeout is provided, raise queue.Empty if no item is available
        before the timeout.
        """
        self._consume_done_putters()
        if self._putters:
            assert self.full(), 'queue not full, why are putters waiting?'
            item, putter = self._putters.popleft()
            self._put(item)

            # When a getter runs and frees up a slot so this putter can
            # run, we need to defer the put for a tick to ensure that
            # getters and putters alternate perfectly. See
            # ChannelTest.test_wait.
            self._event_loop.call_soon(putter.set_result, None)

            return self._get()

        elif self.qsize():
            return self._get()
        else:
            waiter = futures.Future(
                event_loop=self._event_loop, timeout=timeout)

            self._getters.append(waiter)
            try:
                return (yield from waiter)
            except concurrent.futures.CancelledError:
                raise queue.Empty

    def get_nowait(self):
        """Remove and return an item from the queue.

        Return an item if one is immediately available, else raise queue.Full.
        """
        self._consume_done_putters()
        if self._putters:
            assert self.full(), 'queue not full, why are putters waiting?'
            item, putter = self._putters.popleft()
            self._put(item)
            # Wake putter on next tick.
            putter.set_result(None)

            return self._get()

        elif self.qsize():
            return self._get()
        else:
            raise queue.Empty


class PriorityQueue(Queue):
    """A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    """

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item, heappush=heapq.heappush):
        heappush(self._queue, item)

    def _get(self, heappop=heapq.heappop):
        return heappop(self._queue)


class LifoQueue(Queue):
    """A subclass of Queue that retrieves most recently added entries first."""

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item):
        self._queue.append(item)

    def _get(self):
        return self._queue.pop()


class JoinableQueue(Queue):
    """A subclass of Queue with task_done() and join() methods."""

    def __init__(self, maxsize=0):
        self._unfinished_tasks = 0
        self._finished = locks.EventWaiter()
        self._finished.set()
        super().__init__(maxsize=maxsize)

    def _format(self):
        result = Queue._format(self)
        if self._unfinished_tasks:
            result += ' tasks=%s' % self._unfinished_tasks
        return result

    def _put(self, item):
        super()._put(item)
        self._unfinished_tasks += 1
        self._finished.clear()

    def task_done(self):
        """Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).
{'fraction_non_alphanumeric': 0.09351884466361395, 'fraction_numerical': 0.0014089468122578373, 'mean_word_length': 2.107442539219263, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '180172', 'n_tokens_mistral': 4845, 'n_tokens_neox': 4646, 'n_words': 1619}