Skip to content

Instantly share code, notes, and snippets.

@ctkirkman
Created June 5, 2019 00:54
Show Gist options
  • Save ctkirkman/92738df99fb3c0a1280c585ad23fccb2 to your computer and use it in GitHub Desktop.
Save ctkirkman/92738df99fb3c0a1280c585ad23fccb2 to your computer and use it in GitHub Desktop.
def parse_chunked(data):
result = b""
state = "header"
while data:
if state == "header":
chunk, data = data.split(b"\r\n", 1)
length = int(chunk.strip(), 16)
if length == 0:
state = "finished"
else:
state = "body"
elif state == "body":
chunk, data = data[:length], data[length:]
result += chunk
state = "footer"
elif state == "footer":
chunk, data = data.split(b"\r\n", 1)
state = "header"
elif state == "finished":
if data is None or data.strip() == b"":
break
else:
raise RuntimeError("Data After Last Chunk")
break
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment