file_sequence.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use futures::{
  19. task::{Context, Poll},
  20. AsyncRead, AsyncSeek, AsyncWrite,
  21. };
  22. use smol::{
  23. fs::{File, OpenOptions},
  24. io::{self, AsyncReadExt, AsyncSeekExt, AsyncWriteExt, SeekFrom},
  25. };
  26. use std::{path::PathBuf, pin::Pin};
  27. /// `FileSequence` is an object that implements `AsyncRead`, `AsyncSeek`, and
  28. /// `AsyncWrite` for an ordered list of (file path, file size).
  29. ///
  30. /// You can use it to read and write from/to a list a file, without having to
  31. /// manage individual file operations explicitly.
  32. ///
  33. /// This allows seamless handling of multiple files as if they were a single
  34. /// continuous file. It automatically opens the next file in the list when the
  35. /// current file is exhausted.
  36. #[derive(Debug)]
  37. pub struct FileSequence {
  38. /// List of (file path, file size). File sizes are not the sizes of the
  39. /// files as they currently are on the file system, but the sizes we want
  40. files: Vec<(PathBuf, u64)>,
  41. /// Currently opened file
  42. current_file: Option<File>,
  43. /// Index of the currently opened file in the `files` vector
  44. current_file_index: Option<usize>,
  45. /// Set to `true` to automatically set the length of the file on the
  46. /// filesystem to it's size as defined in the `files` vector, after a write
  47. auto_set_len: bool,
  48. }
  49. impl FileSequence {
  50. pub fn new(files: &[(PathBuf, u64)], auto_set_len: bool) -> Self {
  51. Self { files: files.to_vec(), current_file: None, current_file_index: None, auto_set_len }
  52. }
  53. /// Update a single file size.
  54. pub fn set_file_size(&mut self, file_index: usize, file_size: u64) {
  55. self.files[file_index].1 = file_size;
  56. }
  57. /// Return `current_file`.
  58. pub fn get_current_file(&self) -> &Option<File> {
  59. &self.current_file
  60. }
  61. /// Return `files`.
  62. pub fn get_files(&self) -> &Vec<(PathBuf, u64)> {
  63. &self.files
  64. }
  65. /// Open the file at (`current_file_index` + 1).
  66. /// If no file is currently open (`current_file_index` is None), it opens
  67. /// the first file.
  68. async fn open_next_file(&mut self) -> io::Result<()> {
  69. self.current_file_index = match self.current_file_index {
  70. Some(i) => Some(i + 1),
  71. None => Some(0),
  72. };
  73. if self.current_file_index.unwrap() >= self.files.len() {
  74. return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "No more files to open"))
  75. }
  76. let file = OpenOptions::new()
  77. .read(true)
  78. .write(true)
  79. .create(true)
  80. .open(self.files[self.current_file_index.unwrap()].0.clone())
  81. .await?;
  82. self.current_file = Some(file);
  83. Ok(())
  84. }
  85. /// Open the file at `file_index`.
  86. async fn open_file(&mut self, file_index: usize) -> io::Result<()> {
  87. let file = OpenOptions::new()
  88. .read(true)
  89. .write(true)
  90. .create(true)
  91. .open(self.files[file_index].0.clone())
  92. .await?;
  93. self.current_file = Some(file);
  94. self.current_file_index = Some(file_index);
  95. Ok(())
  96. }
  97. }
  98. impl AsyncRead for FileSequence {
  99. fn poll_read(
  100. self: Pin<&mut Self>,
  101. _: &mut Context<'_>,
  102. buf: &mut [u8],
  103. ) -> Poll<io::Result<usize>> {
  104. let this = self.get_mut();
  105. let mut total_read = 0;
  106. while total_read < buf.len() {
  107. if this.current_file.is_none() {
  108. // Stop if there are no more files to read
  109. if let Some(file_index) = this.current_file_index {
  110. if file_index >= this.files.len() - 1 {
  111. return Poll::Ready(Ok(total_read));
  112. }
  113. }
  114. // Open the next file
  115. if let Err(e) = smol::block_on(this.open_next_file()) {
  116. return Poll::Ready(Err(e));
  117. }
  118. }
  119. // Read from the current file
  120. let file = this.current_file.as_mut().unwrap();
  121. match smol::block_on(file.read(&mut buf[total_read..])) {
  122. Ok(bytes_read) => {
  123. if bytes_read == 0 {
  124. this.current_file = None; // Move to the next file
  125. } else {
  126. total_read += bytes_read;
  127. }
  128. }
  129. Err(e) => return Poll::Ready(Err(e)),
  130. }
  131. }
  132. Poll::Ready(Ok(total_read))
  133. }
  134. }
  135. impl AsyncSeek for FileSequence {
  136. fn poll_seek(
  137. self: Pin<&mut Self>,
  138. _: &mut Context<'_>,
  139. pos: SeekFrom,
  140. ) -> Poll<io::Result<u64>> {
  141. let this = self.get_mut();
  142. let abs_pos = match pos {
  143. SeekFrom::Start(offset) => offset,
  144. _ => todo!(), // TODO
  145. };
  146. // Determine which file to seek in
  147. let mut file_index = 0;
  148. let mut bytes_offset = 0;
  149. while file_index < this.files.len() {
  150. if bytes_offset + this.files[file_index].1 >= abs_pos {
  151. break;
  152. }
  153. bytes_offset += this.files[file_index].1;
  154. file_index += 1;
  155. }
  156. if file_index >= this.files.len() {
  157. return Poll::Ready(Err(io::Error::new(
  158. io::ErrorKind::InvalidInput,
  159. "Seek position out of bounds",
  160. )))
  161. }
  162. // Open the file
  163. if this.current_file.is_none() ||
  164. this.current_file_index.is_some() && this.current_file_index.unwrap() != file_index
  165. {
  166. if let Err(e) = smol::block_on(this.open_file(file_index)) {
  167. return Poll::Ready(Err(e));
  168. }
  169. }
  170. let file = this.current_file.as_mut().unwrap();
  171. let file_pos = abs_pos - bytes_offset;
  172. // Seek in the current file
  173. match smol::block_on(file.seek(SeekFrom::Start(file_pos))) {
  174. Ok(new_position) => Poll::Ready(Ok(new_position)),
  175. Err(e) => Poll::Ready(Err(e)),
  176. }
  177. }
  178. }
  179. impl AsyncWrite for FileSequence {
  180. fn poll_write(
  181. self: Pin<&mut Self>,
  182. _: &mut Context<'_>,
  183. buf: &[u8],
  184. ) -> Poll<io::Result<usize>> {
  185. let this = self.get_mut();
  186. let mut total_bytes_written = 0;
  187. let mut remaining_buf = buf;
  188. let auto_set_len = this.auto_set_len;
  189. let finalize_current_file = |file: &mut File, max_size: u64| {
  190. if auto_set_len {
  191. smol::block_on(file.set_len(max_size))?;
  192. }
  193. smol::block_on(file.flush())?;
  194. Ok(())
  195. };
  196. loop {
  197. // Ensure the current file is open
  198. if this.current_file.is_none() {
  199. if let Some(file_index) = this.current_file_index {
  200. if file_index >= this.files.len() - 1 {
  201. break; // No more files
  202. }
  203. }
  204. if let Err(e) = smol::block_on(this.open_next_file()) {
  205. return Poll::Ready(Err(e));
  206. }
  207. }
  208. let file = this.current_file.as_mut().unwrap();
  209. let max_size = this.files[this.current_file_index.unwrap()].1;
  210. // Check how much space is left in the current file
  211. let current_position = smol::block_on(file.seek(io::SeekFrom::Current(0)))?;
  212. let space_left = max_size - current_position;
  213. let bytes_to_write = remaining_buf.len().min(space_left as usize);
  214. if bytes_to_write == 0 {
  215. // Continue to the next iteration to check the new file
  216. if let Err(e) = finalize_current_file(file, max_size) {
  217. return Poll::Ready(Err(e));
  218. }
  219. this.current_file = None;
  220. continue;
  221. }
  222. // Write to the current file
  223. match smol::block_on(file.write(&remaining_buf[..bytes_to_write])) {
  224. Ok(bytes_written) => {
  225. total_bytes_written += bytes_written;
  226. remaining_buf = &remaining_buf[bytes_written..]; // Update the remaining buffer
  227. if remaining_buf.is_empty() {
  228. if let Err(e) = finalize_current_file(file, max_size) {
  229. return Poll::Ready(Err(e));
  230. }
  231. break; // No more data to write
  232. }
  233. // We wrote to the end of this file, use new file on next iteration
  234. if bytes_written == bytes_to_write {
  235. if let Err(e) = finalize_current_file(file, max_size) {
  236. return Poll::Ready(Err(e));
  237. }
  238. this.current_file = None;
  239. }
  240. }
  241. Err(e) => return Poll::Ready(Err(e)), // Return error if write fails
  242. }
  243. }
  244. Poll::Ready(Ok(total_bytes_written))
  245. }
  246. fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
  247. Poll::Ready(Ok(())) // TODO
  248. }
  249. fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
  250. let this = self.get_mut();
  251. if let Some(file) = this.current_file.take() {
  252. match smol::block_on(file.sync_all()) {
  253. Ok(()) => Poll::Ready(Ok(())),
  254. Err(e) => Poll::Ready(Err(e)),
  255. }
  256. } else {
  257. Poll::Ready(Ok(())) // No file to close
  258. }
  259. }
  260. }