use std::collections::HashMap;
use crate::segment::piece_storage::BitfieldMan;
use crate::segment::piece_storage::PieceStorage;
use super::TrackingEntry;
use super::peer_stat::PeerStat;
pub struct SegmentMan {
pub(crate) piece_storage: Option<Box<dyn PieceStorage + Send>>,
pub(crate) used_segment_entries: Vec<TrackingEntry>,
pub(crate) segment_written_length_memo: HashMap<usize, u64>,
pub(crate) peer_stats: Vec<PeerStat>,
pub(crate) fastest_peer_stats: Vec<PeerStat>,
pub(crate) ignore_bitfield: BitfieldMan,
pub(crate) piece_length: u64,
pub(crate) total_length: u64,
}
impl SegmentMan {
pub fn new(piece_length: u64, total_length: u64) -> Self {
let mut ignore_bitfield = BitfieldMan::new(piece_length, total_length);
ignore_bitfield.enable_filter();
for byte in ignore_bitfield.get_filter_bitfield_mut() {
*byte = 0xFF;
}
ignore_bitfield.clear_trailing_filter_bits();
SegmentMan {
piece_storage: None,
used_segment_entries: Vec::new(),
segment_written_length_memo: HashMap::new(),
peer_stats: Vec::new(),
fastest_peer_stats: Vec::new(),
ignore_bitfield,
piece_length,
total_length,
}
}
pub fn init(&mut self) {
self.used_segment_entries.clear();
self.segment_written_length_memo.clear();
self.peer_stats.clear();
self.fastest_peer_stats.clear();
}
pub fn total_length(&self) -> u64 {
match &self.piece_storage {
Some(ps) => ps.get_total_length(),
None => self.total_length,
}
}
pub fn download_finished(&self) -> bool {
match &self.piece_storage {
Some(ps) => ps.download_finished(),
None => false,
}
}
pub fn download_length(&self) -> u64 {
match &self.piece_storage {
Some(ps) => ps.get_completed_length(),
None => 0,
}
}
}
impl std::fmt::Debug for SegmentMan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SegmentMan")
.field("piece_length", &self.piece_length)
.field("total_length", &self.total_length)
.field("in_flight_count", &self.used_segment_entries.len())
.field("memo_count", &self.segment_written_length_memo.len())
.field("peer_stats_count", &self.peer_stats.len())
.field("all_ignored", &self.all_segments_ignored())
.finish()
}
}