github.com/pure-x-eth/consensus_tm@v0.0.0-20230502163723-e3c2ff987250/libs/test/mutate.go (about)

     1  package test
     2  
     3  import (
     4  	tmrand "github.com/pure-x-eth/consensus_tm/libs/rand"
     5  )
     6  
     7  // Contract: !bytes.Equal(input, output) && len(input) >= len(output)
     8  func MutateByteSlice(bytez []byte) []byte {
     9  	// If bytez is empty, panic
    10  	if len(bytez) == 0 {
    11  		panic("Cannot mutate an empty bytez")
    12  	}
    13  
    14  	// Copy bytez
    15  	mBytez := make([]byte, len(bytez))
    16  	copy(mBytez, bytez)
    17  	bytez = mBytez
    18  
    19  	// Try a random mutation
    20  	switch tmrand.Int() % 2 {
    21  	case 0: // Mutate a single byte
    22  		bytez[tmrand.Int()%len(bytez)] += byte(tmrand.Int()%255 + 1)
    23  	case 1: // Remove an arbitrary byte
    24  		pos := tmrand.Int() % len(bytez)
    25  		bytez = append(bytez[:pos], bytez[pos+1:]...)
    26  	}
    27  	return bytez
    28  }