file_sequence.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::{collections::HashSet, 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. ///
  37. /// It's also made so that files in `files` that do not exist on the filesystem
  38. /// will get skipped, without returning an Error. All files you want to read,
  39. /// write, and seek to should be created before using the FileSequence.
  40. #[derive(Debug)]
  41. pub struct FileSequence {
  42. /// List of (file path, file size). File sizes are not the sizes of the
  43. /// files as they currently are on the file system, but the sizes we want
  44. files: Vec<(PathBuf, u64)>,
  45. /// Currently opened file
  46. current_file: Option<File>,
  47. /// Index of the currently opened file in the `files` vector
  48. current_file_index: Option<usize>,
  49. position: u64,
  50. /// Set to `true` to automatically set the length of the file on the
  51. /// filesystem to it's size as defined in the `files` vector, after a write
  52. auto_set_len: bool,
  53. }
  54. impl FileSequence {
  55. pub fn new(files: &[(PathBuf, u64)], auto_set_len: bool) -> Self {
  56. Self {
  57. files: files.to_vec(),
  58. current_file: None,
  59. current_file_index: None,
  60. position: 0,
  61. auto_set_len,
  62. }
  63. }
  64. /// Update a single file size.
  65. pub fn set_file_size(&mut self, file_index: usize, file_size: u64) {
  66. self.files[file_index].1 = file_size;
  67. }
  68. /// Return `current_file`.
  69. pub fn get_current_file(&self) -> &Option<File> {
  70. &self.current_file
  71. }
  72. /// Return `files`.
  73. pub fn get_files(&self) -> &Vec<(PathBuf, u64)> {
  74. &self.files
  75. }
  76. /// Return the combined file size of all files.
  77. pub fn len(&self) -> u64 {
  78. self.files.iter().map(|(_, size)| size).sum()
  79. }
  80. /// Return `true` if the `FileSequence` contains no file.
  81. pub fn is_empty(&self) -> bool {
  82. self.files.is_empty()
  83. }
  84. /// Return the combined file size of all files.
  85. pub fn subset_len(&self, files: HashSet<PathBuf>) -> u64 {
  86. self.files.iter().filter(|(path, _)| files.contains(path)).map(|(_, size)| size).sum()
  87. }
  88. /// Compute the starting position of the file (in bytes) by suming up
  89. /// the size of the previous files.
  90. pub fn get_file_position(&self, file_index: usize) -> u64 {
  91. let mut pos = 0;
  92. for i in 0..file_index {
  93. pos += self.files[i].1;
  94. }
  95. pos
  96. }
  97. /// Open the file at (`current_file_index` + 1).
  98. /// If no file is currently open (`current_file_index` is None), it opens
  99. /// the first file.
  100. async fn open_next_file(&mut self) -> io::Result<()> {
  101. self.current_file = None;
  102. self.current_file_index = match self.current_file_index {
  103. Some(i) => Some(i + 1),
  104. None => Some(0),
  105. };
  106. if self.current_file_index.unwrap() >= self.files.len() {
  107. return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "No more files to open"))
  108. }
  109. let file = OpenOptions::new()
  110. .read(true)
  111. .write(true)
  112. .create(false)
  113. .open(self.files[self.current_file_index.unwrap()].0.clone())
  114. .await?;
  115. self.current_file = Some(file);
  116. Ok(())
  117. }
  118. /// Open the file at `file_index`.
  119. async fn open_file(&mut self, file_index: usize) -> io::Result<()> {
  120. self.current_file = None;
  121. self.current_file_index = Some(file_index);
  122. let file = OpenOptions::new()
  123. .read(true)
  124. .write(true)
  125. .create(false)
  126. .open(self.files[file_index].0.clone())
  127. .await?;
  128. self.current_file = Some(file);
  129. Ok(())
  130. }
  131. }
  132. impl AsyncRead for FileSequence {
  133. fn poll_read(
  134. self: Pin<&mut Self>,
  135. _: &mut Context<'_>,
  136. buf: &mut [u8],
  137. ) -> Poll<io::Result<usize>> {
  138. let this = self.get_mut();
  139. let mut total_read = 0;
  140. while total_read < buf.len() {
  141. if this.current_file.is_none() {
  142. if let Some(file_index) = this.current_file_index {
  143. // Stop if there are no more files to read
  144. if file_index >= this.files.len() - 1 {
  145. return Poll::Ready(Ok(total_read));
  146. }
  147. let start_pos = this.get_file_position(file_index);
  148. let file_size = this.files[file_index].1 as usize;
  149. let file_pos = this.position - start_pos;
  150. let space_left = file_size - file_pos as usize;
  151. let skip_bytes = (buf.len() - total_read).min(space_left);
  152. this.position += skip_bytes as u64;
  153. total_read += skip_bytes;
  154. }
  155. // Open the next file
  156. match smol::block_on(this.open_next_file()) {
  157. Ok(_) => {}
  158. Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
  159. return Poll::Ready(Ok(total_read));
  160. }
  161. Err(e) if e.kind() == io::ErrorKind::NotFound => {
  162. this.current_file = None;
  163. continue; // Skip to next file
  164. }
  165. Err(e) => return Poll::Ready(Err(e)),
  166. }
  167. }
  168. // Read from the current file
  169. let file = this.current_file.as_mut().unwrap();
  170. match smol::block_on(file.read(&mut buf[total_read..])) {
  171. Ok(bytes_read) => {
  172. if bytes_read == 0 {
  173. this.current_file = None; // Move to the next file
  174. } else {
  175. total_read += bytes_read;
  176. this.position += bytes_read as u64;
  177. }
  178. }
  179. Err(e) => return Poll::Ready(Err(e)),
  180. }
  181. }
  182. Poll::Ready(Ok(total_read))
  183. }
  184. }
  185. impl AsyncSeek for FileSequence {
  186. fn poll_seek(
  187. self: Pin<&mut Self>,
  188. _: &mut Context<'_>,
  189. pos: SeekFrom,
  190. ) -> Poll<io::Result<u64>> {
  191. let this = self.get_mut();
  192. let abs_pos = match pos {
  193. SeekFrom::Start(offset) => offset,
  194. _ => todo!(), // TODO
  195. };
  196. // Determine which file to seek in
  197. let mut file_index = 0;
  198. let mut bytes_offset = 0;
  199. while file_index < this.files.len() {
  200. if bytes_offset + this.files[file_index].1 >= abs_pos {
  201. break;
  202. }
  203. bytes_offset += this.files[file_index].1;
  204. file_index += 1;
  205. }
  206. if file_index >= this.files.len() {
  207. return Poll::Ready(Err(io::Error::new(
  208. io::ErrorKind::InvalidInput,
  209. "Seek position out of bounds",
  210. )))
  211. }
  212. this.position = abs_pos; // Update FileSequence position
  213. // Open the file
  214. if this.current_file.is_none() ||
  215. this.current_file_index.is_some() && this.current_file_index.unwrap() != file_index
  216. {
  217. match smol::block_on(this.open_file(file_index)) {
  218. Ok(_) => {}
  219. Err(e) if e.kind() == io::ErrorKind::NotFound => {
  220. // If the file does not exist, return without actually seeking it
  221. return Poll::Ready(Ok(this.position));
  222. }
  223. Err(e) => return Poll::Ready(Err(e)),
  224. };
  225. }
  226. let file = this.current_file.as_mut().unwrap();
  227. let file_pos = abs_pos - bytes_offset;
  228. // Seek in the current file
  229. match smol::block_on(file.seek(SeekFrom::Start(file_pos))) {
  230. Ok(_) => Poll::Ready(Ok(this.position)),
  231. Err(e) => Poll::Ready(Err(e)),
  232. }
  233. }
  234. }
  235. impl AsyncWrite for FileSequence {
  236. fn poll_write(
  237. self: Pin<&mut Self>,
  238. _: &mut Context<'_>,
  239. buf: &[u8],
  240. ) -> Poll<io::Result<usize>> {
  241. let this = self.get_mut();
  242. let mut total_bytes_written = 0;
  243. let mut remaining_buf = buf;
  244. let auto_set_len = this.auto_set_len;
  245. let finalize_current_file = |file: &mut File, max_size: u64| {
  246. if auto_set_len {
  247. smol::block_on(file.set_len(max_size))?;
  248. }
  249. smol::block_on(file.flush())?;
  250. Ok(())
  251. };
  252. loop {
  253. // Ensure the current file is open
  254. if this.current_file.is_none() {
  255. if let Some(file_index) = this.current_file_index {
  256. if file_index >= this.files.len() - 1 {
  257. break; // No more files
  258. }
  259. if remaining_buf.is_empty() {
  260. break; // No more data to write
  261. }
  262. let start_pos = this.get_file_position(file_index);
  263. let file_size = this.files[file_index].1 as usize;
  264. let file_pos = this.position - start_pos;
  265. let space_left = file_size - file_pos as usize;
  266. let skip_bytes = remaining_buf.len().min(space_left);
  267. this.position += skip_bytes as u64;
  268. remaining_buf = &remaining_buf[skip_bytes..]; // Update the remaining buffer
  269. }
  270. // Switch to the next file
  271. match smol::block_on(this.open_next_file()) {
  272. Ok(_) => {}
  273. Err(e) if e.kind() == io::ErrorKind::NotFound => {
  274. this.current_file = None;
  275. continue; // Skip to next file
  276. }
  277. Err(e) => return Poll::Ready(Err(e)),
  278. }
  279. }
  280. let file = this.current_file.as_mut().unwrap();
  281. let max_size = this.files[this.current_file_index.unwrap()].1;
  282. // Check how much space is left in the current file
  283. let current_position = smol::block_on(file.seek(io::SeekFrom::Current(0)))?;
  284. let space_left = max_size - current_position;
  285. let bytes_to_write = remaining_buf.len().min(space_left as usize);
  286. if bytes_to_write == 0 {
  287. // Continue to the next iteration to check the new file
  288. if let Err(e) = finalize_current_file(file, max_size) {
  289. return Poll::Ready(Err(e));
  290. }
  291. this.current_file = None;
  292. continue;
  293. }
  294. // Write to the current file
  295. match smol::block_on(file.write(&remaining_buf[..bytes_to_write])) {
  296. Ok(bytes_written) => {
  297. total_bytes_written += bytes_written;
  298. this.position += bytes_written as u64;
  299. remaining_buf = &remaining_buf[bytes_written..]; // Update the remaining buffer
  300. if remaining_buf.is_empty() {
  301. if let Err(e) = finalize_current_file(file, max_size) {
  302. return Poll::Ready(Err(e));
  303. }
  304. break; // No more data to write
  305. }
  306. // We wrote to the end of this file, use new file on next iteration
  307. if bytes_written == bytes_to_write {
  308. if let Err(e) = finalize_current_file(file, max_size) {
  309. return Poll::Ready(Err(e));
  310. }
  311. this.current_file = None;
  312. }
  313. }
  314. Err(e) => return Poll::Ready(Err(e)), // Return error if write fails
  315. }
  316. }
  317. Poll::Ready(Ok(total_bytes_written))
  318. }
  319. fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
  320. Poll::Ready(Ok(())) // TODO
  321. }
  322. fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
  323. let this = self.get_mut();
  324. if let Some(file) = this.current_file.take() {
  325. match smol::block_on(file.sync_all()) {
  326. Ok(()) => Poll::Ready(Ok(())),
  327. Err(e) => Poll::Ready(Err(e)),
  328. }
  329. } else {
  330. Poll::Ready(Ok(())) // No file to close
  331. }
  332. }
  333. }