import struct


def write_uvarint(w, val):
  """Writes a varint value to the supplied file-like object.

  Args:
    w (object): A file-like object to write to. Must implement write.
    val (number): The value to write. Must be >= 0.

  Returns (int): The number of bytes that were written.

  Raises:
    ValueError if 'val' is < 0.
  """
  if val < 0:
    raise ValueError('Cannot encode negative value, %d' % (val,))

  count = 0
  while val > 0 or count == 0:
    byte = (val & 0b01111111)
    val >>= 7
    if val > 0:
      byte |= 0b10000000

    w.write(struct.pack('B', byte))
    count += 1
  return count