"""Threads, processes and asyncio snippets."""
import asyncio
from concurrent.futures import ThreadPoolExecutor


def parallel_map(fn, items, workers=8):
    """Run ``fn`` over items on a thread pool (good for I/O), keeping order.

    >>> parallel_map(lambda x: x * 2, [1, 2, 3])
    [2, 4, 6]
    """
    with ThreadPoolExecutor(max_workers=workers) as pool:
        return list(pool.map(fn, items))


async def gather_limited(coros, limit):
    """Await coroutines with at most ``limit`` running at once; results keep order.

    >>> async def double(x):
    ...     await asyncio.sleep(0)
    ...     return x * 2
    >>> asyncio.run(gather_limited([double(i) for i in range(5)], limit=2))
    [0, 2, 4, 6, 8]
    """
    sem = asyncio.Semaphore(limit)

    async def run(coro):
        async with sem:
            return await coro
    return await asyncio.gather(*(run(c) for c in coros))


async def with_timeout(coro, seconds, default=None):
    """Await ``coro`` but give up after ``seconds`` and return ``default``.

    >>> asyncio.run(with_timeout(asyncio.sleep(10, 'late'), 0.01, default='timeout'))
    'timeout'
    """
    try:
        return await asyncio.wait_for(coro, seconds)
    except asyncio.TimeoutError:
        return default


def run_sync(coro):
    """Run a coroutine from regular code (no running event loop required).

    >>> async def hello():
    ...     return 'hi'
    >>> run_sync(hello())
    'hi'
    """
    return asyncio.run(coro)
