blob: 0e82586e4c49a50764d315f7a906fc27b99215f1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
module chunked
import strings
// See: https://en.wikipedia.org/wiki/Chunked_transfer_encoding
// /////////////////////////////////////////////////////////////
// The chunk size is transferred as a hexadecimal number
// followed by \r\n as a line separator,
// followed by a chunk of data of the given size.
// The end is marked with a chunk with size 0.
struct ChunkScanner {
mut:
pos int
text string
}
fn (mut s ChunkScanner) read_chunk_size() int {
mut n := 0
for {
if s.pos >= s.text.len {
break
}
c := s.text[s.pos]
if !c.is_hex_digit() {
break
}
n = n << 4
n += int(unhex(c))
s.pos++
}
return n
}
fn unhex(c byte) byte {
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
}
return 0
}
fn (mut s ChunkScanner) skip_crlf() {
s.pos += 2
}
fn (mut s ChunkScanner) read_chunk(chunksize int) string {
startpos := s.pos
s.pos += chunksize
return s.text[startpos..s.pos]
}
pub fn decode(text string) string {
mut sb := strings.new_builder(100)
mut cscanner := ChunkScanner{
pos: 0
text: text
}
for {
csize := cscanner.read_chunk_size()
if 0 == csize {
break
}
cscanner.skip_crlf()
sb.write_string(cscanner.read_chunk(csize))
cscanner.skip_crlf()
}
cscanner.skip_crlf()
return sb.str()
}
|