github.com/slspeek/camlistore_namedsearch@v0.0.0-20140519202248-ed6f70f7721a/pkg/readerutil/readersize.go (about) 1 /* 2 Copyright 2012 The Camlistore 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 19 20 import ( 21 "bytes" 22 "io" 23 "os" 24 ) 25 26 // ReaderSize tries to determine the length of r. 27 func ReaderSize(r io.Reader) (size int64, ok bool) { 28 switch rt := r.(type) { 29 case io.Seeker: 30 pos, err := rt.Seek(0, os.SEEK_CUR) 31 if err != nil { 32 return 33 } 34 end, err := rt.Seek(0, os.SEEK_END) 35 if err != nil { 36 return 37 } 38 size = end - pos 39 pos1, err := rt.Seek(pos, os.SEEK_SET) 40 if err != nil || pos1 != pos { 41 msg := "failed to restore seek position" 42 if err != nil { 43 msg += ": " + err.Error() 44 } 45 panic(msg) 46 } 47 return size, true 48 case *bytes.Buffer: 49 return int64(rt.Len()), true 50 } 51 return 52 }