Skip to content

Commit

Permalink
Make Clamp Go 1.20 compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkKremer committed Sep 21, 2024
1 parent 9fafb73 commit caac121
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 10 deletions.
4 changes: 2 additions & 2 deletions buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ func (f Format) DecodeUnsigned(p []byte) (sample [2]float64, n int) {
func (f Format) encode(signed bool, p []byte, sample [2]float64) (n int) {
switch {
case f.NumChannels == 1:
x := util.Clamp((sample[0]+sample[1])/2, -1, 1)
x := util.ClampFloat64((sample[0]+sample[1])/2, -1, 1)
p = p[encodeFloat(signed, f.Precision, p, x):]
case f.NumChannels >= 2:
for c := range sample {
x := util.Clamp(sample[c], -1, 1)
x := util.ClampFloat64(sample[c], -1, 1)
p = p[encodeFloat(signed, f.Precision, p, x):]
}
for c := len(sample); c < f.NumChannels; c++ {
Expand Down
12 changes: 8 additions & 4 deletions internal/util/math.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package util

import "cmp"

func Clamp[T cmp.Ordered](x, minV, maxV T) T {
return max(min(x, maxV), minV)
func ClampFloat64(x, minV, maxV float64) float64 {
if x <= minV {
return minV
}
if x >= maxV {
return maxV
}
return x
}
6 changes: 3 additions & 3 deletions internal/util/math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

func TestClamp(t *testing.T) {
assert.Equal(t, 0, Clamp(-5, 0, 1))
assert.Equal(t, 1, Clamp(5, 0, 1))
assert.Equal(t, 0.5, Clamp(0.5, 0, 1))
assert.Equal(t, 0.0, ClampFloat64(-5, 0, 1))
assert.Equal(t, 1.0, ClampFloat64(5, 0, 1))
assert.Equal(t, 0.5, ClampFloat64(0.5, 0, 1))
}
2 changes: 1 addition & 1 deletion speaker/speaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ func (s *sampleReader) Read(buf []byte) (n int, err error) {
for i := range s.buf[:ns] {
for c := range s.buf[i] {
val := s.buf[i][c]
val = util.Clamp(val, -1, 1)
val = util.ClampFloat64(val, -1, 1)
valInt16 := int16(val * (1<<15 - 1))
low := byte(valInt16)
high := byte(valInt16 >> 8)
Expand Down

0 comments on commit caac121

Please sign in to comment.