blob: 8f17055103a477fb8178567d045ac9ab380cd6e7 (
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
|
package main
import (
"container/heap"
)
type Playlist []*Song
func (pl Playlist) Len() int { return len(pl) }
func (pl Playlist) Less(i, j int) bool {
return pl[i].Weight > pl[j].Weight
}
func (pl Playlist) Swap(i, j int) {
pl[i], pl[j] = pl[j], pl[i]
pl[i].index = i
pl[j].index = j
}
func (pl *Playlist) Push(x any) {
n := len(*pl)
song := x.(*Song)
song.index = n
*pl = append(*pl, song)
}
func (pl *Playlist) Pop() any {
old := *pl
n := len(old)
s := old[n-1]
old[n-1] = nil // avoid memory leak
s.index = -1 // for safety
*pl = old[0 : n-1]
return s
}
func (pl *Playlist) PopSong() *Song {
if len(*pl) == 0 {
return nil
}
return heap.Pop(pl).(*Song)
}
func (pl *Playlist) Add(s *Song) {
heap.Push(pl, s)
}
func (pl *Playlist) Adjust(s *Song) {
heap.Fix(pl, s.index)
}
|