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