Imported Upstream version 2.5.1
[scm/test.git] / git / pkt_line_reader.go
1 package git
2
3 import (
4         "io"
5
6         "github.com/git-lfs/git-lfs/tools"
7 )
8
9 type pktlineReader struct {
10         pl *pktline
11
12         buf []byte
13 }
14
15 var _ io.Reader = new(pktlineReader)
16
17 func (r *pktlineReader) Read(p []byte) (int, error) {
18         var n int
19
20         if len(r.buf) > 0 {
21                 // If there is data in the buffer, shift as much out of it and
22                 // into the given "p" as we can.
23                 n = tools.MinInt(len(p), len(r.buf))
24
25                 copy(p, r.buf[:n])
26                 r.buf = r.buf[n:]
27         }
28
29         // Loop and grab as many packets as we can in a given "run", until we
30         // have either, a) overfilled the given buffer "p", or we have started
31         // to internally buffer in "r.buf".
32         for len(r.buf) == 0 {
33                 chunk, err := r.pl.readPacket()
34                 if err != nil {
35                         return n, err
36                 }
37
38                 if len(chunk) == 0 {
39                         // If we got an empty chunk, then we know that we have
40                         // reached the end of processing for this particular
41                         // packet, so let's terminate.
42
43                         return n, io.EOF
44                 }
45
46                 // Figure out how much of the packet we can read into "p".
47                 nn := tools.MinInt(len(chunk), len(p[n:]))
48
49                 // Move that amount into "p", from where we left off.
50                 copy(p[n:], chunk[:nn])
51                 // And move the rest into the buffer.
52                 r.buf = append(r.buf, chunk[nn:]...)
53
54                 // Mark that we have read "nn" bytes into "p"
55                 n += nn
56         }
57
58         return n, nil
59 }