1
0

Embedded a sync.Mutex to a ListenerCounter.

This commit is contained in:
Alexander Andreev 2023-10-05 18:18:48 +04:00
parent f1eaba016f
commit c7f6b3072d
Signed by: Arav
GPG Key ID: D22A817D95815393

View File

@ -10,7 +10,7 @@ import (
// ListenerCounter stores the current and peak numbers of listeners.
type ListenerCounter struct {
mut sync.Mutex
sync.Mutex
current, peak int
}
@ -21,22 +21,22 @@ func NewListenerCounter() *ListenerCounter {
// Current returns a number of current listeners.
func (l *ListenerCounter) Current() int {
l.mut.Lock()
defer l.mut.Unlock()
l.Lock()
defer l.Unlock()
return l.current
}
// Current returns a number of peak listeners.
func (l *ListenerCounter) Peak() int {
l.mut.Lock()
defer l.mut.Unlock()
l.Lock()
defer l.Unlock()
return l.peak
}
// Inc increments by 1 a current number of listeners and updates a peak number.
func (l *ListenerCounter) Inc() int {
l.mut.Lock()
defer l.mut.Unlock()
l.Lock()
defer l.Unlock()
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))
@ -51,8 +51,8 @@ func (l *ListenerCounter) Inc() int {
// Dec decrements by 1 a current number of listeners. An error will occur if
// a resulting number is less than 0.
func (l *ListenerCounter) Dec() (int, error) {
l.mut.Lock()
defer l.mut.Unlock()
l.Lock()
defer l.Unlock()
if l.current == 0 {
return l.current, errors.New("an attempt to decrement a number of current listeners down to less than 0")
}
@ -61,8 +61,8 @@ func (l *ListenerCounter) Dec() (int, error) {
}
func (l *ListenerCounter) MarshalJSON() ([]byte, error) {
l.mut.Lock()
defer l.mut.Unlock()
l.Lock()
defer l.Unlock()
return json.Marshal(&struct {
Current int `json:"current"`
Peak int `json:"peak"`