Skip to main content

fx_torrent/
file.rs

1use crate::{overlapping_range, FileAttributeFlags, PieceIndex, PiecePriority, TorrentFileInfo};
2use log::warn;
3use std::hash::Hash;
4use std::ops::Range;
5use std::path::PathBuf;
6
7/// The unique index of the file within the torrent.
8pub type FileIndex = usize;
9
10/// Alias name for the piece priority of a file.
11pub type FilePriority = PiecePriority;
12
13/// The metadata information about a single file within a torrent.
14///
15/// ## Ranges
16///
17/// A torrent file has two distinct byte ranges:
18///
19/// 1. **Torrent range** — The range of bytes occupied by this file *within the torrent as a whole*.
20/// 2. **I/O range** — The range of bytes occupied by this file *on the storage device*.
21///
22/// Use [`File::torrent_range`] to get the byte range within the torrent.
23/// Use [`File::io_range`] to get the byte range on the storage device.
24#[derive(Debug, Clone)]
25pub struct File {
26    /// The index of the file within the torrent.
27    pub index: FileIndex,
28    /// The path of the file within the torrent.
29    pub torrent_path: PathBuf,
30    /// The amount of bytes in the torrent before this file.
31    pub torrent_offset: usize,
32    /// The original metadata info of the file from the torrent.
33    pub info: TorrentFileInfo,
34    /// The priority of the file.
35    ///
36    /// This may differ from the underlying piece priorities.
37    /// When the priority is [`FilePriority::None`], the file's bytes will not be written to storage,
38    /// even if a piece containing them has a priority and is being downloaded.
39    pub priority: FilePriority,
40    /// The range of torrent pieces that contain this file's data.
41    pub pieces: Range<PieceIndex>,
42}
43
44impl File {
45    /// Get the filename of the file.
46    pub fn filename(&self) -> &str {
47        Self::filename_from_path(&self.torrent_path).unwrap_or_else(|| {
48            self.info
49                .path_segments()
50                .last()
51                .map(|e| e.as_str())
52                .unwrap_or("")
53        })
54    }
55
56    /// Get the total amount of bytes in the torrent file.
57    pub fn len(&self) -> usize {
58        self.info.length as usize
59    }
60
61    /// Check if the file contains some bytes from the given torrent byte range.
62    ///
63    /// # Returns
64    ///
65    /// It returns `true` when at least 1 byte overlaps with the given range, else `false`.
66    pub fn contains(&self, range: &Range<usize>) -> bool {
67        let file_range = self.torrent_range();
68        overlapping_range(file_range, range).is_some()
69    }
70
71    /// Get the byte range of the file within the io storage device.
72    ///
73    /// # Returns
74    ///
75    /// It returns a `Range<usize>` representing the start and end byte positions of the file
76    /// within the storage device.
77    pub fn io_range(&self) -> Range<usize> {
78        0..self.len()
79    }
80
81    /// Get the byte range of the file within the torrent.
82    ///
83    /// # Returns
84    ///
85    /// It returns a `Range<usize>` indicating the file's position in bytes within the torrent,
86    /// starting from its offset and extending to its length.
87    pub fn torrent_range(&self) -> Range<usize> {
88        self.torrent_offset..(self.torrent_offset + self.len())
89    }
90
91    /// Get the portion of the given torrent byte range that corresponds to the file's storage range.
92    ///
93    /// # Arguments
94    ///
95    /// * `torrent_bytes`: The byte range within the torrent.
96    ///
97    /// # Returns
98    ///
99    /// It returns an `Option<Range<usize>>` containing the portion of the given range that overlaps with the file's
100    /// storage range. If there is no overlap, `None` is returned.
101    pub fn io_applicable_byte_range(&self, torrent_bytes: &Range<usize>) -> Option<Range<usize>> {
102        overlapping_range(self.torrent_range(), &torrent_bytes).map(|e| {
103            let start_offset = e.start.saturating_sub(self.torrent_offset);
104            start_offset..e.end - self.torrent_offset
105        })
106    }
107
108    /// Get the portion of the given torrent byte range that overlaps with the file's range in the torrent.
109    ///
110    /// # Arguments
111    ///
112    /// * `torrent_bytes`: The byte range within the torrent.
113    ///
114    /// # Returns
115    ///
116    /// It returns an `Option<Range<usize>>` containing the portion of `torrent_bytes` that overlaps with the file's
117    /// range in the torrent. If there is no overlap, `None` is returned.
118    pub fn torrent_applicable_byte_range(
119        &self,
120        torrent_bytes: &Range<usize>,
121    ) -> Option<Range<usize>> {
122        overlapping_range(self.torrent_range(), torrent_bytes)
123    }
124
125    /// Get the byte slice of the given torrent bytes that are applicable to this file.
126    ///
127    /// # Arguments
128    ///
129    /// * `torrent_bytes`: The range of the bytes within the torrent.
130    /// * `bytes`: The data bytes of the torrent corresponding to the given `torrent_bytes`.
131    ///
132    /// # Returns
133    ///
134    /// It returns the slice of bytes that are relevant to this file.
135    /// If there is no overlap, `None` is returned.
136    pub fn torrent_applicable_bytes<'a>(
137        &self,
138        torrent_bytes: &Range<usize>,
139        bytes: &'a [u8],
140    ) -> Option<&'a [u8]> {
141        if torrent_bytes.len() != bytes.len() {
142            warn!("Torrent file \"{:?}\" is unable to calculate applicable bytes, invalid range provided", self.torrent_path);
143            return None;
144        }
145
146        if let Some(overlapping_range) = self.torrent_applicable_byte_range(torrent_bytes) {
147            let start = overlapping_range.start.saturating_sub(torrent_bytes.start);
148            let end = overlapping_range.end.saturating_sub(torrent_bytes.start);
149            return Some(&bytes[start..end]);
150        }
151
152        None
153    }
154
155    /// Get the file attributes of the torrent file.
156    pub fn attributes(&self) -> FileAttributeFlags {
157        self.info.attr.unwrap_or(FileAttributeFlags::default())
158    }
159
160    fn filename_from_path(path: &PathBuf) -> Option<&str> {
161        if let Some(filename) = path.file_name() {
162            filename.to_str()
163        } else {
164            None
165        }
166    }
167}
168
169impl PartialEq<Self> for File {
170    fn eq(&self, other: &Self) -> bool {
171        self.torrent_path == other.torrent_path
172            && self.torrent_offset == other.torrent_offset
173            && self.len() == other.len()
174    }
175}
176
177impl Eq for File {}
178
179impl Hash for File {
180    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
181        self.torrent_path.hash(state);
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::{InfoHash, Piece};
189
190    #[test]
191    fn test_contains() {
192        let piece = Piece::new(InfoHash::default(), 0, 0, 64);
193        let file = new_file(0, 128);
194        let result = file.contains(&piece.torrent_range());
195        assert_eq!(true, result);
196
197        let piece = Piece::new(InfoHash::default(), 0, 0, 128);
198        let file = new_file(100, 64);
199        let result = file.contains(&piece.torrent_range());
200        assert_eq!(true, result);
201
202        let piece = Piece::new(InfoHash::default(), 0, 1024, 128);
203        let file = new_file(512, 128);
204        let result = file.contains(&piece.torrent_range());
205        assert_eq!(false, result);
206    }
207
208    #[test]
209    fn test_file_io_range() {
210        let file = new_file(64, 128);
211        let expected_result = 0..128;
212
213        let result = file.io_range();
214
215        assert_eq!(expected_result, result);
216    }
217
218    #[test]
219    fn test_file_torrent_range() {
220        let file = new_file(64, 128);
221        let expected_result = 64..192;
222
223        let result = file.torrent_range();
224
225        assert_eq!(expected_result, result);
226    }
227
228    #[test]
229    fn test_file_io_applicable_byte_range() {
230        let file = new_file(0, 128);
231        let result = file.io_applicable_byte_range(&(0..64));
232        assert_eq!(Some(0..64), result);
233
234        let file = new_file(0, 128);
235        let result = file.io_applicable_byte_range(&(64..512));
236        assert_eq!(Some(64..128), result);
237
238        let file = new_file(496, 128);
239        let result = file.io_applicable_byte_range(&(64..512));
240        assert_eq!(Some(0..16), result);
241
242        let file = new_file(64, 128);
243        let result = file.io_applicable_byte_range(&(128..512));
244        assert_eq!(Some(64..128), result);
245
246        let file = new_file(128, 64);
247        let result = file.io_applicable_byte_range(&(0..192));
248        assert_eq!(Some(0..64), result);
249    }
250
251    #[test]
252    fn test_file_torrent_applicable_byte_range() {
253        let file = new_file(0, 128);
254        let result = file.torrent_applicable_byte_range(&(0..64));
255        assert_eq!(Some(0..64), result);
256
257        let file = new_file(0, 128);
258        let result = file.torrent_applicable_byte_range(&(64..512));
259        assert_eq!(Some(64..128), result);
260
261        let file = new_file(496, 128);
262        let result = file.torrent_applicable_byte_range(&(64..512));
263        assert_eq!(Some(496..512), result);
264
265        let file = new_file(64, 64);
266        let result = file.torrent_applicable_byte_range(&(64..512));
267        assert_eq!(Some(64..128), result);
268
269        let file = new_file(1028, 512);
270        let result = file.torrent_applicable_byte_range(&(0..1028));
271        assert_eq!(None, result);
272    }
273
274    #[test]
275    fn test_file_torrent_applicable_bytes() {
276        let file = new_file(0, 128);
277        let data = (0..64).map(|i| i as u8).collect::<Vec<u8>>();
278        let result = file.torrent_applicable_bytes(&(0..64), data.as_slice());
279        assert_eq!(Some(data.as_slice()), result);
280
281        let file = new_file(0, 128);
282        let data = (0..448).map(|i| i as u8).collect::<Vec<u8>>();
283        let result = file.torrent_applicable_bytes(&(64..512), data.as_slice());
284        assert_eq!(Some(&data[0..64]), result);
285    }
286
287    mod filename {
288        use super::*;
289
290        #[test]
291        fn test_torrent_path() {
292            let torrent_path = PathBuf::from("MyTorrentDirectory/MyTorrentFile.mp4");
293            let file = File {
294                index: 0,
295                torrent_path,
296                torrent_offset: 0,
297                info: TorrentFileInfo {
298                    length: 1024,
299                    path: None,
300                    path_utf8: None,
301                    md5sum: None,
302                    attr: None,
303                    symlink_path: None,
304                    sha1: None,
305                },
306                priority: FilePriority::default(),
307                pieces: 0..100,
308            };
309
310            let result = file.filename();
311
312            assert_eq!("MyTorrentFile.mp4", result);
313        }
314
315        #[test]
316        fn test_info_path() {
317            let filename = "MyTorrentFile.mkv";
318            let file = File {
319                index: 0,
320                torrent_path: PathBuf::new(),
321                torrent_offset: 0,
322                info: TorrentFileInfo {
323                    length: 1024,
324                    path: Some(vec!["MyTorrentDirectory".to_string(), filename.to_string()]),
325                    path_utf8: None,
326                    md5sum: None,
327                    attr: None,
328                    symlink_path: None,
329                    sha1: None,
330                },
331                priority: FilePriority::default(),
332                pieces: 0..100,
333            };
334
335            let result = file.filename();
336
337            assert_eq!(filename, result);
338        }
339    }
340
341    fn new_file(offset: usize, length: usize) -> File {
342        File {
343            index: 0,
344            torrent_path: Default::default(),
345            torrent_offset: offset,
346            info: TorrentFileInfo {
347                length: length as u64,
348                path: None,
349                path_utf8: None,
350                md5sum: None,
351                attr: None,
352                symlink_path: None,
353                sha1: None,
354            },
355            priority: FilePriority::default(),
356            pieces: 0..100,
357        }
358    }
359}