Handle nil buffer in Reader and update tests

Updated the Reader struct in reader.go to properly handle nil buffers. This prevents potential errors from nil pointer dereference. Also added the fmt package for debugging purposes. Correspondingly, additional tests in reader_test.go were also added to cover these edge cases and ensure the Reader struct correctly handles them.
This commit is contained in:
Winni Neessen 2023-11-29 17:18:55 +01:00
parent b63d4803f1
commit b79374224c
Signed by: wneessen
GPG key ID: 5F3AF39B820C119D
2 changed files with 16 additions and 3 deletions

View file

@ -25,7 +25,7 @@ func (r *Reader) Read(p []byte) (n int, err error) {
if r.err != nil { if r.err != nil {
return 0, r.err return 0, r.err
} }
if r.empty() { if r.empty() || r.buf == nil {
r.Reset() r.Reset()
if len(p) == 0 { if len(p) == 0 {
return 0, nil return 0, nil

View file

@ -6,7 +6,9 @@ package mail
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io"
"testing" "testing"
) )
@ -64,9 +66,20 @@ func TestReader_Read_error(t *testing.T) {
// TestReader_Read_empty tests the Reader.Read method with an empty buffer // TestReader_Read_empty tests the Reader.Read method with an empty buffer
func TestReader_Read_empty(t *testing.T) { func TestReader_Read_empty(t *testing.T) {
r := Reader{buf: []byte{}} r := Reader{buf: []byte{}}
var p []byte p := make([]byte, 1)
p[0] = 'a'
_, err := r.Read(p) _, err := r.Read(p)
if err != nil { if err != nil && !errors.Is(err, io.EOF) {
t.Errorf("Reader failed: %s", err)
}
}
// TestReader_Read_nil tests the Reader.Read method with a nil buffer
func TestReader_Read_nil(t *testing.T) {
r := Reader{buf: nil, off: -10}
p := make([]byte, 0)
_, err := r.Read(p)
if err != nil && !errors.Is(err, io.EOF) {
t.Errorf("Reader failed: %s", err) t.Errorf("Reader failed: %s", err)
} }
} }