1 #include <algorithm>
2 #include "vil_block_cache.h"
3 //:
4 // \file
5 #ifdef _MSC_VER
6 #  include "vcl_msvc_warnings.h"
7 #endif
8 #include <cassert>
9 
10 unsigned long bcell::time_ = 0;
11 
~vil_block_cache()12 vil_block_cache::~vil_block_cache()
13 {
14   for (auto & block : blocks_)
15   {
16     delete block;
17     block = nullptr;
18   }
19   blocks_.clear(); // empty the index
20 }
21 
22 //:add a block to the buffer.
23 bool
add_block(const unsigned & block_index_i,const unsigned & block_index_j,vil_image_view_base_sptr const & blk)24 vil_block_cache::add_block(const unsigned & block_index_i,
25                            const unsigned & block_index_j,
26                            vil_image_view_base_sptr const & blk)
27 {
28   // create a cell
29 
30   auto * cell = new bcell(block_index_i, block_index_j, blk);
31   if (blocks_.size() >= nblocks_)
32     if (!this->remove_block())
33       return false;
34   blocks_.push_back(cell);
35   std::sort(blocks_.begin(), blocks_.end(), bcell_less());
36   return true;
37 }
38 
39 bool
get_block(const unsigned & block_index_i,const unsigned & block_index_j,vil_image_view_base_sptr & blk) const40 vil_block_cache::get_block(const unsigned & block_index_i,
41                            const unsigned & block_index_j,
42                            vil_image_view_base_sptr & blk) const
43 {
44   bool found = false;
45   for (auto bit = blocks_.begin(); bit != blocks_.end() && !found; ++bit)
46   {
47     if ((*bit)->bindex_i_ != block_index_i || (*bit)->bindex_j_ != block_index_j)
48       continue;
49     else
50     {
51       found = true;
52       blk = (*bit)->blk_;
53       (*bit)->touch(); // block is in demand so update the age to zero
54     }
55   }
56   return found;
57 }
58 
59 //:remove the oldest priority block
60 bool
remove_block()61 vil_block_cache::remove_block()
62 {
63   if (blocks_.empty())
64   {
65     std::cerr << "warning: attempt to remove block from empty cache\n";
66     return false;
67   }
68   // queue should already be sorted
69   // remove oldest
70   auto bit = blocks_.begin();
71   blocks_.erase(bit);
72   return true;
73 }
74