file_storage/op/file/read/
read_string.rs1use crate::Operation::Read;
2use crate::Reason::{FileContentNotUTF8, FileNotFound};
3use crate::{Error, FilePath};
4
5struct TruncateGuard<'a> {
7 vec: &'a mut Vec<u8>,
8 original_len: usize,
9 armed: bool,
10}
11
12impl<'a> TruncateGuard<'a> {
13 fn new(vec: &'a mut Vec<u8>) -> Self {
14 let original_len: usize = vec.len();
15 Self {
16 vec,
17 original_len,
18 armed: true,
19 }
20 }
21
22 fn disarm(&mut self) {
23 self.armed = false;
24 }
25}
26
27impl Drop for TruncateGuard<'_> {
28 fn drop(&mut self) {
29 if self.armed {
30 self.vec.truncate(self.original_len);
31 }
32 }
33}
34
35impl FilePath {
36 pub fn read_as_string(&self) -> Result<String, Error> {
43 if let Some(file_content) = self.read_as_string_if_exists()? {
44 Ok(file_content)
45 } else {
46 Err(Error::new(self.clone(), Read, FileNotFound))
47 }
48 }
49
50 pub fn read_as_string_if_exists(&self) -> Result<Option<String>, Error> {
55 if let Some(file_content) = self.read_as_vec_if_exists()? {
56 match String::from_utf8(file_content) {
57 Ok(file_content) => Ok(Some(file_content)),
58 Err(_) => Err(Error::new(self.clone(), Read, FileContentNotUTF8)),
59 }
60 } else {
61 Ok(None)
62 }
63 }
64
65 pub fn read_to_string(&self, target: &mut String) -> Result<usize, Error> {
70 if let Some(file_content_len) = self.read_to_string_if_exists(target)? {
71 Ok(file_content_len)
72 } else {
73 Err(Error::new(self.clone(), Read, FileNotFound))
74 }
75 }
76
77 pub fn read_to_string_if_exists(&self, target: &mut String) -> Result<Option<usize>, Error> {
82 let target: &mut Vec<u8> = unsafe { target.as_mut_vec() };
85 let mut guard: TruncateGuard = TruncateGuard::new(target);
86 let original_len: usize = guard.original_len;
87 match self.read_to_vec_if_exists(guard.vec) {
88 Ok(file_content_len) => {
89 if let Some(file_content_len) = file_content_len {
90 debug_assert_eq!(guard.vec.len(), original_len + file_content_len);
91 let slice: &[u8] = &guard.vec[original_len..];
92 match std::str::from_utf8(slice) {
93 Ok(_) => {
94 guard.disarm();
95 Ok(Some(file_content_len))
96 }
97 Err(_) => Err(Error::new(self.clone(), Read, FileContentNotUTF8)),
98 }
99 } else {
100 guard.disarm();
101 Ok(None)
102 }
103 }
104 Err(e) => Err(e),
105 }
106 }
107}