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
|
|
|
|
}
|
|
|
|
|
2020-05-17 13:51:18 +02:00
|
|
|
fn (mut s ChunkScanner) read_chunk_size() int {
|
2019-08-07 03:57:47 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-05-17 13:51:18 +02:00
|
|
|
fn (mut s ChunkScanner) skip_crlf() {
|
2019-08-07 03:57:47 +02:00
|
|
|
s.pos += 2
|
|
|
|
}
|
|
|
|
|
2020-05-17 13:51:18 +02:00
|
|
|
fn (mut s ChunkScanner) read_chunk(chunksize int) string {
|
2019-08-07 03:57:47 +02:00
|
|
|
startpos := s.pos
|
|
|
|
s.pos += chunksize
|
2019-10-27 08:03:15 +01:00
|
|
|
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()
|
|
|
|
}
|