1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/net/http/chunked/dechunk.v

73 lines
1.3 KiB
V
Raw Normal View History

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