github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/wire/fixedIO_test.go (about)

     1  // Copyright (c) 2013-2015 The btcsuite developers
     2  // Copyright (c) 2016 The Dash developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package wire_test
     7  
     8  import (
     9  	"bytes"
    10  	"io"
    11  )
    12  
    13  // fixedWriter implements the io.Writer interface and intentially allows
    14  // testing of error paths by forcing short writes.
    15  type fixedWriter struct {
    16  	b   []byte
    17  	pos int
    18  }
    19  
    20  // Write writes the contents of p to w.  When the contents of p would cause
    21  // the writer to exceed the maximum allowed size of the fixed writer,
    22  // io.ErrShortWrite is returned and the writer is left unchanged.
    23  //
    24  // This satisfies the io.Writer interface.
    25  func (w *fixedWriter) Write(p []byte) (n int, err error) {
    26  	lenp := len(p)
    27  	if w.pos+lenp > cap(w.b) {
    28  		return 0, io.ErrShortWrite
    29  	}
    30  	n = lenp
    31  	w.pos += copy(w.b[w.pos:], p)
    32  	return
    33  }
    34  
    35  // Bytes returns the bytes already written to the fixed writer.
    36  func (w *fixedWriter) Bytes() []byte {
    37  	return w.b
    38  }
    39  
    40  // newFixedWriter returns a new io.Writer that will error once more bytes than
    41  // the specified max have been written.
    42  func newFixedWriter(max int) io.Writer {
    43  	b := make([]byte, max, max)
    44  	fw := fixedWriter{b, 0}
    45  	return &fw
    46  }
    47  
    48  // fixedReader implements the io.Reader interface and intentially allows
    49  // testing of error paths by forcing short reads.
    50  type fixedReader struct {
    51  	buf   []byte
    52  	pos   int
    53  	iobuf *bytes.Buffer
    54  }
    55  
    56  // Read reads the next len(p) bytes from the fixed reader.  When the number of
    57  // bytes read would exceed the maximum number of allowed bytes to be read from
    58  // the fixed writer, an error is returned.
    59  //
    60  // This satisfies the io.Reader interface.
    61  func (fr *fixedReader) Read(p []byte) (n int, err error) {
    62  	n, err = fr.iobuf.Read(p)
    63  	fr.pos += n
    64  	return
    65  }
    66  
    67  // newFixedReader returns a new io.Reader that will error once more bytes than
    68  // the specified max have been read.
    69  func newFixedReader(max int, buf []byte) io.Reader {
    70  	b := make([]byte, max, max)
    71  	if buf != nil {
    72  		copy(b[:], buf)
    73  	}
    74  
    75  	iobuf := bytes.NewBuffer(b)
    76  	fr := fixedReader{b, 0, iobuf}
    77  	return &fr
    78  }