github.com/neohugo/neohugo@v0.123.8/common/hugio/writers.go (about)

     1  // Copyright 2018 The Hugo Authors. 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  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package hugio
    15  
    16  import (
    17  	"io"
    18  )
    19  
    20  // As implemented by strings.Builder.
    21  type FlexiWriter interface {
    22  	io.Writer
    23  	io.ByteWriter
    24  	WriteString(s string) (int, error)
    25  	WriteRune(r rune) (int, error)
    26  }
    27  
    28  type multiWriteCloser struct {
    29  	io.Writer
    30  	closers []io.WriteCloser
    31  }
    32  
    33  func (m multiWriteCloser) Close() error {
    34  	var err error
    35  	for _, c := range m.closers {
    36  		if closeErr := c.Close(); closeErr != nil {
    37  			err = closeErr
    38  		}
    39  	}
    40  	return err
    41  }
    42  
    43  // NewMultiWriteCloser creates a new io.WriteCloser that duplicates its writes to all the
    44  // provided writers.
    45  func NewMultiWriteCloser(writeClosers ...io.WriteCloser) io.WriteCloser {
    46  	writers := make([]io.Writer, len(writeClosers))
    47  	for i, w := range writeClosers {
    48  		writers[i] = w
    49  	}
    50  	return multiWriteCloser{Writer: io.MultiWriter(writers...), closers: writeClosers}
    51  }
    52  
    53  // ToWriteCloser creates an io.WriteCloser from the given io.Writer.
    54  // If it's not already, one will be created with a Close method that does nothing.
    55  func ToWriteCloser(w io.Writer) io.WriteCloser {
    56  	if rw, ok := w.(io.WriteCloser); ok {
    57  		return rw
    58  	}
    59  
    60  	return struct {
    61  		io.Writer
    62  		io.Closer
    63  	}{
    64  		w,
    65  		io.NopCloser(nil),
    66  	}
    67  }
    68  
    69  // ToReadCloser creates an io.ReadCloser from the given io.Reader.
    70  // If it's not already, one will be created with a Close method that does nothing.
    71  func ToReadCloser(r io.Reader) io.ReadCloser {
    72  	if rc, ok := r.(io.ReadCloser); ok {
    73  		return rc
    74  	}
    75  
    76  	return struct {
    77  		io.Reader
    78  		io.Closer
    79  	}{
    80  		r,
    81  		io.NopCloser(nil),
    82  	}
    83  }