Advertisement
keker123

Untitled

May 7th, 2023
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include "byte_tools.h"
  2. #include "piece.h"
  3. #include <iostream>
  4. #include <algorithm>
  5.  
  6. namespace {
  7. constexpr size_t BLOCK_SIZE = 1 << 14;
  8. }
  9.  
  10. Piece::Piece(size_t index, size_t length, std::string hash)
  11.     : index_(index)
  12.     , length_(length)
  13.     , hash_(std::move(hash))
  14.     , blocks_(length / BLOCK_SIZE + (length % BLOCK_SIZE == 0 ? 0 : 1)) {
  15.     for (size_t i = 0; i < blocks_.size(); i++) {
  16.         blocks_[i].piece = index_;
  17.         blocks_[i].offset = i * BLOCK_SIZE;
  18.         blocks_[i].length = std::min(BLOCK_SIZE, length_ - i * BLOCK_SIZE);
  19.     }
  20. }
  21.  
  22. void Piece::Reset() {
  23.     for (auto& block : blocks_) {
  24.         block.status = Block::Status::Missing;
  25.         block.data.clear();
  26.     }
  27. }
  28.  
  29. const std::string &Piece::GetHash() const {
  30.     return hash_;
  31. }
  32.  
  33. size_t Piece::GetIndex() const {
  34.     return index_;
  35. }
  36.  
  37. std::string Piece::GetData() const {
  38.     std::string data;
  39.     for (const auto& block : blocks_) {
  40.         data += block.data;
  41.     }
  42.     return data;
  43. }
  44.  
  45. std::string Piece::GetDataHash() const {
  46.     return CalculateSHA1(GetData());
  47. }
  48.  
  49. bool Piece::HashMatches() const {
  50.     return GetDataHash() == hash_;
  51. }
  52.  
  53. void Piece::SaveBlock(size_t blockOffset, std::string data) {
  54.     blocks_[blockOffset].data = std::move(data);
  55.     blocks_[blockOffset].status = Block::Status::Retrieved;
  56. }
  57.  
  58. Block *Piece::FirstMissingBlock() {
  59.     auto it = std::find_if(blocks_.begin(), blocks_.end(), [](const Block& block) {
  60.         return block.status == Block::Status::Missing;
  61.     });
  62.     if (it == blocks_.end()) {
  63.         return nullptr;
  64.     }
  65.     return &(*it);
  66. }
  67.  
  68. bool Piece::AllBlocksRetrieved() const {
  69.     return std::all_of(blocks_.begin(), blocks_.end(), [](const Block& block) {
  70.         return block.status == Block::Status::Retrieved;
  71.     });
  72. }
  73.  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement