1
0

In ListenerCounter struct also keep track of overall number of listeners for a song and its max simultaneous number of listeners. These parameters are being reset with a Reset() method that returns its values.

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

View File

@ -3,15 +3,15 @@ package radio
import (
"encoding/json"
"errors"
"fmt"
"math"
"sync"
)
// ListenerCounter stores the current and peak numbers of listeners.
// ListenerCounter stores the current, overall and peak numbers of listeners.
type ListenerCounter struct {
mutex sync.RWMutex
current, peak int64
mutex sync.RWMutex
current, peak int64
overall, cur_peak int64
}
// NewListenerCounter returns a new ListenerCounter struct instance.
@ -39,12 +39,19 @@ func (l *ListenerCounter) Inc() int64 {
defer l.mutex.Unlock()
if l.current == math.MaxInt64 {
// We panic here because if this will ever happen, then something's going certainly wrong.
panic(fmt.Sprint("a current number of listeners exceeded MaxInt64 which is", math.MaxInt))
panic("a current number of listeners exceeded MaxInt64")
}
l.current++
if l.current > l.peak {
l.peak = l.current
}
if l.current > l.cur_peak {
l.cur_peak = l.current
}
if l.overall == math.MaxInt64 {
panic("an overall number of listeners exceeded MaxInt64")
}
l.overall++
return l.current
}
@ -60,13 +67,27 @@ func (l *ListenerCounter) Dec() (int64, error) {
return l.current, nil
}
// Reset current peak and overall listeners for a song that is playing.
// And return its values.
func (l *ListenerCounter) Reset() (overall, peak int64) {
l.mutex.Lock()
defer l.mutex.Unlock()
peak = l.cur_peak
l.cur_peak = l.current
overall = l.overall
l.overall = l.current
return
}
func (l *ListenerCounter) MarshalJSON() ([]byte, error) {
l.mutex.RLock()
defer l.mutex.RUnlock()
return json.Marshal(&struct {
Current int64 `json:"current"`
Peak int64 `json:"peak"`
Overall int64 `json:"overall"`
}{
Current: l.current,
Peak: l.peak})
Peak: l.peak,
Overall: l.overall})
}