github.com/FenixAra/go@v0.0.0-20170127160404-96ea0918e670/src/cmd/internal/bio/buf.go (about)

     1  // Copyright 2015 The Go 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 bio implements common I/O abstractions used within the Go toolchain.
     6  package bio
     7  
     8  import (
     9  	"bufio"
    10  	"log"
    11  	"os"
    12  )
    13  
    14  // Reader implements a seekable buffered io.Reader.
    15  type Reader struct {
    16  	f *os.File
    17  	*bufio.Reader
    18  }
    19  
    20  // Writer implements a seekable buffered io.Writer.
    21  type Writer struct {
    22  	f *os.File
    23  	*bufio.Writer
    24  }
    25  
    26  // Create creates the file named name and returns a Writer
    27  // for that file.
    28  func Create(name string) (*Writer, error) {
    29  	f, err := os.Create(name)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	return &Writer{f: f, Writer: bufio.NewWriter(f)}, nil
    34  }
    35  
    36  // Open returns a Reader for the file named name.
    37  func Open(name string) (*Reader, error) {
    38  	f, err := os.Open(name)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	return &Reader{f: f, Reader: bufio.NewReader(f)}, nil
    43  }
    44  
    45  func (r *Reader) Seek(offset int64, whence int) int64 {
    46  	if whence == 1 {
    47  		offset -= int64(r.Buffered())
    48  	}
    49  	off, err := r.f.Seek(offset, whence)
    50  	if err != nil {
    51  		log.Fatalf("seeking in output: %v", err)
    52  	}
    53  	r.Reset(r.f)
    54  	return off
    55  }
    56  
    57  func (w *Writer) Seek(offset int64, whence int) int64 {
    58  	if err := w.Flush(); err != nil {
    59  		log.Fatalf("writing output: %v", err)
    60  	}
    61  	off, err := w.f.Seek(offset, whence)
    62  	if err != nil {
    63  		log.Fatalf("seeking in output: %v", err)
    64  	}
    65  	return off
    66  }
    67  
    68  func (r *Reader) Offset() int64 {
    69  	off, err := r.f.Seek(0, 1)
    70  	if err != nil {
    71  		log.Fatalf("seeking in output [0, 1]: %v", err)
    72  	}
    73  	off -= int64(r.Buffered())
    74  	return off
    75  }
    76  
    77  func (w *Writer) Offset() int64 {
    78  	if err := w.Flush(); err != nil {
    79  		log.Fatalf("writing output: %v", err)
    80  	}
    81  	off, err := w.f.Seek(0, 1)
    82  	if err != nil {
    83  		log.Fatalf("seeking in output [0, 1]: %v", err)
    84  	}
    85  	return off
    86  }
    87  
    88  func (r *Reader) Close() error {
    89  	return r.f.Close()
    90  }
    91  
    92  func (w *Writer) Close() error {
    93  	err := w.Flush()
    94  	err1 := w.f.Close()
    95  	if err == nil {
    96  		err = err1
    97  	}
    98  	return err
    99  }