github.com/TrenchBoot/u-root@v6.0.1-0.20200623220532-550e36da3258+incompatible/pkg/uio/reader.go (about)

     1  // Copyright 2018 the u-root 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 uio
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"io/ioutil"
    11  	"math"
    12  	"reflect"
    13  )
    14  
    15  type inMemReaderAt interface {
    16  	Bytes() []byte
    17  }
    18  
    19  // ReadAll reads everything that r contains.
    20  //
    21  // Callers *must* not modify bytes in the returned byte slice.
    22  //
    23  // If r is an in-memory representation, ReadAll will attempt to return a
    24  // pointer to those bytes directly.
    25  func ReadAll(r io.ReaderAt) ([]byte, error) {
    26  	if imra, ok := r.(inMemReaderAt); ok {
    27  		return imra.Bytes(), nil
    28  	}
    29  	return ioutil.ReadAll(Reader(r))
    30  }
    31  
    32  // Reader generates a Reader from a ReaderAt.
    33  func Reader(r io.ReaderAt) io.Reader {
    34  	return io.NewSectionReader(r, 0, math.MaxInt64)
    35  }
    36  
    37  // ReaderAtEqual compares the contents of r1 and r2.
    38  func ReaderAtEqual(r1, r2 io.ReaderAt) bool {
    39  	var c, d []byte
    40  	var r1err, r2err error
    41  	if r1 != nil {
    42  		c, r1err = ReadAll(r1)
    43  	}
    44  	if r2 != nil {
    45  		d, r2err = ReadAll(r2)
    46  	}
    47  	return bytes.Equal(c, d) && reflect.DeepEqual(r1err, r2err)
    48  }