uni_app/native_fs.rs
1use std;
2use std::io::ErrorKind;
3use std::io::Read;
4use std::str;
5
6/// the root filesystem API
7pub struct FileSystem {}
8/// synchronous (native) / asynchronous (web) file API
9pub enum File {
10 Native(std::fs::File),
11}
12
13pub type IoError = std::io::Error;
14pub type IoErrorKind = std::io::ErrorKind;
15
16impl FileSystem {
17 /// open a file.
18 /// For a file to be accessible from both native and web build, it should be placed
19 /// in a www/ directory in your project's root directory, for example www/config.json.
20 /// You can then open this file with `FileSystem::open("config.json")`.
21 /// When running your native project, use `cd www && cargo run`.
22 /// When deploying on the web, the file should simply be in the same directory as index.html, as config.json.
23 /// Note that on wasm target, this works with any URL, you can do :
24 /// `FileSystem::open('https://raw.githubusercontent.com/unrust/uni-app/master/www/test.txt')`
25 /// To be able to load data from an URL in native mode, you have to enable the http feature.
26 pub fn open(s: &str) -> Result<File, IoError> {
27 if s.starts_with("http") {
28 Err(std::io::Error::new(
29 ErrorKind::Other,
30 format!(
31 "error : could not read {} : http feature not enabled in uni-app::FileSystem",
32 s
33 ),
34 ))
35 } else {
36 Ok(File::Native(std::fs::File::open(s)?))
37 }
38 }
39}
40
41impl File {
42 /// Once the file has been loaded (see [`File::is_ready`]), returns the file content as `Vec<u8>`
43 pub fn read_binary(&mut self) -> Result<Vec<u8>, IoError> {
44 let mut buf = Vec::new();
45 match self {
46 File::Native(f) => {
47 f.read_to_end(&mut buf)?;
48 }
49 }
50 Ok(buf)
51 }
52 /// Once the file has been loaded (see [`File::is_ready`]), returns the file content as a String
53 pub fn read_text(&mut self) -> Result<String, IoError> {
54 let mut data = String::new();
55 match self {
56 File::Native(f) => match f.read_to_string(&mut data) {
57 Ok(_) => Ok(data),
58 Err(e) => Err(std::io::Error::new(ErrorKind::Other, e)),
59 },
60 }
61 }
62 /// return true if the file has been loaded
63 /// On native target, files are loaded synchronously.
64 /// As soon as [`FileSystem::open`] returns, the file is ready.
65 /// [`File::read_binary`] and [`File::read_text`] can be called immediately.
66 /// On web target, files are loaded asynchronously.
67 /// You have to poll [`File::is_ready`] until it returns true.
68 /// Only then you can call [`File::read_binary`] or [`File::read_text`].
69 pub fn is_ready(&mut self) -> bool {
70 true
71 }
72}