blob: 87095ae2b2a6e09c25ea52ce43cb416203e40ab1 (
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
|
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"unicode"
// bencode "github.com/jackpal/bencode-go" // Available if you need it!
)
func decodeBencode(bencodedString string) (interface{}, error) {
if unicode.IsDigit(rune(bencodedString[0])) {
var firstColonIndex int
for i := 0; i < len(bencodedString); i++ {
if bencodedString[i] == ':' {
firstColonIndex = i
break
}
}
lengthStr := bencodedString[:firstColonIndex]
length, err := strconv.Atoi(lengthStr)
if err != nil {
return "", err
}
return bencodedString[firstColonIndex+1 : firstColonIndex+1+length], nil
} else if rune(bencodedString[0]) == 'i' {
return strconv.Atoi(bencodedString[1:strings.IndexByte(bencodedString, 'e')])
} else {
return "", fmt.Errorf("only strings are supported at the moment")
}
}
func main() {
command := os.Args[1]
if command == "decode" {
bencodedValue := os.Args[2]
decoded, err := decodeBencode(bencodedValue)
if err != nil {
fmt.Println(err)
return
}
jsonOutput, _ := json.Marshal(decoded)
fmt.Println(string(jsonOutput))
} else {
fmt.Println("Unknown command: " + command)
os.Exit(1)
}
}
|