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

73 lines
1.3 KiB
V
Raw Permalink 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.
2021-06-14 09:08:41 +02:00
2019-08-07 03:57:47 +02:00
struct ChunkScanner {
mut:
2019-12-21 23:41:42 +01:00
pos int
2019-08-07 03:57:47 +02:00
text string
}
fn (mut s ChunkScanner) read_chunk_size() u32 {
mut n := u32(0)
2019-08-07 03:57:47 +02:00
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
}
2021-06-14 09:08:41 +02:00
n = n << 4
n += u32(unhex(c))
2019-08-07 03:57:47 +02:00
s.pos++
}
return n
}
2022-04-15 17:25:45 +02:00
fn unhex(c u8) u8 {
2019-12-21 23:41:42 +01:00
if `0` <= c && c <= `9` {
return c - `0`
2021-06-14 09:08:41 +02:00
} else if `a` <= c && c <= `f` {
2019-12-21 23:41:42 +01:00
return c - `a` + 10
2021-06-14 09:08:41 +02:00
} else if `A` <= c && c <= `F` {
2019-12-21 23:41:42 +01:00
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
}
fn (mut s ChunkScanner) read_chunk(chunksize u32) string {
2019-08-07 03:57:47 +02:00
startpos := s.pos
s.pos += int(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()
sb.write_string(cscanner.read_chunk(csize))
2019-08-07 03:57:47 +02:00
cscanner.skip_crlf()
}
cscanner.skip_crlf()
return sb.str()
2019-08-07 03:57:47 +02:00
}