v/vlib/net/http/chunked/dechunk.v

75 lines
1.3 KiB
V
Raw Normal View History

2019-08-07 03:57:47 +02:00
module chunked
import strings
// See: https://en.wikipedia.org/wiki/Chunked_transfer_encoding
2019-12-21 23:41:42 +01:00
// /////////////////////////////////////////////////////////////
// The chunk size is transferred as a hexadecimal number
// followed by \r\n as a line separator,
2019-08-07 03:57:47 +02:00
// followed by a chunk of data of the given size.
// The end is marked with a chunk with size 0.
struct ChunkScanner {
mut:
2019-12-21 23:41:42 +01:00
pos int
2019-08-07 03:57:47 +02:00
text string
}
fn (s mut ChunkScanner) read_chunk_size() int {
mut n := 0
for {
2019-12-21 23:41:42 +01:00
if s.pos >= s.text.len {
break
}
2019-08-07 03:57:47 +02:00
c := s.text[s.pos]
2019-12-21 23:41:42 +01:00
if !c.is_hex_digit() {
break
}
n = n<<4
2019-08-07 03:57:47 +02:00
n += int(unhex(c))
s.pos++
}
return n
}
fn unhex(c byte) byte {
2019-12-21 23:41:42 +01:00
if `0` <= c && c <= `9` {
return c - `0`
}
else if `a` <= c && c <= `f` {
return c - `a` + 10
}
else if `A` <= c && c <= `F` {
return c - `A` + 10
}
2019-08-07 03:57:47 +02:00
return 0
}
fn (s mut ChunkScanner) skip_crlf() {
s.pos += 2
}
fn (s mut ChunkScanner) read_chunk(chunksize int) string {
startpos := s.pos
s.pos += chunksize
return s.text[startpos..s.pos]
2019-08-07 03:57:47 +02:00
}
pub fn decode(text string) string {
mut sb := strings.new_builder(100)
2019-12-21 23:41:42 +01:00
mut cscanner := ChunkScanner{
2019-08-07 03:57:47 +02:00
pos: 0
text: text
}
for {
csize := cscanner.read_chunk_size()
2019-12-21 23:41:42 +01:00
if 0 == csize {
break
}
2019-08-07 03:57:47 +02:00
cscanner.skip_crlf()
2019-12-21 23:41:42 +01:00
sb.write(cscanner.read_chunk(csize))
2019-08-07 03:57:47 +02:00
cscanner.skip_crlf()
}
cscanner.skip_crlf()
return sb.str()
}
2019-12-21 23:41:42 +01:00