/** ** File ......... Piece.h ** Published .... 2005-06-14 ** Author ....... grymse@alhem.net **/ /* Copyright (C) 2005 Anders Hedstrom This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _PIECE_H #define _PIECE_H #include #include #ifdef _WIN32 #define MIN(a,b) (a slice_m; public: Piece(size_t nr,size_t piece_length); ~Piece(); size_t GetNumber() { return m_nr; } void Write(Session *,size_t offset, size_t length, unsigned char *); size_t NumberOfSlices() { return m_piece_length / SLICE; } size_t PieceLength() { return m_piece_length; } size_t SliceSize() { return SLICE; } size_t Complete(size_t offset) { return m_complete[offset]; } void SetComplete(size_t offset,size_t length) { m_complete[offset] = length; } size_t Requested(size_t offset) { return m_requested[offset]; } void SetRequested(size_t offset,size_t length) { if (!length || length > m_requested[offset]) m_requested[offset] = length; } void ClearComplete(); void ClearRequested(); bool GetRandomNotRequested(size_t& offset, size_t& length) { std::vector available; for (size_t i = 0; i < m_piece_length; i += SLICE) { if (!Complete(i) && !Requested(i)) { available.push_back(i); } } size_t q; if ((q = available.size()) > 0) { #ifdef _WIN32 offset = available[rand() % q]; #else offset = available[random() % q]; #endif length = MIN(SLICE, m_piece_length - offset); return true; } return false; } bool AllRequested() { for (size_t i = 0; i < m_piece_length; i += SLICE) { if (!Complete(i) && !Requested(i)) { return false; } } return true; } size_t NumberComplete() { size_t q = 0; for (size_t i = 0; i < m_piece_length; i += SLICE) { if (Complete(i)) q++; } return q; } size_t NumberRequested() { size_t q = 0; for (size_t i = 0; i < m_piece_length; i += SLICE) { if (Requested(i) && !Complete(i)) q++; } return q; } bool Complete() { for (size_t i = 0; i < m_piece_length; i += SLICE) { if (!Complete(i)) { return false; } } return true; } void save_slice_m(FILE *,slice_m& ); void load_slice_m(FILE *,slice_m& ); slice_m& MapComplete() { return m_complete; } slice_m& MapRequested() { return m_requested; } private: Piece(const Piece& ) {} // copy constructor Piece& operator=(const Piece& ) { return *this; } // assignment operator size_t m_nr; size_t m_piece_length; slice_m m_complete; slice_m m_requested; }; #endif // _PIECE_H