github.com/unidoc/unidoc@v2.2.0+incompatible/pdf/core/io.go (about) 1 /* 2 * This file is subject to the terms and conditions defined in 3 * file 'LICENSE.md', which is part of this source code package. 4 */ 5 6 package core 7 8 import ( 9 "bufio" 10 "errors" 11 "os" 12 13 "github.com/unidoc/unidoc/common" 14 ) 15 16 // ReadAtLeast reads at least n bytes into slice p. 17 // Returns the number of bytes read (should always be == n), and an error on failure. 18 // TODO (v3): Unexport. 19 func (parser *PdfParser) ReadAtLeast(p []byte, n int) (int, error) { 20 remaining := n 21 start := 0 22 numRounds := 0 23 for remaining > 0 { 24 nRead, err := parser.reader.Read(p[start:]) 25 if err != nil { 26 common.Log.Debug("ERROR Failed reading (%d;%d) %s", nRead, numRounds, err.Error()) 27 return start, errors.New("Failed reading") 28 } 29 numRounds++ 30 start += nRead 31 remaining -= nRead 32 } 33 return start, nil 34 } 35 36 // Get the current file offset, accounting for buffered position. 37 // TODO (v3): Unexport. 38 func (parser *PdfParser) GetFileOffset() int64 { 39 offset, _ := parser.rs.Seek(0, os.SEEK_CUR) 40 offset -= int64(parser.reader.Buffered()) 41 return offset 42 } 43 44 // Seek the file to an offset position. 45 // TODO (v3): Unexport. 46 func (parser *PdfParser) SetFileOffset(offset int64) { 47 parser.rs.Seek(offset, os.SEEK_SET) 48 parser.reader = bufio.NewReader(parser.rs) 49 }