def read_string()

in zktraffic/base/util.py [0:0]


def read_string(data, offset, maxlen=1024, default="unreadable"):
  """
  Note: even though strings are utf-8 decoded, we need to str()
        them since they can't be used by intern() otherwise.
  """
  data = to_bytes(data)
  old = offset
  length, offset = read_number(data, offset)

  if length > maxlen:
    raise StringTooLong("Length %d is greater than the maximum length (%d)" % (length, maxlen))

  if length < 0:
    return ("", old)

  try:
    s = data[offset:offset + length].decode("utf-8")
  except UnicodeDecodeError:
    s = default

  # back to str, so it can be consumed by intern()
  try:
    s = str(s)
  except UnicodeEncodeError:
    s = default

  return (s, offset + length)