...

Source file src/internal/coverage/slicereader/slr_test.go

Documentation: internal/coverage/slicereader

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slicereader
     6  
     7  import (
     8  	"encoding/binary"
     9  	"io"
    10  	"testing"
    11  )
    12  
    13  func TestSliceReader(t *testing.T) {
    14  	b := []byte{}
    15  
    16  	bt := make([]byte, 4)
    17  	e32 := uint32(1030507)
    18  	binary.LittleEndian.PutUint32(bt, e32)
    19  	b = append(b, bt...)
    20  
    21  	bt = make([]byte, 8)
    22  	e64 := uint64(907050301)
    23  	binary.LittleEndian.PutUint64(bt, e64)
    24  	b = append(b, bt...)
    25  
    26  	b = appendUleb128(b, uint(e32))
    27  	b = appendUleb128(b, uint(e64))
    28  	b = appendUleb128(b, 6)
    29  	s1 := "foobar"
    30  	s1b := []byte(s1)
    31  	b = append(b, s1b...)
    32  	b = appendUleb128(b, 9)
    33  	s2 := "bazbasher"
    34  	s2b := []byte(s2)
    35  	b = append(b, s2b...)
    36  
    37  	readStr := func(slr *Reader) string {
    38  		len := slr.ReadULEB128()
    39  		return slr.ReadString(int64(len))
    40  	}
    41  
    42  	for i := 0; i < 2; i++ {
    43  		slr := NewReader(b, i == 0)
    44  		g32 := slr.ReadUint32()
    45  		if g32 != e32 {
    46  			t.Fatalf("slr.ReadUint32() got %d want %d", g32, e32)
    47  		}
    48  		g64 := slr.ReadUint64()
    49  		if g64 != e64 {
    50  			t.Fatalf("slr.ReadUint64() got %d want %d", g64, e64)
    51  		}
    52  		g32 = uint32(slr.ReadULEB128())
    53  		if g32 != e32 {
    54  			t.Fatalf("slr.ReadULEB128() got %d want %d", g32, e32)
    55  		}
    56  		g64 = slr.ReadULEB128()
    57  		if g64 != e64 {
    58  			t.Fatalf("slr.ReadULEB128() got %d want %d", g64, e64)
    59  		}
    60  		gs1 := readStr(slr)
    61  		if gs1 != s1 {
    62  			t.Fatalf("readStr got %s want %s", gs1, s1)
    63  		}
    64  		gs2 := readStr(slr)
    65  		if gs2 != s2 {
    66  			t.Fatalf("readStr got %s want %s", gs2, s2)
    67  		}
    68  		if _, err := slr.Seek(4, io.SeekStart); err != nil {
    69  			t.Fatal(err)
    70  		}
    71  		off := slr.Offset()
    72  		if off != 4 {
    73  			t.Fatalf("Offset() returned %d wanted 4", off)
    74  		}
    75  		g64 = slr.ReadUint64()
    76  		if g64 != e64 {
    77  			t.Fatalf("post-seek slr.ReadUint64() got %d want %d", g64, e64)
    78  		}
    79  	}
    80  }
    81  
    82  func appendUleb128(b []byte, v uint) []byte {
    83  	for {
    84  		c := uint8(v & 0x7f)
    85  		v >>= 7
    86  		if v != 0 {
    87  			c |= 0x80
    88  		}
    89  		b = append(b, c)
    90  		if c&0x80 == 0 {
    91  			break
    92  		}
    93  	}
    94  	return b
    95  }
    96  

View as plain text