def _calculate_varint_size()

in python/aws_kinesis_agg/aggregator.py [0:0]


def _calculate_varint_size(value):
    """For an integral value represented by a varint, calculate how many bytes 
    are necessary to represent the value in a protobuf message.
    (see https://developers.google.com/protocol-buffers/docs/encoding# varints)
     
    Args:
        value (int) - The value whose varint size will be calculated
    Returns:
        The number of bytes necessary to represent the input value as a varint. (int)"""
    
    if value < 0:
        raise ValueError("Size values should not be negative.")
    
    num_bits_needed = 0
    
    if value == 0:
        num_bits_needed = 1
    else:
        # shift the value right one bit at a time until
        # there are no more '1' bits left...this counts
        # how many bits we need to represent the number
        while value > 0:
            num_bits_needed += 1
            value = value >> 1
        
    # varints only use 7 bits of the byte for the actual value
    num_varint_bytes = num_bits_needed // 7
    if num_bits_needed % 7 > 0:
        num_varint_bytes += 1
        
    return num_varint_bytes