1
0

Do not alter Song struct listeners with its methods, use a ListenerCounter to populate Listeners and MaxListeners. Eliminates the need for a mutex and SetFrom(), UpdateMaxListeners() and IncListeners() methods.

This commit is contained in:
Alexander Andreev 2024-05-11 04:18:28 +04:00
parent 3b22643733
commit 1682362779
Signed by: Arav
GPG Key ID: 25969B23DCB5CA34

View File

@ -2,50 +2,20 @@ package radio
import (
"encoding/json"
"sync"
"time"
)
type Song struct {
mutex sync.Mutex
Artist string
Title string
StartAt time.Time
Duration time.Duration
Listeners int64
MaxListeners int64
StartAt time.Time
}
func (s *Song) SetFrom(os *Song) {
s.mutex.Lock()
s.Artist = os.Artist
s.Title = os.Title
s.Duration = os.Duration
s.Listeners = os.Listeners
s.MaxListeners = os.MaxListeners
s.StartAt = os.StartAt
s.mutex.Unlock()
}
func (s *Song) UpdateMaxListeners(listeners int64) {
s.mutex.Lock()
if listeners > s.MaxListeners {
s.MaxListeners = listeners
}
s.mutex.Unlock()
}
// IncListeners increments by one an overall amount of listeners of this song.
func (s *Song) IncListeners() {
s.mutex.Lock()
s.Listeners++
s.mutex.Unlock()
}
// DurationString returns song's duration as a string formatted as [H:]M:SS.
func (s *Song) DurationString() string {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.Duration.Hours() >= 1 {
return time.UnixMilli(s.Duration.Milliseconds()).Format("3:4:05")
}
@ -53,8 +23,6 @@ func (s *Song) DurationString() string {
}
func (s *Song) MarshalJSON() ([]byte, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
return json.Marshal(&struct {
Artist string `json:"artist"`
Title string `json:"title"`