file_sequence.rs 13 KB

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