ContigousMemory / memories / WorstFitMemory.cpp
WorstFitMemory.cpp
Raw
#include "FauxMemory.imp.h"

class WorstFitMemory : public FauxMemory {

  public:

  // Constructor
  WorstFitMemory(int size) : FauxMemory(size){strategy = "Worst fit";};


  // Malloc
   bool allocMem(ProgramBlock* new_block){
    // Increment BID (block id) , sort of like a PID.
    
    
    // increment if next block can only be "id + 1"
    this->incrementBid();
    
    
    // Check if the new block is indeed the next in the sequence.
    if((*this->getBid()) != new_block->getId()){
      return false;
    }


    // First check if new block > available free space in memory.
    if (new_block->getSize() > (*this->getFree())){
      return false;
    };


    // Make sure new block size is not negative or zero.
    if (new_block->getSize() < 1){
      return false;
    }    


    // Look for the best block
    MemBlock* worst_block = NULL;
    int worst_block_index;

    for(int i = 0; i < (*this->getAllBlocks()).size(); i++){
      MemBlock* curr_block = (*this->getAllBlocks())[i];
      // Check if current block is a hole block.
      if(curr_block->getId() == -1){


        // Check if hole block is big enough to fit the new program block
        if(curr_block->getSize() >= new_block->getSize()){


          // Base case if no worst_block had been found so far.
          if(worst_block == NULL){
            worst_block = curr_block;
            worst_block_index = i;



          // Compare to see if current hole block is larger than worst_block so far
          }else if(curr_block->getSize() > worst_block->getSize()){
            worst_block = curr_block;
            worst_block_index = i;

          };
        };
      };
    };

    // Confirm that a suitable block had been found
    if(worst_block == NULL){
      return false;
    };

    // Case program and hole blocks equal
    if(new_block->getSize() == worst_block->getSize()){
      // Set addresses
      new_block->setStart(worst_block->getStart());
      new_block->setEnd(worst_block->getEnd());


      (*this->getAllBlocks()).insert(this->getAllBlocks()->begin() + worst_block_index, new_block);
      (*this->getAllBlocks()->erase(this->getAllBlocks()->begin() + worst_block_index + 1));
      delete worst_block;


    // Case program block smaller
    } else {
      // Set addressess.
      new_block->setStart(worst_block->getStart());
      new_block->setEnd(worst_block->getStart() + new_block->getSize() - 1);
      (*this->getAllBlocks()).insert(this->getAllBlocks()->begin() + worst_block_index, new_block);

      worst_block->setStart(new_block->getEnd() + 1);
      worst_block->resize();
    }
    
    // Reduce free space in the faux memory.
    this->setFree((*this->getFree()) - new_block->getSize());

    // Sucessfull allocation
    return true;
   };
};