github.com/stellar/go-xdr@v0.0.0-20231122183749-b53fb00bcac2/xdr3/fixedIO_test.go (about)

     1  /*
     2   * Copyright (c) 2014 Dave Collins <dave@davec.name>
     3   *
     4   * Permission to use, copy, modify, and distribute this software for any
     5   * purpose with or without fee is hereby granted, provided that the above
     6   * copyright notice and this permission notice appear in all copies.
     7   *
     8   * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     9   * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    10   * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    11   * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    12   * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    13   * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    14   * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    15   */
    16  
    17  package xdr_test
    18  
    19  import (
    20  	"io"
    21  )
    22  
    23  // fixedWriter implements the io.Writer interface and intentially allows
    24  // testing of error paths by forcing short writes.
    25  type fixedWriter struct {
    26  	b   []byte
    27  	pos int
    28  }
    29  
    30  // Write writes the contents of p to w. When the contents of p would cause
    31  // the writer to exceed the maximum allowed size of the fixed writer, the writer
    32  // writes as many bytes as possible to reach the maximum allowed size and
    33  // io.ErrShortWrite is returned.
    34  //
    35  // This satisfies the io.Writer interface.
    36  func (w *fixedWriter) Write(p []byte) (int, error) {
    37  	if w.pos+len(p) > cap(w.b) {
    38  		n := copy(w.b[w.pos:], p[:cap(w.b)-w.pos])
    39  		w.pos += n
    40  		return n, io.ErrShortWrite
    41  	}
    42  
    43  	n := copy(w.b[w.pos:], p)
    44  	w.pos += n
    45  	return n, nil
    46  }
    47  
    48  // Bytes returns the bytes already written to the fixed writer.
    49  func (w *fixedWriter) Bytes() []byte {
    50  	return w.b
    51  }
    52  
    53  // newFixedWriter returns a new io.Writer that will error once more bytes than
    54  // the specified max have been written.
    55  func newFixedWriter(max int) *fixedWriter {
    56  	b := make([]byte, max, max)
    57  	fw := fixedWriter{b, 0}
    58  	return &fw
    59  }