import binascii


def get_partition(num_partitions, queue, project=None):
    """Get the partition number for a given queue and project.

    Hashes the queue to a partition number. The hash is stable,
    meaning given the same queue name and project ID, the same
    partition number will always be returned. Note also that
    queues will be uniformly distributed across partitions.

    The number of partitions is taken from the "partitions"
    property in the config file, under the [drivers:storage:mongodb]
    section.
    """

    name = project + queue if project is not None else queue

    # NOTE(kgriffs): For small numbers of partitions, crc32 will
    # provide a uniform distribution. This was verified experimentally
    # with up to 100 partitions.
    return binascii.crc32(name.encode('utf-8')) % num_partitions