Skip to content

Commit

Permalink
Simplify compressedWriter.Write.
Browse files Browse the repository at this point in the history
  • Loading branch information
Joe Mann committed Oct 12, 2023
1 parent 7610823 commit eb449fa
Showing 1 changed file with 15 additions and 43 deletions.
58 changes: 15 additions & 43 deletions compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ import (
"io"
)

const (
minCompressLength = 50
)

type compressedReader struct {
buf packetReader
bytesBuf []byte
Expand Down Expand Up @@ -124,20 +120,27 @@ func (r *compressedReader) uncompressPacket() error {
return nil
}

const maxPayloadLen = maxPacketSize - 4

var blankHeader = make([]byte, 7)

func (w *compressedWriter) Write(data []byte) (int, error) {
// when asked to write an empty packet, do nothing
if len(data) == 0 {
return 0, nil
}

totalBytes := len(data)
length := len(data) - 4
maxPayloadLength := maxPacketSize - 4
blankHeader := make([]byte, 7)

for length >= maxPayloadLength {
payload := data[:maxPayloadLength]
uncompressedLen := len(payload)
dataLen := len(data)
for dataLen != 0 {
payloadLen := dataLen
if payloadLen > maxPayloadLen {
payloadLen = maxPayloadLen
}
payload := data[:payloadLen]

uncompressedLen := payloadLen

buf := bytes.NewBuffer(blankHeader)

Expand All @@ -159,42 +162,11 @@ func (w *compressedWriter) Write(data []byte) (int, error) {
return 0, err
}

length -= maxPayloadLength
data = data[maxPayloadLength:]
}

payloadLen := len(data)

// do not attempt compression if packet is too small
if payloadLen < minCompressLength {
if err := w.writeToNetwork(append(blankHeader, data...), 0); err != nil {
return 0, err
}
return totalBytes, nil
}

bytesBuf := &bytes.Buffer{}
bytesBuf.Write(blankHeader)
w.zw.Reset(bytesBuf)
if _, err := w.zw.Write(data); err != nil {
return 0, err
}
w.zw.Close()

compressedPayload := bytesBuf.Bytes()

if len(compressedPayload) > len(data) {
compressedPayload = append(blankHeader, data...)
payloadLen = 0
}

// add header and send over the wire
if err := w.writeToNetwork(compressedPayload, payloadLen); err != nil {
return 0, err
dataLen -= payloadLen
data = data[payloadLen:]
}

return totalBytes, nil

}

func (w *compressedWriter) writeToNetwork(data []byte, uncompressedLen int) error {
Expand Down

0 comments on commit eb449fa

Please sign in to comment.