Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace manual slice management with bytes.Buffer in Writer #619

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions internal/stream/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package stream

import (
"bytes"
"crypto/cipher"
"errors"
"fmt"
Expand Down Expand Up @@ -149,7 +150,7 @@ func nonceIsZero(nonce *[chacha20poly1305.NonceSize]byte) bool {
type Writer struct {
a cipher.AEAD
dst io.Writer
unwritten []byte // backed by buf
unwritten bytes.Buffer // backed by buf
buf [encChunkSize]byte
nonce [chacha20poly1305.NonceSize]byte
err error
Expand All @@ -164,33 +165,31 @@ func NewWriter(key []byte, dst io.Writer) (*Writer, error) {
a: aead,
dst: dst,
}
w.unwritten = w.buf[:0]
w.unwritten.Grow(ChunkSize)
return w, nil
}

func (w *Writer) Write(p []byte) (n int, err error) {
// TODO: consider refactoring with a bytes.Buffer.
if w.err != nil {
return 0, w.err
}
if len(p) == 0 {
return 0, nil
}

total := len(p)
for len(p) > 0 {
freeBuf := w.buf[len(w.unwritten):ChunkSize]
n := copy(freeBuf, p)
p = p[n:]
w.unwritten = w.unwritten[:len(w.unwritten)+n]

if len(w.unwritten) == ChunkSize && len(p) > 0 {
if err := w.flushChunk(notLastChunk); err != nil {
w.err = err
return 0, err
}
_, err = w.unwritten.Write(p)
if err != nil {
w.err = err
return 0, err
}

for w.unwritten.Len() > ChunkSize {
if err := w.flushChunk(notLastChunk); err != nil {
w.err = err
return 0, err
}
}

return total, nil
}

Expand All @@ -215,16 +214,19 @@ const (
)

func (w *Writer) flushChunk(last bool) error {
if !last && len(w.unwritten) != ChunkSize {
if !last && w.unwritten.Len() < ChunkSize {
panic("stream: internal error: flush called with partial chunk")
}

if last {
setLastChunkFlag(&w.nonce)
}
buf := w.a.Seal(w.buf[:0], w.nonce[:], w.unwritten, nil)
_, err := w.dst.Write(buf)
w.unwritten = w.buf[:0]

chunk := w.unwritten.Next(ChunkSize)
sealed := w.a.Seal(w.buf[:0], w.nonce[:], chunk, nil)
if _, err := w.dst.Write(sealed); err != nil {
return err
}
incNonce(&w.nonce)
return err
return nil
}
Loading