def _random_int(rng, min_val, max_val, available):
    """
    Generate a random number between min_val and max_val given the available space,
    taking care of leaving enough space for the next iteration.

    Parameters
    ----------
    rng : numpy.random.Generator
    min_val, max_val : int
        Range of the value.
    available : int
        Value used to cumpute how much "space" is left, if there is not enough space
        this value is returned.

    Returns
    -------
    int
        Random integer.
    """

    if available - min_val >= max_val:
        return rng.integers(min_val, max_val + 1)

    if available - min_val >= min_val:
        return rng.integers(min_val, available - min_val + 1)

    return available