OSDN Git Service

Update to current version of Go library.
[pf3gnuchains/gcc-fork.git] / libgo / go / image / tiff / buffer.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package tiff
6
7 import (
8         "io"
9         "os"
10 )
11
12 // buffer buffers an io.Reader to satisfy io.ReaderAt.
13 type buffer struct {
14         r   io.Reader
15         buf []byte
16 }
17
18 func (b *buffer) ReadAt(p []byte, off int64) (int, os.Error) {
19         o := int(off)
20         end := o + len(p)
21         if int64(end) != off+int64(len(p)) {
22                 return 0, os.EINVAL
23         }
24
25         m := len(b.buf)
26         if end > m {
27                 if end > cap(b.buf) {
28                         newcap := 1024
29                         for newcap < end {
30                                 newcap *= 2
31                         }
32                         newbuf := make([]byte, end, newcap)
33                         copy(newbuf, b.buf)
34                         b.buf = newbuf
35                 } else {
36                         b.buf = b.buf[:end]
37                 }
38                 if n, err := io.ReadFull(b.r, b.buf[m:end]); err != nil {
39                         end = m + n
40                         b.buf = b.buf[:end]
41                         return copy(p, b.buf[o:end]), err
42                 }
43         }
44
45         return copy(p, b.buf[o:end]), nil
46 }
47
48 // newReaderAt converts an io.Reader into an io.ReaderAt.
49 func newReaderAt(r io.Reader) io.ReaderAt {
50         if ra, ok := r.(io.ReaderAt); ok {
51                 return ra
52         }
53         return &buffer{
54                 r:   r,
55                 buf: make([]byte, 0, 1024),
56         }
57 }