forked from TRON-US/go-btfs-files
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathreaderfile.go
100 lines (80 loc) · 1.84 KB
/
readerfile.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
package files
import (
"bytes"
"io"
"os"
"path/filepath"
"time"
)
// ReaderFile is a implementation of File created from an `io.Reader`.
// ReaderFiles are never directories, and can be read from and closed.
type ReaderFile struct {
abspath string
reader io.ReadCloser
stat os.FileInfo
fsize int64
}
func NewBytesFile(b []byte) File {
return &ReaderFile{"", NewReaderFile(bytes.NewReader(b)), nil, int64(len(b))}
}
func NewReaderFile(reader io.Reader) File {
return NewReaderStatFile(reader, nil)
}
func NewReaderStatFile(reader io.Reader, stat os.FileInfo) File {
rc, ok := reader.(io.ReadCloser)
if !ok {
rc = io.NopCloser(reader)
}
return &ReaderFile{"", rc, stat, -1}
}
func NewReaderPathFile(path string, reader io.ReadCloser, stat os.FileInfo) (*ReaderFile, error) {
abspath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
return &ReaderFile{abspath, reader, stat, -1}, nil
}
func (f *ReaderFile) AbsPath() string {
return f.abspath
}
func (f *ReaderFile) Read(p []byte) (int, error) {
return f.reader.Read(p)
}
func (f *ReaderFile) Close() error {
return f.reader.Close()
}
func (f *ReaderFile) Stat() os.FileInfo {
return f.stat
}
func (f *ReaderFile) Mode() os.FileMode {
if f.stat == nil {
return 0
}
return f.stat.Mode()
}
func (f *ReaderFile) ModTime() time.Time {
if f.stat == nil {
return time.Time{}
}
return f.stat.ModTime()
}
func (f *ReaderFile) Size() (int64, error) {
if f.stat == nil {
if f.fsize >= 0 {
return f.fsize, nil
}
return 0, ErrNotSupported
}
return f.stat.Size(), nil
}
func (f *ReaderFile) Seek(offset int64, whence int) (int64, error) {
if s, ok := f.reader.(io.Seeker); ok {
return s.Seek(offset, whence)
}
return 0, ErrNotSupported
}
func (f *ReaderFile) Reader() io.Reader {
return f.reader
}
var _ File = &ReaderFile{}
var _ FileInfo = &ReaderFile{}