go4.org@v0.0.0-20230225012048-214862532bf5/readerutil/readersize.go (about)

     1  /*
     2  Copyright 2012 The Go4 Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package readerutil provides and operates on io.Readers.
    18  package readerutil // import "go4.org/readerutil"
    19  
    20  import (
    21  	"bytes"
    22  	"io"
    23  	"os"
    24  	"strings"
    25  )
    26  
    27  // Size tries to determine the length of r. If r is an io.Seeker, Size may seek
    28  // to guess the length.
    29  func Size(r io.Reader) (size int64, ok bool) {
    30  	switch rt := r.(type) {
    31  	case *bytes.Buffer:
    32  		return int64(rt.Len()), true
    33  	case *bytes.Reader:
    34  		return int64(rt.Len()), true
    35  	case *strings.Reader:
    36  		return int64(rt.Len()), true
    37  	case io.Seeker:
    38  		pos, err := rt.Seek(0, os.SEEK_CUR)
    39  		if err != nil {
    40  			return
    41  		}
    42  		end, err := rt.Seek(0, os.SEEK_END)
    43  		if err != nil {
    44  			return
    45  		}
    46  		size = end - pos
    47  		pos1, err := rt.Seek(pos, os.SEEK_SET)
    48  		if err != nil || pos1 != pos {
    49  			msg := "failed to restore seek position"
    50  			if err != nil {
    51  				msg += ": " + err.Error()
    52  			}
    53  			panic(msg)
    54  		}
    55  		return size, true
    56  	}
    57  	return 0, false
    58  }