github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/util/pair.go (about)

     1  // Copyright (c) 2014, Kevin Walsh.  All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"io"
    19  	"io/ioutil"
    20  )
    21  
    22  // A PairReadWriteCloser groups an io.ReadCloser and an io.WriteCloser into a
    23  // single structure that implements the io.ReadWriteCloser interface. This can
    24  // be used to turn a pair of uni-directional streams into a single
    25  // bi-directional stream.
    26  type PairReadWriteCloser struct {
    27  	io.ReadCloser
    28  	io.WriteCloser
    29  }
    30  
    31  // Close closes the underying streams, both the io.ReadCloser and the
    32  // io.WriteCloser.
    33  func (pair PairReadWriteCloser) Close() error {
    34  	err1 := pair.ReadCloser.Close()
    35  	err2 := pair.WriteCloser.Close()
    36  	if err1 != nil {
    37  		return err1
    38  	}
    39  	return err2
    40  }
    41  
    42  // NewPairReadWriteCloser creates a new io.ReadWriteCloser given separate
    43  // streams for reading and writing. If both streams refer to the same object,
    44  // then the read stream will be wrapped in an ioutil.NopCloser() so that Close()
    45  // on the resulting io.ReadWriteCloser() will only close that underlying stream
    46  // object once.
    47  func NewPairReadWriteCloser(r io.ReadCloser, w io.WriteCloser) *PairReadWriteCloser {
    48  	if rw, _ := w.(io.ReadCloser); r == rw {
    49  		return &PairReadWriteCloser{ioutil.NopCloser(r), w}
    50  	}
    51  	return &PairReadWriteCloser{r, w}
    52  }