github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/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 "math" 11 "os" 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 io.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 } 49 50 // ReadIntoFile reads all from io.Reader into the file at given path. 51 // 52 // If the file at given path does not exist, a new file will be created. 53 // If the file exists at the given path, but not empty, it will be truncated. 54 func ReadIntoFile(r io.Reader, p string) error { 55 f, err := os.OpenFile(p, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0o644) 56 if err != nil { 57 return err 58 } 59 defer f.Close() 60 61 _, err = io.Copy(f, r) 62 if err != nil { 63 return err 64 } 65 66 return f.Close() 67 }