-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreaming_zip_reader.go
98 lines (85 loc) · 2.21 KB
/
streaming_zip_reader.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
package main
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"io/fs"
)
const sniffSize = 512
// StreamingZipEntryReader implements fs.File as well as io.ReaderAt and
// io.ReadSeekCloser without actually loading the entire file into the memory.
type StreamingZipEntryReader struct {
fs.File
*bytes.Reader
}
func (s *StreamingZipEntryReader) Read(buffer []byte) (int, error) {
if s.Reader.Len() == 0 {
return s.File.Read(buffer)
}
res, err := s.Reader.Read(buffer)
if err != nil && errors.Is(err, io.EOF) {
return res, nil
}
return res, err
}
func (s *StreamingZipEntryReader) Seek(offset int64, whence int) (int64, error) {
if whence == io.SeekStart && offset == 0 {
return s.Reader.Seek(0, io.SeekStart)
}
if whence == io.SeekEnd && offset == 0 {
stat, err := s.File.Stat()
if err != nil {
return -1, err
}
return stat.Size(), nil
}
return -1, fmt.Errorf("unsupported seek parameters")
}
var (
_ io.ReadSeekCloser = &StreamingZipEntryReader{}
_ fs.File = &StreamingZipEntryReader{}
)
// NewStreamingZipEntryReader returns a lazy reader with limited seek.
// `file` must not be a directory.
func NewStreamingZipEntryReader(file fs.File) *StreamingZipEntryReader {
var buffer bytes.Buffer
_, err := io.CopyN(&buffer, file, sniffSize*2)
if err != nil && !errors.Is(err, io.EOF) {
panic(err)
}
return &StreamingZipEntryReader{
File: file,
Reader: bytes.NewReader(buffer.Bytes()),
}
}
type StreamingZipFS struct {
*zip.Reader
}
// Name returns the name of this implementation. This exists for test purpose.
func (zipFS *StreamingZipFS) Name() string {
return "StreamingZipFS"
}
func GetStreamingZipFs(reader io.ReaderAt, size int64) *StreamingZipFS {
zipReader, err := zip.NewReader(reader, size)
checkError(err, "cannot create ZIP reader")
return &StreamingZipFS{Reader: zipReader}
}
func (zipFS *StreamingZipFS) Open(name string) (fs.File, error) {
verbose("open: %s", name)
f, err := zipFS.Reader.Open(name)
if err != nil || f == nil {
verbose("error opening %s: %v", name, err)
return nil, err
}
stat, err := f.Stat()
if err != nil {
return nil, err
}
if stat.IsDir() {
return f, nil
}
return NewStreamingZipEntryReader(f), nil
}
var _ fs.FS = &BufferingZipFS{}