pub mod messages;
use bytes::{BufMut, BytesMut};
use tokio::io;
pub const BLOCK_LEN: u32 = 16384;
pub const PSTR: [u8; 19] = [
66, 105, 116, 84, 111, 114, 114, 101, 110, 116, 32, 112, 114, 111, 116,
111, 99, 111, 108,
];
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Block {
pub index: usize,
pub begin: u32,
pub block: Vec<u8>,
}
impl Block {
pub fn encode(&self, buf: &mut BytesMut) -> io::Result<()> {
let piece_index = self
.index
.try_into()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
buf.put_u32(piece_index);
buf.put_u32(self.begin);
buf.extend_from_slice(&self.block);
Ok(())
}
pub fn is_valid(&self) -> bool {
self.block.len() <= BLOCK_LEN as usize && self.begin <= BLOCK_LEN
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlockInfo {
pub index: u32,
pub begin: u32,
pub len: u32,
}
impl Default for BlockInfo {
fn default() -> Self {
Self { index: 0, begin: 0, len: BLOCK_LEN }
}
}
impl From<Block> for BlockInfo {
fn from(val: Block) -> Self {
BlockInfo {
index: val.index as u32,
begin: val.begin,
len: val.block.len() as u32,
}
}
}
impl BlockInfo {
pub fn new() -> Self {
Self::default()
}
pub fn index(mut self, index: u32) -> Self {
self.index = index;
self
}
pub fn begin(mut self, begin: u32) -> Self {
self.begin = begin;
self
}
pub fn len(mut self, len: u32) -> Self {
self.len = len;
self
}
pub fn encode(&self, buf: &mut BytesMut) -> io::Result<()> {
buf.put_u32(self.index);
buf.put_u32(self.begin);
buf.put_u32(self.len);
Ok(())
}
pub fn is_valid(&self) -> bool {
self.len <= BLOCK_LEN && self.begin <= BLOCK_LEN && self.len > 0
}
}