MRUCache.h 17.3 KB
Newer Older
hrchilds's avatar
hrchilds committed
1 2
/*****************************************************************************
*
bonnell's avatar
bonnell committed
3
* Copyright (c) 2000 - 2015, Lawrence Livermore National Security, LLC
hrchilds's avatar
hrchilds committed
4
* Produced at the Lawrence Livermore National Laboratory
brugger's avatar
 
brugger committed
5
* LLNL-CODE-442911
hrchilds's avatar
hrchilds committed
6 7
* All rights reserved.
*
brugger's avatar
 
brugger committed
8
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
hrchilds's avatar
hrchilds committed
9 10 11 12 13 14 15 16 17 18
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
brugger's avatar
 
brugger committed
19 20 21
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
hrchilds's avatar
hrchilds committed
22 23 24 25 26
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
brugger's avatar
 
brugger committed
27 28 29
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
hrchilds's avatar
hrchilds committed
30 31 32 33 34 35 36 37 38
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

hrchilds's avatar
hrchilds committed
39 40 41
#ifndef MRU_CACHE_H
#define MRU_CACHE_H

fogal1's avatar
fogal1 committed
42
#include <cstddef>
miller86's avatar
miller86 committed
43
#include <cstdlib>
hrchilds's avatar
hrchilds committed
44
#include <map>
hrchilds's avatar
hrchilds committed
45
#include <vector>
hrchilds's avatar
hrchilds committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

// ****************************************************************************
//
//  Class: MRUCacheBase
//
//  Purpose: Provide a generic, map-like, container that also serves as a
//  most recently used cache. This class is implemented using 2 STL maps. One
//  for the cached entries and one for the 'age counters' of those entries.
//  We use two STL maps rather than a single map whose value is a pair
//  of <cached-value, age> so that we can easily return an iterator to
//  the caller to iterate over the cached entries as s/he ordinarily would.
//
//  The notion of 'most-recent' is implemented by keeping a sort-of 'clock'
//  for the cache. It is just a simple counter. Each time an operation on the
//  cache is performed that effects what is stored in the cache, the 'clock'
//  is incremented. Likewise, when entries in the cache are referenced there
//  age is updated to whatever the current 'clock' is.
//
//  All of the magic of occurs on a reference to
//  an item in the cache with the '[]' operator.  When items in the cache are
//  referenced using the '[]' operator, if the referenced item exists in the
//  cache, it is returned to the caller and it's "age" is also updated to
//  to the current 'clock' to indicate it is the most recently used item.
//  In this way, the oldest item in the cache is the one whose age is the
//  smallest. When an item referenced by the '[]' operator is not in the cache,
//  a new slot is made available in the cache for the item. If the cache is
//  full, the oldest entry in the cache is removed and its data is deleted.
//
//  The deletion of the cached data is handled by the 3rd argument to the
//  template, the MRUCache_DeleteMethod. The options are to not delete,
//  to use 'delete' to delete the data, to use 'delete []' to delete the
//  data or to use 'free()' to delete the data. Again, the particular
//  choice depends on the 3rd argument to the template which creates the
//  cache to begin with.
//
//  A cache is created using the following syntax
//
//     MRUCache< key-type, val-type, del-method, init-size> gorfo
//
//  where
//
//     key-type:   the type of key used to reference items in the cache.
//     val-type:   the type of values stored in the cache
//     del-method: how to delete the values that are cached
//     init-size:  initial number of slots in the cache
//
//  Notes: Unfortunately, there is no way to tell the difference between
//  a pointer obtained from a call such as 'new gorfo[...]' versus
//  'new gorfo'. This is important as the appropriate delete for the
//  former is 'delete []' while it is 'delete' for the latter. Consequently,
//  care must be taken to selecte the appropriate 'del-method' for the
hrchilds's avatar
hrchilds committed
97 98 99
//  val-type being used in the cache. If all else fails, you can always
//  set the delete callback method so MRUCache will call your special
//  purpose delete method.
hrchilds's avatar
hrchilds committed
100 101 102 103
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
hrchilds's avatar
hrchilds committed
104 105 106 107 108 109 110
//  Modifications:
//    Mark C. Miller, Wed Aug  2 19:58:44 PDT 2006
//    Fixed problems with deleteit only getting invoked on base-class.
//    Fixed problems with clear getting called too late in deconstruction.
//    Added find methods. Renamed existing find to exists. Added
//    CallbackDelete specialization.
//
hrchilds's avatar
hrchilds committed
111 112 113 114 115
//    Jeremy Meredith, Mon Aug 28 18:04:57 EDT 2006
//    Newer gcc's won't resolve unqualified members of a dependent base in 
//    templates.  See [temp.dep]/3 in the ANSI C++ Standard.  Using explicit
//    this-> fixes it (as would adding explicit "using" declaration).
//
116 117 118 119
//    Mark C. Miller, Mon Jul 30 13:31:00 PDT 2007
//    Made oldest method public.
//    Added const operator[]
//
fogal1's avatar
fogal1 committed
120 121 122
//    Tom Fogal, Thu Aug 21 16:06:29 EDT 2008
//    Made the destructor virtual, since there is a virtual method.
//
hrchilds's avatar
hrchilds committed
123 124 125 126 127 128 129
// ****************************************************************************

// tags for which kind of delete to call on cache pre-emption
typedef enum {
   MRUCache_DontDelete,
   MRUCache_Delete,
   MRUCache_ArrayDelete,
hrchilds's avatar
hrchilds committed
130 131
   MRUCache_Free,
   MRUCache_CallbackDelete
hrchilds's avatar
hrchilds committed
132 133
} MRUCache_DeleteMethod;

hrchilds's avatar
hrchilds committed
134
typedef void (*MRUCache_DeleteCallback)(void*);
hrchilds's avatar
hrchilds committed
135 136 137 138 139 140 141

// kT is keyType, vT is valueType
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS=20>
class MRUCacheBase {

   public:

hrchilds's avatar
hrchilds committed
142
      MRUCacheBase() : numSlots(nS), ageCounter(0) {};
fogal1's avatar
fogal1 committed
143
      virtual ~MRUCacheBase() {};
hrchilds's avatar
hrchilds committed
144 145

      // explicit existence test (won't change MRU history)
hrchilds's avatar
hrchilds committed
146
      bool exists(const kT& key) const;
hrchilds's avatar
hrchilds committed
147 148 149 150 151 152 153 154 155 156 157

      // explicit remove of an entry from the cache
      void remove(const kT& key);

      // remove all entries from the cache
      void clear(void);

      // get reference to cached entry 
      //    a. hit moves cached entry to mru,
      //    b. miss removes lru entry, moves new entry to mru
      vT& operator[](const kT& key);
158
      const vT& operator[](const kT& key) const;
hrchilds's avatar
hrchilds committed
159 160

      // iterator (only allow const_iterator)
161 162
      typedef typename std::map<kT,vT>::const_iterator const_iterator;
      typedef typename std::map<kT,vT>::const_iterator iterator;
hrchilds's avatar
hrchilds committed
163 164 165
      const_iterator begin(void) const { return cache.begin(); };
      const_iterator end(void) const { return cache.end(); };

hrchilds's avatar
hrchilds committed
166 167 168 169 170 171 172 173 174 175
      // find operators
      iterator find(const kT& key)
      {
          iterator mpos = cache.find(key);
          if (mpos != end())
              age[key] = ageCounter++;
          return mpos;
      };
      const_iterator find(const kT& key) const { return cache.find(key); };

fogal1's avatar
fogal1 committed
176
      iterator find(const std::vector<kT>& keys)
hrchilds's avatar
hrchilds committed
177 178
      {
          iterator mpos;
179
          for (size_t i = 0; i < keys.size(); i++)
hrchilds's avatar
hrchilds committed
180 181 182 183 184 185 186
          {
              mpos = find(keys[i]);
              if (mpos != end())
                  return mpos;
          }
          return mpos;
      }
fogal1's avatar
fogal1 committed
187
      const_iterator find(const std::vector<kT>& keys) const
hrchilds's avatar
hrchilds committed
188 189 190 191 192 193 194 195 196 197 198
      {
          iterator mpos;
          for (int i = 0; i < keys.size(); i++)
          {
              mpos = find(keys[i]);
              if (mpos != end())
                  return mpos;
          }
          return mpos;
      }

hrchilds's avatar
hrchilds committed
199
      // get most recently used entry 
200
      const vT& mru(void) const;
hrchilds's avatar
hrchilds committed
201 202 203 204

      // return total memory used by all cached values
      size_t memsize(void) const { return cache.size() * sizeof(vT); };

205 206 207
      // return number of cache slots in use
      size_t size(void) const { return cache.size(); };

hrchilds's avatar
hrchilds committed
208 209 210 211 212 213 214 215 216 217
      // return number of cache slots 
      size_t numslots(void) const { return numSlots; };

      // set number of cache slots, may result in
      // cache deletions if smaller than previous number
      size_t numslots(size_t newNumSlots);

      // returns key of the oldest entry
      kT oldest(void);

218 219
   private:

hrchilds's avatar
hrchilds committed
220
      // only method to be overridden based on item type 
hrchilds's avatar
hrchilds committed
221
      virtual void deleteit(vT& item)  = 0;
hrchilds's avatar
hrchilds committed
222 223 224 225 226 227 228 229 230

      // maximum number of slots in cache
      size_t numSlots;

      // a sort-of clock for aging entries
      size_t ageCounter;

      // cached values indexed by keys
      // (we use two maps so we can return an iterator to cache)
231 232
      std::map<kT,vT>  cache;
      std::map<kT,int> age;
hrchilds's avatar
hrchilds committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
};

// The MRUCache class
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS=20>
class MRUCache : public MRUCacheBase<kT,vT,dM,nS>
{
   public:
      MRUCache() : MRUCacheBase<kT,vT,dM,nS>() {} ;
};

// DontDelete specialization
template<class kT, class vT, size_t nS>
class MRUCache<kT,vT,MRUCache_DontDelete,nS> : public MRUCacheBase<kT,vT,MRUCache_DontDelete,nS>
{
   public:
      MRUCache() : MRUCacheBase<kT,vT,MRUCache_DontDelete,nS>() {} ;
hrchilds's avatar
hrchilds committed
249
     ~MRUCache() { this->clear(); };
hrchilds's avatar
hrchilds committed
250 251
   private:
      void deleteit(vT& item) {} ;
hrchilds's avatar
hrchilds committed
252 253 254 255 256 257 258 259
};

// Delete specialization
template<class kT, class vT, size_t nS>
class MRUCache<kT,vT,MRUCache_Delete,nS> : public MRUCacheBase<kT,vT,MRUCache_Delete,nS>
{
   public:
      MRUCache() : MRUCacheBase<kT,vT,MRUCache_Delete,nS>() {} ;
hrchilds's avatar
hrchilds committed
260
     ~MRUCache() { this->clear(); };
hrchilds's avatar
hrchilds committed
261 262 263 264 265 266 267 268 269 270
   private:
      void deleteit(vT& item) { delete item; } ;
};

// ArrayDelete specialization 
template<class kT, class vT, size_t nS>
class MRUCache<kT,vT,MRUCache_ArrayDelete,nS> : public MRUCacheBase<kT,vT,MRUCache_ArrayDelete,nS>
{
   public:
      MRUCache() : MRUCacheBase<kT,vT,MRUCache_ArrayDelete,nS>() {} ;
hrchilds's avatar
hrchilds committed
271
     ~MRUCache() { this->clear(); };
hrchilds's avatar
hrchilds committed
272 273 274 275 276 277 278 279 280 281
   private:
      void deleteit(vT& item) { delete [] item; } ;
};

// Free specialization 
template<class kT, class vT, size_t nS>
class MRUCache<kT,vT,MRUCache_Free,nS> : public MRUCacheBase<kT,vT,MRUCache_Free,nS>
{
   public:
      MRUCache() : MRUCacheBase<kT,vT,MRUCache_Free,nS>() {} ;
hrchilds's avatar
hrchilds committed
282
     ~MRUCache() { this->clear(); };
hrchilds's avatar
hrchilds committed
283 284 285 286
   private:
      void deleteit(vT& item) { free (item); } ;
};

hrchilds's avatar
hrchilds committed
287 288 289 290 291 292
// Delete callback specialization 
template<class kT, class vT, size_t nS>
class MRUCache<kT,vT,MRUCache_CallbackDelete,nS> : public MRUCacheBase<kT,vT,MRUCache_CallbackDelete,nS>
{
   public:
      MRUCache(MRUCache_DeleteCallback cb) : MRUCacheBase<kT,vT,MRUCache_CallbackDelete,nS>(), delCb(cb) {};
hrchilds's avatar
hrchilds committed
293
     ~MRUCache() { this->clear(); };
hrchilds's avatar
hrchilds committed
294 295 296 297 298 299
   private:
      MRUCache() : MRUCacheBase<kT,vT,MRUCache_CallbackDelete,nS>(), delCb(0) {};
      MRUCache_DeleteCallback  delCb;
      void deleteit(vT& item) { (*delCb) (item); } ;
};

hrchilds's avatar
hrchilds committed
300
// ****************************************************************************
hrchilds's avatar
hrchilds committed
301
//  Method: MRUCacheBase::exists
hrchilds's avatar
hrchilds committed
302 303 304 305 306 307 308 309 310 311 312 313
//
//  Purpose: an explicit test for existence of an entry in the cache. Does not
//  change the MRU history
//
//  Arguments:
//     key: the key to search for 
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
hrchilds's avatar
hrchilds committed
314
bool MRUCacheBase<kT,vT,dM,nS>::exists(const kT& key) const
hrchilds's avatar
hrchilds committed
315
{
hrchilds's avatar
hrchilds committed
316
   return cache.find(key) != cache.end();
hrchilds's avatar
hrchilds committed
317 318 319 320 321 322 323 324 325 326 327 328 329
}

// ****************************************************************************
//  Method: MRUCacheBase::remove
//
//  Purpose: an explicit removal of an entry in the cache
//
//  Arguments:
//     key: the key to the item to remove 
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
hrchilds's avatar
hrchilds committed
330 331 332 333 334
//  Modifications:
//    Mark C. Miller, Mon Sep 18 14:22:13 PDT 2006
//    Worked around apparent STL bug on AIX where the const kT& key arg for kT
//    being type string was getting changed to "" after calling cache.erase(k)
//
hrchilds's avatar
hrchilds committed
335 336 337 338
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
void MRUCacheBase<kT,vT,dM,nS>::remove(const kT& key)
{
339
   typename std::map<kT,vT>::iterator k = cache.find(key);
hrchilds's avatar
hrchilds committed
340 341 342 343 344 345 346
   if (k == cache.end())
      return;

   // delete the cached value
   deleteit(k->second);

   // erase slots from the cache
347
   typename std::map<kT,int>::iterator j = age.find(key);
hrchilds's avatar
hrchilds committed
348
   cache.erase(k);
hrchilds's avatar
hrchilds committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
   age.erase(j);
}

// ****************************************************************************
//  Method: MRUCacheBase::clear
//
//  Purpose: Remove all the items from the cache 
//
//  Note: we take a funny approach here to confine all work having to do with
//  deleting entries to the 'remove' method
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
void MRUCacheBase<kT,vT,dM,nS>::clear(void)
{
367
   typename std::map<kT,vT>::iterator i = cache.begin();
hrchilds's avatar
hrchilds committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

   while (i != cache.end())
   {
      remove(i->first);
      i = cache.begin();
   }
}

// ****************************************************************************
//  Method: MRUCacheBase::operator[]
//
//  Purpose: Reference an item in the cache. If the item is not found, make
//  room for it by removing the oldest item. Put the item's key at the front
//  of the mru history.
//
//  Arguments:
//     key: the key to the item
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
vT& MRUCacheBase<kT,vT,dM,nS>::operator[](const kT& key)
{
393
   typename std::map<kT,vT>::iterator mpos = cache.find(key);
hrchilds's avatar
hrchilds committed
394 395 396 397 398 399 400 401 402 403 404 405

   if (mpos == cache.end())
   {
      // Didn't find it. Erase oldest entry, add this as newest
      if (cache.size() > numSlots)
         remove(oldest());
   }

   age[key] = ageCounter++;
   return cache[key];
}

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
// ****************************************************************************
//  Method: MRUCacheBase::operator[]
//
//  Purpose: const version of above 
//
//  Arguments:
//     key: the key to the item
//
//  Programmer: Mark C. Miller 
//  Creation:   August 5, 2007 
//
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
const vT& MRUCacheBase<kT,vT,dM,nS>::operator[](const kT& key) const
{
421
   typename std::map<kT,vT>::const_iterator mpos = cache.find(key);
422 423 424
   return mpos->second;
}

hrchilds's avatar
hrchilds committed
425 426 427 428 429 430 431 432
// ****************************************************************************
//  Method: MRUCacheBase::mru
//
//  Purpose: return most recently used entry in cache 
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
433 434 435 436
//  Modifications:
//
//    Mark C. Miller, Mon Aug  6 13:36:16 PDT 2007
//    const qualified the return value
hrchilds's avatar
hrchilds committed
437 438
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
439
const vT& MRUCacheBase<kT,vT,dM,nS>::mru(void) const
hrchilds's avatar
hrchilds committed
440
{
441
   typename std::map<kT,int>::iterator i = age.begin();
hrchilds's avatar
hrchilds committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
   kT mruKey               = i->first;
   int newest              = i->second; 

   for (i = age.begin(); i != age.end(); i++)
   {
      if (i->second > newest)
      {
         newest = i->second;
         mruKey = i->first;
      }
   }

   return cache[mruKey];
}

// ****************************************************************************
//  Method: MRUCacheBase::numslots
//
//  Purpose: change the number of slots in the cache 
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
465 466 467 468
//  Modifications:
//
//    Mark C. Miller, Mon Aug  6 13:36:16 PDT 2007
//    Fixed error in missing '()' on refernece to oldest
hrchilds's avatar
hrchilds committed
469 470 471 472 473 474
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
size_t MRUCacheBase<kT,vT,dM,nS>::numslots(size_t newNumSlots)
{
   int oldNumSlots = numSlots;

475
   if (newNumSlots <= 0)
hrchilds's avatar
hrchilds committed
476 477 478 479
      return oldNumSlots;

   // remove entries if we're making it smaller
   while (newNumSlots < cache.size())
480
      remove(oldest());
hrchilds's avatar
hrchilds committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

   numSlots = newNumSlots;

   return oldNumSlots;
}

// ****************************************************************************
//  Method: MRUCacheBase::oldest
//
//  Purpose: return key of oldest entry in cache 
//
//  Programmer: Mark C. Miller 
//  Creation:   October 6, 2003 
//
// ****************************************************************************
template<class kT, class vT, MRUCache_DeleteMethod dM, size_t nS>
kT MRUCacheBase<kT,vT,dM,nS>::oldest(void)
{
499
   typename std::map<kT,int>::iterator i = age.begin();
hrchilds's avatar
hrchilds committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
   kT retval               = i->first;
   int oldestAge           = i->second; 

   for (i = age.begin(); i != age.end(); i++)
   {
      if (i->second < oldestAge)
      {
         retval    = i->first;
         oldestAge = i->second;
      }
   }

   return retval;
}

#endif