Skip to content

Commit

Permalink
refactor: set the error using a setter
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Feb 1, 2023
1 parent 5cd552b commit e0930c1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
2 changes: 1 addition & 1 deletion enc_stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func TestEncoder_ResetWriter(t *testing.T) {
// This benchmark is used to measure the overhead of ignoring errors.
func BenchmarkSkipError(b *testing.B) {
e := NewStreamingEncoder(io.Discard, 32)
e.w.stream.writeErr = errors.New("test")
e.w.stream.setError(errors.New("test"))

b.ResetTimer()
b.ReportAllocs()
Expand Down
4 changes: 2 additions & 2 deletions w_b64.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ func (w *Writer) Base64(data []byte) bool {
}
e := stdbase64.NewEncoder(stdbase64.StdEncoding, s.writer)
if _, err := e.Write(data); err != nil {
s.writeErr = err
s.setError(err)
return true
}
if err := e.Close(); err != nil {
s.writeErr = err
s.setError(err)
return true
}
}
Expand Down
20 changes: 14 additions & 6 deletions w_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,26 @@ func (s *streamState) Reset(w io.Writer) {
s.writeErr = nil
}

func (s *streamState) setError(err error) {
s.writeErr = err
}

func (s *streamState) fail() bool {
return s.writeErr != nil
}

func (s *streamState) flush(buf []byte) ([]byte, bool) {
if s.writeErr != nil {
if s.fail() {
return nil, true
}

var n int
n, s.writeErr = s.writer.Write(buf)
n, err := s.writer.Write(buf)
switch {
case s.writeErr != nil:
case err != nil:
s.setError(err)
return nil, true
case n != len(buf):
s.writeErr = io.ErrShortWrite
s.setError(io.ErrShortWrite)
return nil, true
default:
buf = buf[:0]
Expand All @@ -73,7 +81,7 @@ func writeStreamByteseq[S byteseq.Byteseq](w *Writer, s S) bool {
return false
}

if w.stream.writeErr != nil {
if w.stream.fail() {
return true
}

Expand Down

0 comments on commit e0930c1

Please sign in to comment.