Debian Codegraph @

plumbing/format/objfile/writer.go

raw
1 package objfile
2
3 import (
4 "compress/zlib"
5 "errors"
6 "io"
7 "strconv"
8
9 "github.com/go-git/go-git/v5/plumbing"
10 "github.com/go-git/go-git/v5/utils/sync"
11 )
12
13 var (
14 ErrOverflow = errors.New("objfile: declared data length exceeded (overflow)")
15 )
16
17 // Writer writes and encodes data in compressed objfile format to a provided
18 // io.Writer. Close should be called when finished with the Writer. Close will
19 // not close the underlying io.Writer.
20 type Writer struct {
21 raw io.Writer
22 hasher plumbing.Hasher
23 multi io.Writer
24 zlib *zlib.Writer
25
26 closed bool
27 pending int64 // number of unwritten bytes
28 }
29
30 // NewWriter returns a new Writer writing to w.
31 //
32 // The returned Writer implements io.WriteCloser. Close should be called when
33 // finished with the Writer. Close will not close the underlying io.Writer.
34 func NewWriter(w io.Writer) *Writer {
35 zlib := sync.GetZlibWriter(w)
36 return &Writer{
37 raw: w,
38 zlib: zlib,
39 }
40 }
41
42 // WriteHeader writes the type and the size and prepares to accept the object's
43 // contents. If an invalid t is provided, plumbing.ErrInvalidType is returned. If a
44 // negative size is provided, ErrNegativeSize is returned.
45 func (w *Writer) WriteHeader(t plumbing.ObjectType, size int64) error {
46 if !t.Valid() {
47 return plumbing.ErrInvalidType
48 }
49 if size < 0 {
50 return ErrNegativeSize
51 }
52
53 b := t.Bytes()
54 b = append(b, ' ')
55 b = append(b, []byte(strconv.FormatInt(size, 10))...)
56 b = append(b, 0)
57
58 defer w.prepareForWrite(t, size)
59 _, err := w.zlib.Write(b)
60
61 return err
62 }
63
64 func (w *Writer) prepareForWrite(t plumbing.ObjectType, size int64) {
65 w.pending = size
66
67 w.hasher = plumbing.NewHasher(t, size)
68 w.multi = io.MultiWriter(w.zlib, w.hasher)
69 }
70
71 // Write writes the object's contents. Write returns the error ErrOverflow if
72 // more than size bytes are written after WriteHeader.
73 func (w *Writer) Write(p []byte) (n int, err error) {
74 if w.closed {
75 return 0, ErrClosed
76 }
77
78 overwrite := false
79 if int64(len(p)) > w.pending {
80 p = p[0:w.pending]
81 overwrite = true
82 }
83
84 n, err = w.multi.Write(p)
85 w.pending -= int64(n)
86 if err == nil && overwrite {
87 err = ErrOverflow
88 return
89 }
90
91 return
92 }
93
94 // Hash returns the hash of the object data stream that has been written so far.
95 // It can be called before or after Close.
96 func (w *Writer) Hash() plumbing.Hash {
97 return w.hasher.Sum() // Not yet closed, return hash of data written so far
98 }
99
100 // Close releases any resources consumed by the Writer.
101 //
102 // Calling Close does not close the wrapped io.Writer originally passed to
103 // NewWriter.
104 func (w *Writer) Close() error {
105 defer sync.PutZlibWriter(w.zlib)
106 if err := w.zlib.Close(); err != nil {
107 return err
108 }
109
110 w.closed = true
111 return nil
112 }