-
Notifications
You must be signed in to change notification settings - Fork 19
/
writer.go
111 lines (90 loc) · 2.06 KB
/
writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package siva
import (
"errors"
"io"
)
var (
ErrMissingHeader = errors.New("WriteHeader was not called, or already flushed")
ErrClosedWriter = errors.New("Writer is closed")
)
// A Writer provides sequential writing of a siva archive
type Writer interface {
io.Writer
io.Closer
WriteHeader(h *Header) error
Flush() error
}
type writer struct {
w *hashedWriter
index Index
oIndex OrderedIndex
current *IndexEntry
position uint64
closed bool
}
// NewWriter creates a new Writer writing to w.
func NewWriter(w io.Writer) Writer {
return newWriter(w)
}
func newWriter(w io.Writer) *writer {
return &writer{
w: newHashedWriter(w),
}
}
// WriteHeader writes hdr and prepares to accept the file's contents.
func (w *writer) WriteHeader(h *Header) error {
if err := w.flushIfPending(); err != nil {
return err
}
w.current = &IndexEntry{
Header: (*h),
Start: w.position,
}
w.current.Name = ToSafePath(h.Name)
w.index = append(w.index, w.current)
w.oIndex = w.oIndex.Update(w.current)
return nil
}
// Write writes to the current entry in the siva archive, WriteHeader should
// called before, if not returns ErrMissingHeader
func (w *writer) Write(b []byte) (int, error) {
if w.current == nil {
return 0, ErrMissingHeader
}
n, err := w.w.Write(b)
w.position += uint64(n)
return n, err
}
// Flush finishes writing the current file (optional)
func (w *writer) Flush() error {
if w.closed {
return ErrClosedWriter
} else if w.current == nil {
return ErrMissingHeader
}
w.current.Size = w.position - w.current.Start
w.current.CRC32 = w.w.Checksum()
w.current = nil
w.w.Reset()
return nil
}
func (w *writer) flushIfPending() error {
if w.closed {
return ErrClosedWriter
} else if w.current == nil {
return nil
}
return w.Flush()
}
// Close closes the siva archive, writing the Index footer to the current writer.
func (w *writer) Close() error {
defer func() { w.closed = true }()
if err := w.flushIfPending(); err != nil {
return err
}
err := w.index.WriteTo(w.w)
if err == ErrEmptyIndex {
return nil
}
return err
}