2023-09-30 23:57:31 +04:00
|
|
|
package radio
|
|
|
|
|
|
|
|
import (
|
2023-10-01 22:03:26 +04:00
|
|
|
"encoding/json"
|
2023-09-30 23:57:31 +04:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"math"
|
2023-10-01 04:18:43 +04:00
|
|
|
"sync"
|
2023-09-30 23:57:31 +04:00
|
|
|
)
|
|
|
|
|
2023-10-01 20:32:07 +04:00
|
|
|
// ListenerCounter stores the current and peak numbers of listeners.
|
|
|
|
type ListenerCounter struct {
|
2023-10-01 04:18:43 +04:00
|
|
|
mut sync.Mutex
|
2023-09-30 23:57:31 +04:00
|
|
|
current, peak int
|
|
|
|
}
|
|
|
|
|
2023-10-01 20:32:07 +04:00
|
|
|
// NewListenerCounter returns a new ListenerCounter struct instance.
|
|
|
|
func NewListenerCounter() *ListenerCounter {
|
|
|
|
return &ListenerCounter{}
|
2023-09-30 23:57:31 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Current returns a number of current listeners.
|
2023-10-01 20:32:07 +04:00
|
|
|
func (l *ListenerCounter) Current() int {
|
2023-10-01 04:18:43 +04:00
|
|
|
l.mut.Lock()
|
|
|
|
defer l.mut.Unlock()
|
2023-09-30 23:57:31 +04:00
|
|
|
return l.current
|
|
|
|
}
|
|
|
|
|
|
|
|
// Current returns a number of peak listeners.
|
2023-10-01 20:32:07 +04:00
|
|
|
func (l *ListenerCounter) Peak() int {
|
2023-10-01 04:18:43 +04:00
|
|
|
l.mut.Lock()
|
|
|
|
defer l.mut.Unlock()
|
2023-09-30 23:57:31 +04:00
|
|
|
return l.peak
|
|
|
|
}
|
|
|
|
|
|
|
|
// Inc increments by 1 a current number of listeners and updates a peak number.
|
2023-10-01 20:32:07 +04:00
|
|
|
func (l *ListenerCounter) Inc() int {
|
2023-10-01 04:18:43 +04:00
|
|
|
l.mut.Lock()
|
|
|
|
defer l.mut.Unlock()
|
2023-09-30 23:57:31 +04:00
|
|
|
if l.current == math.MaxInt {
|
|
|
|
// We panic here because if this will ever happen, then something's going certainly wrong.
|
|
|
|
panic(fmt.Sprint("a current number of listeners exceeded MaxInt which is", math.MaxInt))
|
|
|
|
}
|
|
|
|
l.current++
|
|
|
|
if l.current > l.peak {
|
|
|
|
l.peak = l.current
|
|
|
|
}
|
|
|
|
return l.current
|
|
|
|
}
|
|
|
|
|
|
|
|
// Dec decrements by 1 a current number of listeners. An error will occur if
|
|
|
|
// a resulting number is less than 0.
|
2023-10-01 20:32:07 +04:00
|
|
|
func (l *ListenerCounter) Dec() (int, error) {
|
2023-10-01 04:18:43 +04:00
|
|
|
l.mut.Lock()
|
|
|
|
defer l.mut.Unlock()
|
2023-09-30 23:57:31 +04:00
|
|
|
if l.current == 0 {
|
|
|
|
return l.current, errors.New("an attempt to decrement a number of current listeners down to less than 0")
|
|
|
|
}
|
|
|
|
l.current--
|
|
|
|
return l.current, nil
|
|
|
|
}
|
2023-10-01 22:03:26 +04:00
|
|
|
|
|
|
|
func (l *ListenerCounter) MarshalJSON() ([]byte, error) {
|
|
|
|
l.mut.Lock()
|
|
|
|
defer l.mut.Unlock()
|
|
|
|
return json.Marshal(&struct {
|
|
|
|
Current int `json:"current"`
|
|
|
|
Peak int `json:"peak"`
|
|
|
|
}{
|
|
|
|
Current: l.current,
|
|
|
|
Peak: l.peak})
|
|
|
|
}
|