-
Notifications
You must be signed in to change notification settings - Fork 10
/
torrent.go
104 lines (89 loc) · 2.46 KB
/
torrent.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
package magopie
import (
"encoding/json"
"fmt"
)
// A Torrent is an individual result from a search operation representing a
// single torrent file.
type Torrent struct {
ID string
Title string
MagnetURI string
SiteID string
Seeders int
Leechers int
Size int
}
// TorrentCollection is a collection of torrents because gomobile can't
// handle slices
type TorrentCollection struct {
list []Torrent
}
// Length returns how many torrents are in the collection
func (tc *TorrentCollection) Length() int {
return len(tc.list)
}
// Get returns the torrent at idx or a nil torrent
func (tc *TorrentCollection) Get(idx int) *Torrent {
if idx <= tc.Length() {
return &tc.list[idx]
}
return nil
}
// Clear empties the list of torrents
func (tc *TorrentCollection) Clear() {
tc.list = tc.list[:0]
}
// Index finds the index of a torrent or -1 if not found
func (tc *TorrentCollection) Index(t *Torrent) int {
for i, tst := range tc.list {
if tst == *t {
return i
}
}
return -1
}
// Insert inserts a torrent into the collection at i
func (tc *TorrentCollection) Insert(i int, t *Torrent) {
if i < 0 || i > tc.Length() {
fmt.Printf("Magopie-go:: Attempted to insert a torrent at an invalid index")
return
}
tc.list = append(tc.list, Torrent{})
copy(tc.list[i+1:], tc.list[i:])
tc.list[i] = *t
}
// Remove a torrent from the collection at i
func (tc *TorrentCollection) Remove(i int) {
if i < 0 || i >= tc.Length() {
fmt.Printf("Magopie-go:: Attempted to remove a torrent from an invalid index")
return
}
copy(tc.list[i:], tc.list[i+1:])
tc.list[len(tc.list)-1] = Torrent{}
tc.list = tc.list[:len(tc.list)-1]
}
// Push adds an element to the end of the collection
func (tc *TorrentCollection) Push(t *Torrent) {
tc.Insert(tc.Length(), t)
}
// Pop removes the last element from the collection
func (tc *TorrentCollection) Pop(t *Torrent) {
tc.Remove(tc.Length() - 1)
}
// Unshift adds an element to the front of the collection
func (tc *TorrentCollection) Unshift(t *Torrent) {
tc.Insert(0, t)
}
// Shift removes an element from the front of the collection
func (tc *TorrentCollection) Shift(t *Torrent) {
tc.Remove(0)
}
// MarshalJSON returns JSON from the collection
func (tc *TorrentCollection) MarshalJSON() ([]byte, error) {
return json.Marshal(tc.list)
}
// UnmarshalJSON replaces the collection with the results from a JSON []byte
func (tc *TorrentCollection) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &tc.list)
}