hugo

Fork of github.com/gohugoio/hugo with reverse pagination support

git clone git://git.shimmy1996.com/hugo.git

writers.go (2102B)

    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 	"io/ioutil"
   19 )
   20 
   21 // As implemented by strings.Builder.
   22 type FlexiWriter interface {
   23 	io.Writer
   24 	io.ByteWriter
   25 	WriteString(s string) (int, error)
   26 	WriteRune(r rune) (int, error)
   27 }
   28 
   29 type multiWriteCloser struct {
   30 	io.Writer
   31 	closers []io.WriteCloser
   32 }
   33 
   34 func (m multiWriteCloser) Close() error {
   35 	var err error
   36 	for _, c := range m.closers {
   37 		if closeErr := c.Close(); err != nil {
   38 			err = closeErr
   39 		}
   40 	}
   41 	return err
   42 }
   43 
   44 // NewMultiWriteCloser creates a new io.WriteCloser that duplicates its writes to all the
   45 // provided writers.
   46 func NewMultiWriteCloser(writeClosers ...io.WriteCloser) io.WriteCloser {
   47 	writers := make([]io.Writer, len(writeClosers))
   48 	for i, w := range writeClosers {
   49 		writers[i] = w
   50 	}
   51 	return multiWriteCloser{Writer: io.MultiWriter(writers...), closers: writeClosers}
   52 }
   53 
   54 // ToWriteCloser creates an io.WriteCloser from the given io.Writer.
   55 // If it's not already, one will be created with a Close method that does nothing.
   56 func ToWriteCloser(w io.Writer) io.WriteCloser {
   57 	if rw, ok := w.(io.WriteCloser); ok {
   58 		return rw
   59 	}
   60 
   61 	return struct {
   62 		io.Writer
   63 		io.Closer
   64 	}{
   65 		w,
   66 		ioutil.NopCloser(nil),
   67 	}
   68 }
   69 
   70 // ToReadCloser creates an io.ReadCloser from the given io.Reader.
   71 // If it's not already, one will be created with a Close method that does nothing.
   72 func ToReadCloser(r io.Reader) io.ReadCloser {
   73 	if rc, ok := r.(io.ReadCloser); ok {
   74 		return rc
   75 	}
   76 
   77 	return struct {
   78 		io.Reader
   79 		io.Closer
   80 	}{
   81 		r,
   82 		ioutil.NopCloser(nil),
   83 	}
   84 }