-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
144 lines (115 loc) · 2.18 KB
/
decoder.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package gobencode
import (
"bufio"
"bytes"
"fmt"
"os"
"strconv"
)
type Decoder struct {
b *bufio.Reader
Cursor int64
}
func DecodeFile(filepath string) BencodeItem {
file, err := os.Open(filepath)
if err != nil {
panic(err)
}
defer file.Close()
reader := bufio.NewReader(file)
d := NewDecoder(reader)
return d.decode()
}
func DecodeString(bencode string) BencodeItem {
buff := new(bytes.Buffer)
buff.WriteString(bencode)
reader := bufio.NewReader(buff)
d := NewDecoder(reader)
return d.decode()
}
func (d *Decoder) ReadByte() byte {
b, err := d.b.ReadByte()
if err != nil {
panic(err)
}
d.Cursor += 1
return b
}
func (d *Decoder) ReadBytes(delim byte) []byte {
b, err := d.b.ReadBytes(delim)
if err != nil {
panic(err)
}
d.Cursor += int64(len(b))
return b
}
func (d *Decoder) Read(p []byte) {
n, err := d.b.Read(p)
if err != nil {
panic(err)
}
d.Cursor += int64(n)
}
func NewDecoder(r *bufio.Reader) Decoder {
return Decoder{
r,
0,
}
}
func (d *Decoder) decode() BencodeItem {
ch := d.ReadByte()
bi := BencodeItem{}
if '0' <= ch && ch <= '9' {
lengthBytes := d.ReadBytes(':')
lengthBytes = append([]byte{ch}, lengthBytes[:len(lengthBytes)-1]...)
length, err := strconv.Atoi(string(lengthBytes))
if err != nil {
panic(err)
}
bytes := make([]byte, length)
d.Read(bytes)
bi.Type = Bytes
bi.Value = bytes
return bi
}
switch ch {
case 'i':
rawInt := d.ReadBytes('e')
intVal, err := strconv.Atoi(string(rawInt[:len(rawInt)-1]))
if err != nil {
panic(err)
}
bi.Type = Integer
bi.Value = intVal
case 'l':
list := []BencodeItem{}
for {
item := d.decode()
if item.Type == EOL {
break
}
list = append(list, item)
}
bi.Type = List
bi.Value = list
case 'd':
dict := map[string]BencodeItem{}
for {
key := d.decode()
if key.Type == EOL {
break
} else if key.Type != Bytes {
panic(fmt.Sprintf("dict key type is not value, it is %d", key.Type))
}
value := d.decode()
dict[string(key.Value.([]byte))] = value
}
bi.Type = Dict
bi.Value = dict
case 'e':
bi.Type = EOL
default:
panic(fmt.Sprintf("Wrong format symbol (%c) at %d", ch, d.Cursor))
}
return bi
}