github.com/aykevl/tinygo@v0.5.0/testdata/gc.go (about)

     1  package main
     2  
     3  var xorshift32State uint32 = 1
     4  
     5  func xorshift32(x uint32) uint32 {
     6  	// Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs"
     7  	x ^= x << 13
     8  	x ^= x >> 17
     9  	x ^= x << 5
    10  	return x
    11  }
    12  
    13  func randuint32() uint32 {
    14  	xorshift32State = xorshift32(xorshift32State)
    15  	return xorshift32State
    16  }
    17  
    18  func main() {
    19  	testNonPointerHeap()
    20  }
    21  
    22  var scalarSlices [4][]byte
    23  var randSeeds [4]uint32
    24  
    25  func testNonPointerHeap() {
    26  	// Allocate roughly 0.5MB of memory.
    27  	for i := 0; i < 1000; i++ {
    28  		// Pick a random index that the optimizer can't predict.
    29  		index := randuint32() % 4
    30  
    31  		// Check whether the contents of the previous allocation was correct.
    32  		rand := randSeeds[index]
    33  		for _, b := range scalarSlices[index] {
    34  			rand = xorshift32(rand)
    35  			if b != byte(rand) {
    36  				panic("memory was overwritten!")
    37  			}
    38  		}
    39  
    40  		// Allocate a randomly-sized slice, randomly sliced to be smaller.
    41  		sliceLen := randuint32() % 1024
    42  		slice := make([]byte, sliceLen)
    43  		cutLen := randuint32() % 1024
    44  		if cutLen < sliceLen {
    45  			slice = slice[cutLen:]
    46  		}
    47  		scalarSlices[index] = slice
    48  
    49  		// Fill the slice with a pattern that looks random but is easily
    50  		// calculated and verified.
    51  		rand = randuint32() + 1
    52  		randSeeds[index] = rand
    53  		for i := 0; i < len(slice); i++ {
    54  			rand = xorshift32(rand)
    55  			slice[i] = byte(rand)
    56  		}
    57  	}
    58  	println("ok")
    59  }