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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use core::ffi::{CStr, c_void};
use core::ptr::NonNull;
use flipperzero_sys::furi::UnsafeRecord;
use flipperzero_sys::{self as sys, HasFlag};
use crate::furi::string::FuriString;
use crate::io::*;
use crate::path::Path;
/// Storage service handle.
#[derive(Clone)]
pub struct Storage {
record: UnsafeRecord<sys::Storage>,
}
impl Storage {
pub const NAME: &CStr = c"storage";
/// Open handle to Storage service.
pub fn open() -> Self {
Self {
record: unsafe { UnsafeRecord::open(Self::NAME) },
}
}
/// Access raw Furi Storage record.
#[inline]
pub fn as_ptr(&self) -> *mut sys::Storage {
self.record.as_ptr()
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct OpenOptions {
access_mode: sys::FS_AccessMode,
open_mode: sys::FS_OpenMode,
}
impl OpenOptions {
pub fn new() -> Self {
Self::default()
}
fn from_parts(access_mode: sys::FS_AccessMode, open_mode: sys::FS_OpenMode) -> Self {
OpenOptions {
access_mode,
open_mode,
}
}
/// Read access
pub fn read(self, set: bool) -> Self {
OpenOptions::from_parts(
if set {
self.access_mode | sys::FSAM_READ
} else {
self.access_mode & !sys::FSAM_READ
},
self.open_mode,
)
}
/// Write access
pub fn write(self, set: bool) -> Self {
OpenOptions::from_parts(
if set {
self.access_mode | sys::FSAM_WRITE
} else {
self.access_mode & !sys::FSAM_WRITE
},
self.open_mode,
)
}
/// Open file, fail if file doesn't exist
pub fn open_existing(self, set: bool) -> Self {
OpenOptions::from_parts(
self.access_mode,
if set {
self.open_mode | sys::FSOM_OPEN_EXISTING
} else {
self.open_mode & !sys::FSOM_OPEN_EXISTING
},
)
}
/// Open file. Create new file if not exist
pub fn open_always(self, set: bool) -> Self {
OpenOptions::from_parts(
self.access_mode,
if set {
self.open_mode | sys::FSOM_OPEN_ALWAYS
} else {
self.open_mode & !sys::FSOM_OPEN_ALWAYS
},
)
}
/// Open file. Create new file if not exist. Set R/W pointer to EOF
pub fn open_append(self, set: bool) -> Self {
OpenOptions::from_parts(
self.access_mode,
if set {
self.open_mode | sys::FSOM_OPEN_APPEND
} else {
self.open_mode & !sys::FSOM_OPEN_APPEND
},
)
}
/// Creates a new file. Fails if the file is exist
pub fn create_new(self, set: bool) -> Self {
OpenOptions::from_parts(
self.access_mode,
if set {
self.open_mode | sys::FSOM_CREATE_NEW
} else {
self.open_mode & !sys::FSOM_CREATE_NEW
},
)
}
/// Creates a new file. If file exist, truncate to zero size
pub fn create_always(self, set: bool) -> Self {
OpenOptions::from_parts(
self.access_mode,
if set {
self.open_mode | sys::FSOM_CREATE_ALWAYS
} else {
self.open_mode & !sys::FSOM_CREATE_ALWAYS
},
)
}
pub fn open(self, path: impl AsRef<Path>) -> Result<File> {
let path: &Path = path.as_ref();
// It's possible to produce a nonsensical `open_mode` using the above
// operations, so we have some logic here to drop any extraneous
// information. The possible open modes form a partial order (for
// example, `create_new` is more specialized than `truncate`) so we
// search for the first "on" bit in this sequence, and use that as the
// open mode.
let canonicalized_open_mode = if self.open_mode.has_flag(sys::FSOM_CREATE_NEW) {
sys::FSOM_CREATE_NEW
} else if self.open_mode.has_flag(sys::FSOM_CREATE_ALWAYS) {
sys::FSOM_CREATE_ALWAYS
} else if self.open_mode.has_flag(sys::FSOM_OPEN_APPEND) {
sys::FSOM_OPEN_APPEND
} else if self.open_mode.has_flag(sys::FSOM_OPEN_ALWAYS) {
sys::FSOM_OPEN_ALWAYS
} else {
sys::FSOM_OPEN_EXISTING
};
let f = File::new();
if unsafe {
sys::storage_file_open(
f.as_ptr(),
path.as_c_str().as_ptr().cast(),
self.access_mode,
canonicalized_open_mode,
)
} {
Ok(f)
} else {
// Per docs, "you need to close the file even if the open operation
// failed," but this is handled by `Drop`.
Err(Error::from_sys(f.get_raw_error()).unwrap())
}
}
}
/// Basic, unbuffered file handle
#[allow(dead_code)]
pub struct File {
raw: NonNull<sys::File>,
storage: Storage,
}
impl File {
pub(crate) fn new() -> Self {
let storage = Storage::open();
Self {
// SAFETY: Alloc always returns a valid non-null pointer or `furi_panic`s.
raw: unsafe { NonNull::new_unchecked(sys::storage_file_alloc(storage.as_ptr())) },
storage,
}
}
/// Attempts to open a file in read-only mode.
///
/// This function will return an error if path does not already exist.
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
OpenOptions::new().read(true).open_existing(true).open(path)
}
/// Opens a file in write-only mode.
///
/// This function will create a file if it does not exist, and will truncate it if it does.
pub fn create(path: impl AsRef<Path>) -> Result<Self> {
OpenOptions::new()
.write(true)
.create_always(true)
.open(path)
}
/// Attempts to create a new file in read-write mode.
///
/// This function will return an error if path does not already exist.
pub fn create_new(path: impl AsRef<Path>) -> Result<Self> {
OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(path)
}
/// Obtain raw Furi file handle.
///
/// This pointer must not be `free`d or otherwise invalidated.
/// It must not be referenced after `File` as been dropped.
pub fn as_ptr(&self) -> *mut sys::File {
self.raw.as_ptr()
}
/// Get last error.
fn get_raw_error(&self) -> sys::FS_Error {
// SAFETY: Pointer is always non-null and valid `sys::File`
unsafe { sys::storage_file_get_error(self.as_ptr()) }
}
}
impl Drop for File {
fn drop(&mut self) {
unsafe {
// `storage_file_close` calls `storage_file_sync`
// internally, so it's not necesssary to call it here.
sys::storage_file_close(self.as_ptr());
}
}
}
impl Read for File {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let bytes_read = unsafe {
sys::storage_file_read(self.as_ptr(), buf.as_mut_ptr() as *mut c_void, buf.len())
};
match Error::from_sys(self.get_raw_error()) {
Some(err) => Err(err),
None => Ok(bytes_read),
}
}
fn read_to_string(&mut self, string: &mut FuriString) -> Result<usize> {
let file_len = self.stream_len()?;
string.reserve(file_len);
default_read_to_string(self, string)
}
}
impl Seek for File {
fn seek(&mut self, pos: SeekFrom) -> Result<usize> {
let (from_start, offset) = match pos {
SeekFrom::Start(n) => (true, n.try_into().map_err(|_| Error::InvalidParameter)?),
SeekFrom::Current(n) => (false, n.try_into().map_err(|_| Error::InvalidParameter)?),
SeekFrom::End(n) => {
// TODO: Per str4d, "for SeekFrom::End we will need to measure
// the length of the file, and then use from_start = true and
// offset = file_length - n."
//
// How can we perform this subtraction safely?
let file_length: i64 = self.stream_len()?.try_into().unwrap();
(
true,
(file_length - n)
.try_into()
.map_err(|_| Error::InvalidParameter)?,
)
}
};
unsafe {
if sys::storage_file_seek(self.as_ptr(), offset, from_start) {
Ok(sys::storage_file_tell(self.as_ptr())
.try_into()
.map_err(|_| Error::InvalidParameter)?)
} else {
Err(Error::from_sys(self.get_raw_error()).unwrap())
}
}
}
fn rewind(&mut self) -> Result<()> {
self.seek(SeekFrom::Start(0)).map(|_| {})
}
fn stream_len(&mut self) -> Result<usize> {
Ok(unsafe {
sys::storage_file_size(self.as_ptr())
.try_into()
.map_err(|_| Error::InvalidParameter)?
})
}
fn stream_position(&mut self) -> Result<usize> {
Ok(unsafe {
sys::storage_file_tell(self.as_ptr())
.try_into()
.map_err(|_| Error::InvalidParameter)?
})
}
}
impl Write for File {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let bytes_written = unsafe {
sys::storage_file_write(self.as_ptr(), buf.as_ptr() as *mut c_void, buf.len())
};
match Error::from_sys(self.get_raw_error()) {
Some(err) => Err(err),
None => Ok(bytes_written),
}
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
impl Default for File {
fn default() -> Self {
Self::new()
}
}
/// Reads the entire contents of a file into a string.
///
/// This is a convenience function for using `File::open` and `read_to_string`
/// with fewer imports and without an intermediate variable.
pub fn read_to_string(path: impl AsRef<Path>) -> Result<FuriString> {
let mut string = FuriString::new();
File::open(path)?.read_to_string(&mut string)?;
Ok(string)
}