azul_layout/desktop/
file.rs1use alloc::sync::Arc;
2use core::fmt;
3use std::{
4 fs,
5 io::{Read, Write},
6 sync::Mutex,
7};
8
9use azul_css::{impl_option, impl_option_inner, AzString, U8Vec};
10
11#[repr(C)]
12pub struct File {
13 pub ptr: Box<Arc<Mutex<fs::File>>>,
14 pub path: AzString,
15 pub run_destructor: bool,
16}
17
18impl Clone for File {
19 fn clone(&self) -> Self {
20 Self {
21 ptr: self.ptr.clone(),
22 path: self.path.clone(),
23 run_destructor: true,
24 }
25 }
26}
27
28impl Drop for File {
29 fn drop(&mut self) {
30 self.run_destructor = false;
31 }
32}
33
34impl fmt::Debug for File {
35 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36 write!(f, "{}", self.path.as_str())
37 }
38}
39
40impl fmt::Display for File {
41 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42 write!(f, "{}", self.path.as_str())
43 }
44}
45
46impl PartialEq for File {
47 fn eq(&self, other: &Self) -> bool {
48 self.path.as_str().eq(other.path.as_str())
49 }
50}
51
52impl Eq for File {}
53
54impl PartialOrd for File {
55 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
56 self.path.as_str().partial_cmp(other.path.as_str())
57 }
58}
59
60impl_option!(File, OptionFile, copy = false, [Clone, Debug]);
61
62impl File {
63 fn new(f: fs::File, path: AzString) -> Self {
64 Self {
65 ptr: Box::new(Arc::new(Mutex::new(f))),
66 path,
67 run_destructor: true,
68 }
69 }
70 pub fn open(path: &str) -> Option<Self> {
71 Some(Self::new(
72 fs::File::open(path).ok()?,
73 path.to_string().into(),
74 ))
75 }
76 pub fn create(path: &str) -> Option<Self> {
77 Some(Self::new(
78 fs::File::create(path).ok()?,
79 path.to_string().into(),
80 ))
81 }
82 pub fn read_to_string(&mut self) -> Option<AzString> {
83 let file_string = std::fs::read_to_string(self.path.as_str()).ok()?;
84 Some(file_string.into())
85 }
86 pub fn read_to_bytes(&mut self) -> Option<U8Vec> {
87 let file_bytes = std::fs::read(self.path.as_str()).ok()?;
88 Some(file_bytes.into())
89 }
90 pub fn write_string(&mut self, string: &str) -> Option<()> {
91 self.write_bytes(string.as_bytes())
92 }
93 pub fn write_bytes(&mut self, bytes: &[u8]) -> Option<()> {
94 let mut lock = self.ptr.lock().ok()?;
95 lock.write_all(bytes).ok()?;
96 lock.sync_all().ok()?;
97 Some(())
98 }
99 pub fn close(self) {}
100}