aboutsummaryrefslogtreecommitdiff
path: root/cmd/mybittorrent/decoder.go
blob: 10066e1cda81e6898fcb016bde320543f3fe0e9b (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
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
package main

import (
	"fmt"
	"strconv"
	"strings"
	"unicode"
)

type Decoder struct {
	raw          string
	decoderFuncs []DecoderFunc
}

type DecoderFunc func(string) (any, int, bool)

func NewDecoder(raw string) *Decoder {
	d := &Decoder{raw: raw}
	return d.WithDecoderFunc(d.decodeSlice).WithDecoderFunc(d.decodeString).WithDecoderFunc(d.decodeInteger)
}

func (d *Decoder) WithDecoderFunc(f DecoderFunc) *Decoder {
	d.decoderFuncs = append(d.decoderFuncs, f)
	return d
}

func (d *Decoder) Decode() (any, error) {
	for _, f := range d.decoderFuncs {
		if r, _, ok := f(d.raw); ok {
			return r, nil
		}
	}

	return nil, fmt.Errorf("failed to decode value: %s", d.raw)
}

func (d *Decoder) decodeString(chunk string) (any, int, bool) {
	if !unicode.IsDigit(rune(chunk[0])) {
		return "", 0, false
	}

	var firstColonIndex int

	for i := 0; i < len(chunk); i++ {
		if chunk[i] == ':' {
			firstColonIndex = i
			break
		}
	}

	lengthStr := chunk[:firstColonIndex]

	length, err := strconv.Atoi(lengthStr)
	if err != nil {
		return "", 0, false
	}

	val := chunk[firstColonIndex+1 : firstColonIndex+1+length]

	return val, length + 1 + len(lengthStr), true
}

func (d *Decoder) decodeInteger(chunk string) (any, int, bool) {
	if rune(chunk[0]) != 'i' {
		return 0, 0, false
	}

	num, err := strconv.Atoi(chunk[1:strings.IndexByte(chunk, 'e')])
	if err != nil {
		return 0, 0, false
	}

	return num, len(strconv.Itoa(num)) + 2, true
}

func (d *Decoder) decodeSlice(chunk string) (any, int, bool) {
	if rune(chunk[0]) != 'l' {
		return nil, 0, false
	}

	if rune(chunk[1]) == 'e' {
		return []any{}, 2, true
	}

	slice := make([]any, 0, 1024)
	offset := 1

	for rune(chunk[offset]) != 'e' {
		for _, f := range d.decoderFuncs {
			if v, l, ok := f(chunk[offset:]); ok {
				slice = append(slice, v)
				offset += l
			}
		}
	}

	return slice, offset + 1, true
}