1
0

A struct to hold a number of current and peak listeners was added.

This commit is contained in:
Alexander Andreev 2023-09-30 23:57:31 +04:00
parent c3b3604a6f
commit 328dbc644e
Signed by: Arav
GPG Key ID: D22A817D95815393

View File

@ -0,0 +1,50 @@
package radio
import (
"errors"
"fmt"
"math"
)
// Listeners stores the current and peak numbers of listeners.
type Listeners struct {
current, peak int
}
// NewListeners returns a new Listeners struct instance.
func NewListeners() *Listeners {
return &Listeners{}
}
// Current returns a number of current listeners.
func (l *Listeners) Current() int {
return l.current
}
// Current returns a number of peak listeners.
func (l *Listeners) Peak() int {
return l.peak
}
// Inc increments by 1 a current number of listeners and updates a peak number.
func (l *Listeners) Inc() int {
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.
func (l *Listeners) Dec() (int, error) {
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
}