...

Source file src/github.com/AdaLogics/go-fuzz-headers/bytesource/bytesource.go

Documentation: github.com/AdaLogics/go-fuzz-headers/bytesource

     1  // Copyright 2023 The go-fuzz-headers Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bytesource
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/binary"
    20  	"io"
    21  	"math/rand"
    22  )
    23  
    24  type ByteSource struct {
    25  	*bytes.Reader
    26  	fallback rand.Source
    27  }
    28  
    29  // New returns a new ByteSource from a given slice of bytes.
    30  func New(input []byte) *ByteSource {
    31  	s := &ByteSource{
    32  		Reader:   bytes.NewReader(input),
    33  		fallback: rand.NewSource(0),
    34  	}
    35  	if len(input) > 0 {
    36  		s.fallback = rand.NewSource(int64(s.consumeUint64()))
    37  	}
    38  	return s
    39  }
    40  
    41  func (s *ByteSource) Uint64() uint64 {
    42  	// Return from input if it was not exhausted.
    43  	if s.Len() > 0 {
    44  		return s.consumeUint64()
    45  	}
    46  
    47  	// Input was exhausted, return random number from fallback (in this case fallback should not be
    48  	// nil). Try first having a Uint64 output (Should work in current rand implementation),
    49  	// otherwise return a conversion of Int63.
    50  	if s64, ok := s.fallback.(rand.Source64); ok {
    51  		return s64.Uint64()
    52  	}
    53  	return uint64(s.fallback.Int63())
    54  }
    55  
    56  func (s *ByteSource) Int63() int64 {
    57  	return int64(s.Uint64() >> 1)
    58  }
    59  
    60  func (s *ByteSource) Seed(seed int64) {
    61  	s.fallback = rand.NewSource(seed)
    62  	s.Reader = bytes.NewReader(nil)
    63  }
    64  
    65  // consumeUint64 reads 8 bytes from the input and convert them to a uint64. It assumes that the the
    66  // bytes reader is not empty.
    67  func (s *ByteSource) consumeUint64() uint64 {
    68  	var bytes [8]byte
    69  	_, err := s.Read(bytes[:])
    70  	if err != nil && err != io.EOF {
    71  		panic("failed reading source") // Should not happen.
    72  	}
    73  	return binary.BigEndian.Uint64(bytes[:])
    74  }
    75  

View as plain text