go4.org@v0.0.0-20230225012048-214862532bf5/readerutil/bufreaderat_test.go (about)

     1  /*
     2  Copyright 2018 The go4 Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package readerutil
    18  
    19  import "testing"
    20  
    21  type trackingReader struct {
    22  	off       int
    23  	reads     int
    24  	readBytes int
    25  }
    26  
    27  func (t *trackingReader) Read(p []byte) (n int, err error) {
    28  	t.reads++
    29  	t.readBytes += len(p)
    30  	for len(p) > 0 {
    31  		p[0] = '0' + byte(t.off%10)
    32  		t.off++
    33  		p = p[1:]
    34  		n++
    35  	}
    36  	return
    37  
    38  }
    39  
    40  func TestBufferingReaderAt(t *testing.T) {
    41  	tr := new(trackingReader)
    42  	ra := NewBufferingReaderAt(tr)
    43  	for i, tt := range []struct {
    44  		off           int64
    45  		want          string
    46  		wantReads     int
    47  		wantReadBytes int
    48  	}{
    49  		{off: 0, want: "0123456789", wantReads: 1, wantReadBytes: 10},
    50  		{off: 5, want: "56789", wantReads: 1, wantReadBytes: 10},      // already buffered
    51  		{off: 6, want: "67890", wantReads: 2, wantReadBytes: 11},      // need 1 more byte
    52  		{off: 0, want: "0123456789", wantReads: 2, wantReadBytes: 11}, // already buffered
    53  	} {
    54  		got := make([]byte, len(tt.want))
    55  		n, err := ra.ReadAt(got, tt.off)
    56  		if err != nil || n != len(tt.want) {
    57  			t.Errorf("step %d: ReadAt = %v, %v; want %v, %v", i, n, err, len(tt.want), nil)
    58  			continue
    59  		}
    60  		if string(got) != tt.want {
    61  			t.Errorf("step %d: ReadAt read %q; want %q", i, got, tt.want)
    62  		}
    63  		if tr.reads != tt.wantReads {
    64  			t.Errorf("step %d: num reads = %d; want %d", i, tr.reads, tt.wantReads)
    65  		}
    66  		if tr.readBytes != tt.wantReadBytes {
    67  			t.Errorf("step %d: read bytes = %d; want %d", i, tr.reads, tt.wantReads)
    68  		}
    69  	}
    70  }