/
file_ios.go
123 lines (95 loc) · 2.24 KB
/
file_ios.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
112
113
114
115
116
117
118
119
120
121
122
123
// +build ios
package gomobile
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation
#import <stdlib.h>
void* iosParseUrl(const char* url);
const void* iosReadFromURL(void* url, int* len);
const int iosWriteToURL(void* url, const void* bytes, int len);
*/
import "C"
import (
"io"
"unsafe"
"fyne.io/fyne/v2/storage/repository"
)
type secureReadCloser struct {
url unsafe.Pointer
closer func()
data []byte
offset int
}
// Declare conformity to ReadCloser interface
var _ io.ReadCloser = (*secureReadCloser)(nil)
func (s *secureReadCloser) Read(p []byte) (int, error) {
if s.data == nil {
var length C.int
s.data = C.GoBytes(C.iosReadFromURL(s.url, &length), length)
}
count := len(p)
remain := len(s.data) - s.offset
var err error
if count >= remain {
count = remain
err = io.EOF
}
newOffset := s.offset + count
o := 0
for i := s.offset; i < newOffset; i++ {
p[o] = s.data[i]
o++
}
s.offset = newOffset
return count, err
}
func (s *secureReadCloser) Close() error {
if s.closer != nil {
s.closer()
}
s.url = nil
return nil
}
type secureWriteCloser struct {
url unsafe.Pointer
closer func()
offset int
}
// Declare conformity to WriteCloser interface
var _ io.WriteCloser = (*secureWriteCloser)(nil)
func (s *secureWriteCloser) Write(p []byte) (int, error) {
count := int(C.iosWriteToURL(s.url, C.CBytes(p), C.int(len(p))))
s.offset += count
return count, nil
}
func (s *secureWriteCloser) Close() error {
if s.closer != nil {
s.closer()
}
s.url = nil
return nil
}
func nativeFileOpen(f *fileOpen) (io.ReadCloser, error) {
if f.uri == nil || f.uri.String() == "" {
return nil, nil
}
cStr := C.CString(f.uri.String())
defer C.free(unsafe.Pointer(cStr))
url := C.iosParseUrl(cStr)
fileStruct := &secureReadCloser{url: url, closer: f.done}
return fileStruct, nil
}
func nativeFileSave(f *fileSave) (io.WriteCloser, error) {
if f.uri == nil || f.uri.String() == "" {
return nil, nil
}
cStr := C.CString(f.uri.String())
defer C.free(unsafe.Pointer(cStr))
url := C.iosParseUrl(cStr)
fileStruct := &secureWriteCloser{url: url, closer: f.done}
return fileStruct, nil
}
func registerRepository(d *mobileDriver) {
repo := &mobileFileRepo{driver: d}
repository.Register("file", repo)
}