Skip to content

Commit

Permalink
Reduce allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
negbie committed Jun 6, 2021
1 parent d4a2dac commit c3e5419
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
7 changes: 3 additions & 4 deletions gobaresip.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,6 @@ func (b *Baresip) read() {
}
}
} else if bytes.Contains(msg, []byte("\"response\":true")) {
if bytes.Contains(msg, []byte("keep_active_ping")) {
continue
}

var r ResponseMsg
r.RawJSON = msg
Expand Down Expand Up @@ -309,14 +306,16 @@ func (b *Baresip) GetResponseChan() <-chan ResponseMsg {
return b.responseChan
}

var ping = []byte(`16:{"token":"ping"},`)

func (b *Baresip) keepActive() {
for {
time.Sleep(1 * time.Second)
if atomic.LoadUint32(&b.ctrlConnAlive) == 0 {
break
}
b.ctrlConn.SetWriteDeadline(time.Now().Add(2 * time.Second))
b.ctrlConn.Write([]byte(`46:{"command":"about","token":"keep_active_ping"},`))
b.ctrlConn.Write(ping)
}
}

Expand Down
19 changes: 15 additions & 4 deletions netstring.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ package gobaresip
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
"strings"
)

const (
Expand All @@ -49,10 +49,21 @@ func (r *reader) readNetstring() ([]byte, error) {
if err != nil {
return nil, err
}
l, err := strconv.Atoi(strings.TrimSuffix(string(length), string(lengthDelim)))
if err != nil {
return nil, err

var l int
for _, ch := range length {
if ch != lengthDelim && ch != dataDelim {
ch -= '0'
if ch > 9 {
return nil, fmt.Errorf("wrong netstring length character")
}
l = l*10 + int(ch)
}
}
if l <= 0 {
return nil, fmt.Errorf("wrong netstring length")
}

ret := make([]byte, l)
_, err = io.ReadFull(r.r, ret)
if err != nil {
Expand Down

0 comments on commit c3e5419

Please sign in to comment.