use std::sync::atomic::{AtomicU64, Ordering};
use tracing::trace;
use super::bitfield::BlockBitfield;
use super::completion::{HashState, finalize_hash};
pub const DEFAULT_BLOCK_LENGTH: u32 = 16 * 1024;
static NEXT_PIECE_ID: AtomicU64 = AtomicU64::new(1);
pub struct Piece {
pub(super) identity: u64,
pub(super) completed: BlockBitfield,
pub(super) in_use: BlockBitfield,
pub(super) users: Vec<u64>,
pub(super) hash_type: Option<String>,
pub(super) hash_state: Option<HashState>,
pub(super) next_begin: u64,
pub(super) index: usize,
pub(super) length: u64,
pub(super) block_length: u32,
pub(super) used_by_segment: bool,
}
impl Piece {
pub fn new(index: usize, length: u64) -> Self {
Self::with_block_length(index, length, DEFAULT_BLOCK_LENGTH)
}
pub fn with_block_length(index: usize, length: u64, block_length: u32) -> Self {
let num_blocks = Self::compute_num_blocks(length, block_length);
Piece {
identity: NEXT_PIECE_ID.fetch_add(1, Ordering::Relaxed),
completed: BlockBitfield::new(num_blocks),
in_use: BlockBitfield::new(num_blocks),
users: Vec::new(),
hash_type: None,
hash_state: None,
next_begin: 0,
index,
length,
block_length,
used_by_segment: false,
}
}
#[inline]
fn compute_num_blocks(length: u64, block_length: u32) -> usize {
if length == 0 || block_length == 0 {
0
} else {
length.div_ceil(block_length as u64) as usize
}
}
fn last_block_length(&self) -> u32 {
if self.length == 0 || self.block_length == 0 {
return 0;
}
let remainder = self.length % self.block_length as u64;
if remainder == 0 {
self.block_length
} else {
remainder as u32
}
}
#[inline]
pub fn index(&self) -> usize {
self.index
}
pub(crate) fn identity(&self) -> u64 {
self.identity
}
#[inline]
pub fn set_index(&mut self, index: usize) {
self.index = index;
}
#[inline]
pub fn length(&self) -> u64 {
self.length
}
#[inline]
pub fn set_length(&mut self, length: u64) {
self.length = length;
}
#[inline]
pub fn block_length(&self) -> u32 {
self.block_length
}
pub fn count_blocks(&self) -> usize {
self.completed.len()
}
pub fn block_length_at(&self, block_index: usize) -> u32 {
let num_blocks = self.count_blocks();
if block_index >= num_blocks {
return 0;
}
if num_blocks > 0 && block_index == num_blocks - 1 {
self.last_block_length()
} else {
self.block_length
}
}
#[inline]
pub fn default_block_length(&self) -> u32 {
self.block_length
}
pub fn count_completed_blocks(&self) -> usize {
self.completed.count_set()
}
pub fn count_missing_blocks(&self) -> usize {
self.completed.count_clear()
}
pub fn has_block(&self, block_index: usize) -> bool {
self.completed.test(block_index)
}
pub fn is_complete(&self) -> bool {
self.completed.is_all_set()
}
pub fn completed_bitfield_bytes(&self) -> &[u8] {
self.completed.as_bytes()
}
pub fn completed_bitfield_byte_len(&self) -> usize {
self.completed.as_bytes().len()
}
pub fn set_completed_bitfield(&mut self, data: &[u8]) {
self.completed = BlockBitfield::from_bytes(data, self.count_blocks());
}
pub fn completed_length(&self) -> u64 {
let num_blocks = self.count_blocks();
if num_blocks == 0 {
return 0;
}
let completed_count = self.completed.count_set();
if completed_count == 0 {
return 0;
}
let last_block_idx = num_blocks - 1;
if self.completed.test(last_block_idx) {
(completed_count - 1) as u64 * self.block_length as u64
+ self.last_block_length() as u64
} else {
completed_count as u64 * self.block_length as u64
}
}
pub fn get_missing_unused_block_index(&mut self) -> Option<usize> {
let num_blocks = self.count_blocks();
for i in 0..num_blocks {
if !self.completed.test(i) && !self.in_use.test(i) {
self.in_use.set(i);
return Some(i);
}
}
None
}
pub fn get_missing_unused_block_indexes(&mut self, n: usize) -> Vec<usize> {
let mut result = Vec::with_capacity(n);
let num_blocks = self.count_blocks();
for i in 0..num_blocks {
if result.len() >= n {
break;
}
if !self.completed.test(i) && !self.in_use.test(i) {
self.in_use.set(i);
result.push(i);
}
}
result
}
pub fn get_first_missing_block_index(&self) -> Option<usize> {
self.completed.find_first_clear()
}
pub fn missing_block_bitfield_bytes(&self) -> Vec<u8> {
let num_blocks = self.count_blocks();
let mut missing = BlockBitfield::all_set(num_blocks);
for i in 0..num_blocks {
if self.completed.test(i) {
missing.clear(i);
}
}
missing.data.clone()
}
pub fn complete_block(&mut self, block_index: usize) {
self.completed.set(block_index);
self.in_use.clear(block_index);
}
pub fn cancel_block(&mut self, block_index: usize) {
self.in_use.clear(block_index);
}
pub fn clear_all_blocks(&mut self) {
self.completed.clear_all();
self.in_use.clear_all();
}
pub fn set_block_in_use(&mut self, block_index: usize) {
self.in_use.set(block_index);
}
pub fn clear_block_in_use(&mut self, block_index: usize) {
self.in_use.clear(block_index);
}
pub fn is_block_in_use(&self, block_index: usize) -> bool {
self.in_use.test(block_index)
}
pub fn set_used_by_segment(&mut self, used: bool) {
self.used_by_segment = used;
}
pub fn is_used_by_segment(&self) -> bool {
self.used_by_segment
}
pub fn set_all_blocks(&mut self) {
self.completed.set_all();
}
pub fn reconfigure(&mut self, length: u64) {
self.length = length;
let max_block_length = i32::MAX as u32;
let num_blocks = Self::compute_num_blocks(length, max_block_length);
self.completed = BlockBitfield::new(num_blocks);
self.in_use = BlockBitfield::new(num_blocks);
self.block_length = max_block_length;
}
pub fn add_user(&mut self, cuid: u64) {
if !self.used_by(cuid) {
self.users.push(cuid);
}
}
pub fn remove_user(&mut self, cuid: u64) {
self.users.retain(|&c| c != cuid);
}
pub fn user_count(&self) -> usize {
self.users.len()
}
pub fn used_by(&self, cuid: u64) -> bool {
self.users.contains(&cuid)
}
pub fn is_used(&self) -> bool {
!self.users.is_empty()
}
pub fn set_hash_type(&mut self, hash_type: &str) {
self.hash_type = Some(hash_type.to_string());
self.destroy_hash_context();
}
pub fn hash_type(&self) -> Option<&str> {
self.hash_type.as_deref()
}
pub fn update_hash(&mut self, begin: u64, data: &[u8]) -> bool {
let hash_type = match &self.hash_type {
Some(ht) => ht,
None => return false,
};
if begin != self.next_begin {
trace!(
"Piece::update_hash: offset mismatch, expected={}, got={}, piece={}",
self.next_begin, begin, self.index
);
return false;
}
if self.next_begin + data.len() as u64 > self.length {
trace!(
"Piece::update_hash: data would exceed piece length, next_begin={} + data_len={} > length={}, piece={}",
self.next_begin,
data.len(),
self.length,
self.index
);
return false;
}
if self.hash_state.is_none() {
match HashState::new(hash_type) {
Some(state) => self.hash_state = Some(state),
None => return false,
}
}
if let Some(ref mut state) = self.hash_state {
state.update(data);
self.next_begin += data.len() as u64;
true
} else {
false
}
}
pub fn is_hash_calculated(&self) -> bool {
self.hash_state.is_some() && self.next_begin == self.length
}
pub fn get_digest(&mut self) -> Option<Vec<u8>> {
let state = self.hash_state.take()?;
let digest = finalize_hash(state);
self.next_begin = 0;
Some(digest)
}
pub fn destroy_hash_context(&mut self) {
self.hash_state = None;
self.next_begin = 0;
}
}