From 2dbc5d26c773e4400c0adfc25d9160eeaf6530b0 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Thu, 10 Apr 2014 15:46:07 -0700 Subject: [PATCH] bytes, strings: add Reader.ReadAt race tests Tests for the race detector to catch anybody trying to mutate Reader in ReadAt. LGTM=gri R=gri CC=golang-codereviews https://golang.org/cl/86700043 --- src/pkg/bytes/reader.go | 1 + src/pkg/bytes/reader_test.go | 17 +++++++++++++++++ src/pkg/strings/reader.go | 1 + src/pkg/strings/reader_test.go | 17 +++++++++++++++++ 4 files changed, 36 insertions(+) diff --git a/src/pkg/bytes/reader.go b/src/pkg/bytes/reader.go index cdc3233219..61845e350b 100644 --- a/src/pkg/bytes/reader.go +++ b/src/pkg/bytes/reader.go @@ -43,6 +43,7 @@ func (r *Reader) Read(b []byte) (n int, err error) { } func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) { + // cannot modify state - see io.ReaderAt if off < 0 { return 0, errors.New("bytes: invalid offset") } diff --git a/src/pkg/bytes/reader_test.go b/src/pkg/bytes/reader_test.go index a25f8ff0e3..7abaee7fad 100644 --- a/src/pkg/bytes/reader_test.go +++ b/src/pkg/bytes/reader_test.go @@ -10,6 +10,7 @@ import ( "io" "io/ioutil" "os" + "sync" "testing" ) @@ -98,6 +99,22 @@ func TestReaderAt(t *testing.T) { } } +func TestReaderAtConcurrent(t *testing.T) { + // Test for the race detector, to verify ReadAt doesn't mutate + // any state. + r := NewReader([]byte("0123456789")) + var wg sync.WaitGroup + for i := 0; i < 5; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + var buf [1]byte + r.ReadAt(buf[:], int64(i)) + }(i) + } + wg.Wait() +} + func TestReaderWriteTo(t *testing.T) { for i := 0; i < 30; i += 3 { var l int diff --git a/src/pkg/strings/reader.go b/src/pkg/strings/reader.go index 93ff804ed1..c02d33bd61 100644 --- a/src/pkg/strings/reader.go +++ b/src/pkg/strings/reader.go @@ -42,6 +42,7 @@ func (r *Reader) Read(b []byte) (n int, err error) { } func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) { + // cannot modify state - see io.ReaderAt if off < 0 { return 0, errors.New("strings: invalid offset") } diff --git a/src/pkg/strings/reader_test.go b/src/pkg/strings/reader_test.go index c7a34123ac..5995f21038 100644 --- a/src/pkg/strings/reader_test.go +++ b/src/pkg/strings/reader_test.go @@ -10,6 +10,7 @@ import ( "io" "os" "strings" + "sync" "testing" ) @@ -98,6 +99,22 @@ func TestReaderAt(t *testing.T) { } } +func TestReaderAtConcurrent(t *testing.T) { + // Test for the race detector, to verify ReadAt doesn't mutate + // any state. + r := strings.NewReader("0123456789") + var wg sync.WaitGroup + for i := 0; i < 5; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + var buf [1]byte + r.ReadAt(buf[:], int64(i)) + }(i) + } + wg.Wait() +} + func TestWriteTo(t *testing.T) { const str = "0123456789" for i := 0; i <= len(str); i++ { -- 2.50.0