lvrefcache.h 13.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
/*******************************************************

   CoolReader Engine

   lvrefcache.h:  Referenced objects cache
      allows to reuse objects with the same concents

   (c) Vadim Lopatin, 2000-2006
   This source code is distributed under the terms of
   GNU General Public License
   See LICENSE file for details

*******************************************************/

#if !defined(__LV_REF_CACHE_H_INCLUDED__)
#define __LV_REF_CACHE_H_INCLUDED__

#include "lvref.h"
#include "lvarray.h"

/*
    Object cache

    Requirements: 
       sz parameter of constructor should be power of 2
       bool operator == (LVRef<T> & r1, LVRef<T> & r2 ) should be defined
       lUInt32 calcHash( LVRef<T> & r1 ) should be defined
*/

template <class ref_t> 
class LVRefCache {

    class LVRefCacheRec {
        ref_t style;
        lUInt32 hash;
        LVRefCacheRec * next;
        LVRefCacheRec(ref_t & s, lUInt32 h)
            : style(s), hash(h), next(NULL) { }
        friend class LVRefCache< ref_t >;
    };

private:
    int size;
    LVRefCacheRec ** table;

public:
    // check whether equal object already exists if cache
    // if found, replace reference with cached value
    void cacheIt(ref_t & style)
    {
        lUInt32 hash = calcHash( style );
        lUInt32 index = hash & (size - 1);
        LVRefCacheRec **rr;
        rr = &table[index];
        while ( *rr != NULL )
        {
            if ( *(*rr)->style.get() == *style.get() )
            {
                style = (*rr)->style;
                return;
            }
            rr = &(*rr)->next;
        }
        *rr = new LVRefCacheRec( style, hash );
    }
    // garbage collector: remove unused entries
    void gc()
    {
        for (int index = 0; index < size; index++)
        {
            LVRefCacheRec **rr;
            rr = &table[index];
            while ( *rr != NULL )
            {
                if ( (*rr)->style.getRefCount() == 1 )
                {
                    LVRefCacheRec * r = (*rr);
                    *rr = r->next;
                    delete r;
                }
                else
                {
                    rr = &(*rr)->next;
                }
            }
        }
    }
    LVRefCache( int sz )
    {
        size = sz;
        table = new LVRefCacheRec * [ sz ];
        for( int i=0; i<sz; i++ )
            table[i] = NULL;
    }
    ~LVRefCache()
    {
        LVRefCacheRec *r, *r2;
        for ( int i=0; i < size; i++ )
        {
            for ( r = table[ i ]; r;  )
            {
                r2 = r;
                r = r->next;
                delete r2;
            }
        }
        delete[] table;
    }
};

template <class ref_t>
class LVIndexedRefCache {

    // hash table item
    struct LVRefCacheRec {
        int index;
        ref_t style;
        lUInt32 hash;
        LVRefCacheRec * next;
        LVRefCacheRec(ref_t & s, lUInt32 h)
            : style(s), hash(h), next(NULL) { }
    };

    // index item
    struct LVRefCacheIndexRec {
        LVRefCacheRec * item;
        int refcount; // refcount, or next free index if item==NULL
    };

private:
    int size;
    LVRefCacheRec ** table;

    LVRefCacheIndexRec * index;
    int indexsize;
    int nextindex;
    int freeindex;
    int numitems;

    int indexItem( LVRefCacheRec * rec )
    {
        int n;
        if ( freeindex ) {
            n = freeindex;
            freeindex = index[freeindex].refcount; // next free index
        } else {
            n = ++nextindex;
        }
        if ( n>=indexsize ) {
            // resize
            if ( indexsize==0 )
                indexsize = size/2;
            else
                indexsize *= 2;
            index = (LVRefCacheIndexRec*)realloc( index, sizeof(LVRefCacheIndexRec)*indexsize );
            for ( int i=nextindex+1; i<indexsize; i++ ) {
                index[i].item = NULL;
                index[i].refcount = 0;
            }
        }
        rec->index = n;
        index[n].item = rec;
        index[n].refcount = 1;
        return n;
    }

    // remove item from hash table
    void removeItem( LVRefCacheRec * item )
    {
        lUInt32 hash = item->hash;
        lUInt32 tindex = hash & (size - 1);
        LVRefCacheRec **rr = &table[tindex];
        for ( ; *rr; rr = &(*rr)->next ) {
            if ( *rr == item ) {
                LVRefCacheRec * tmp = *rr;
                *rr = (*rr)->next;
                delete tmp;
                numitems--;
                return;
            }
        }
        // not found!
    }

public:

    LVArray<ref_t> * getIndex()
    {
        LVArray<ref_t> * list = new LVArray<ref_t>(indexsize, ref_t());
        for ( int i=1; i<indexsize; i++ ) {
            if ( index[i].item )
                list->set(i, index[i].item->style);
        }
        return list;
    }

    int length()
    {
        return numitems;
    }

    void release( ref_t r )
    {
        int i = find(r);
        if (  i>0 )
            release(i);
    }

    void release( int n )
    {
        if ( n<1 || n>nextindex )
            return;
        if ( index[n].item ) {
            if ( (--index[n].refcount)<=0 ) {
                removeItem( index[n].item );
                // next free
                index[n].refcount = freeindex;
                index[n].item = NULL;
                freeindex = n;
            }
        }
    }

    // get by index
    ref_t get( int n )
    {
        if ( n>0 && n<=nextindex && index[n].item )
            return index[n].item->style;
        return ref_t();
    }

    // check whether equal object already exists if cache
    // if found, replace reference with cached value
    // returns index of item - use it to release reference
    bool cache( lUInt16 &indexholder, ref_t & style)
    {
        int newindex = cache( style );
        if ( indexholder != newindex ) {
            release( indexholder );
            indexholder = (lUInt16)newindex;
            return true;
        } else {
            release( indexholder );
            return false;
        }
    }

    bool addIndexRef( lUInt16 n )
    {
        if ( n>0 && n<=nextindex && index[n].item ) {
            index[n].refcount++;
            return true;
        } else
            return false;
    }

    // check whether equal object already exists if cache
    // if found, replace reference with cached value
    // returns index of item - use it to release reference
    int cache(ref_t & style)
    {
        lUInt32 hash = calcHash( style );
        lUInt32 index = hash & (size - 1);
        LVRefCacheRec **rr;
        rr = &table[index];
        while ( *rr != NULL )
        {
            if ( (*rr)->hash==hash && *(*rr)->style.get() == *style.get() )
            {
                style = (*rr)->style;
                int n = (*rr)->index;
                this->index[n].refcount++;
                return n;
            }
            rr = &(*rr)->next;
        }
        *rr = new LVRefCacheRec( style, hash );
        numitems++;
        return indexItem( *rr );
    }

    // check whether equal object already exists if cache
    // if found, replace reference with cached value
    // returns index of item - use it to release reference
    int find(ref_t & style)
    {
        lUInt32 hash = calcHash( style );
        lUInt32 index = hash & (size - 1);
        LVRefCacheRec **rr;
        rr = &table[index];
        while ( *rr != NULL )
        {
            if ( (*rr)->hash==hash && *(*rr)->style.get() == *style.get() )
            {
                int n = (*rr)->index;
                return n;
            }
            rr = &(*rr)->next;
        }
        return 0;
    }

    /// from index array
    LVIndexedRefCache( LVArray<ref_t> &list )
    : index(NULL)
    , indexsize(0)
    , nextindex(0)
    , freeindex(0)
    , numitems(0)
    {
        setIndex(list);
    }

    int nearestPowerOf2( int n )
    {
        int res;
        for ( res = 1; res<n; res<<=1 )
            ;
        return res;
    }

    /// init from index array
    void setIndex( LVArray<ref_t> &list )
    {
        clear();
        size = nearestPowerOf2(list.length()>0 ? list.length()*4 : 32);
        if ( table )
            delete[] table;
        table = new LVRefCacheRec * [ size ];
        for( int i=0; i<size; i++ )
            table[i] = NULL;
        indexsize = list.length();
        nextindex = indexsize > 0 ? indexsize-1 : 0;
        if ( indexsize ) {
            index = (LVRefCacheIndexRec*)realloc( index, sizeof(LVRefCacheIndexRec)*indexsize );
            index[0].item = NULL;
            index[0].refcount=0;
            for ( int i=1; i<indexsize; i++ ) {
                if ( list[i].isNull() ) {
                    // add free node
                    index[i].item = NULL;
                    index[i].refcount = freeindex;
                    freeindex = i;
                } else {
                    // add item
                    lUInt32 hash = calcHash( list[i] );
                    lUInt32 hindex = hash & (size - 1);
                    LVRefCacheRec * rec = new LVRefCacheRec(list[i], hash);
                    rec->index = i;
                    rec->next = table[hindex];
                    table[hindex] = rec;
                    index[i].item = rec;
                    index[i].refcount = 1;
                    numitems++;
                }
            }
        }
    }

    LVIndexedRefCache( int sz )
    : index(NULL)
    , indexsize(0)
    , nextindex(0)
    , freeindex(0)
    , numitems(0)
    {
        size = sz;
        table = new LVRefCacheRec * [ sz ];
        for( int i=0; i<sz; i++ )
            table[i] = NULL;
    }
    void clear( int sz = 0 )
    {
        if ( sz==-1 )
            sz = size;
        LVRefCacheRec *r, *r2;
        for ( int i=0; i < size; i++ )
        {
            for ( r = table[ i ]; r;  )
            {
                r2 = r;
                r = r->next;
                delete r2;
            }
            table[i] = NULL;
        }
        if (index) {
            free( index );
            index = NULL;
            indexsize = 0;
            nextindex = 0;
            freeindex = 0;
        }
        numitems = 0;
        if ( sz ) {
            size = sz;
            if ( table )
                delete[] table;
            table = new LVRefCacheRec * [ sz ];
            for( int i=0; i<sz; i++ )
                table[i] = NULL;
        }
    }
    ~LVIndexedRefCache()
    {
        clear();
        delete[] table;
    }
};

template <typename keyT, class dataT> class LVCacheMap
{
private:
    class Pair {
    public: 
        keyT key;
        dataT data;
        int lastAccess;
    };
    Pair * buf;
    int size;
    int numitems;
    int lastAccess;
    void checkOverflow( int oldestAccessTime )
    {
        int i;
        if ( oldestAccessTime==-1 ) {
            for ( i=0; i<size; i++ )
                if ( oldestAccessTime==-1 || buf[i].lastAccess>oldestAccessTime )
                    oldestAccessTime = buf[i].lastAccess;
        }
        if ( oldestAccessTime>1000000000 ) {
            int maxLastAccess = 0;
            for ( i=0; i<size; i++ ) {
                buf[i].lastAccess -= 1000000000;
                if ( maxLastAccess==0 || buf[i].lastAccess>maxLastAccess )
                    maxLastAccess = buf[i].lastAccess;
            }
            lastAccess = maxLastAccess+1;
        }
    }
public:
    int length()
    {
        return numitems;
    }
    LVCacheMap( int maxSize )
    : size(maxSize), numitems(0), lastAccess(1)
    {
        buf = new Pair[ size ];
        clear();
    }
    void clear()
    {
        for ( int i=0; i<size; i++ )
        {
            buf[i].key = keyT();
            buf[i].data = dataT();
            buf[i].lastAccess = 0;
        }
        numitems = 0;
    }
    bool get( keyT key, dataT & data )
    {
        for ( int i=0; i<size; i++ ) {
            if ( buf[i].key == key ) {
                data = buf[i].data;
                buf[i].lastAccess = ++lastAccess;
                if ( lastAccess>1000000000 )
                    checkOverflow(-1);
                return true;
            }
        }
        return false;
    }
    bool remove( keyT key )
    {
        for ( int i=0; i<size; i++ ) {
            if ( buf[i].key == key ) {
                buf[i].key = keyT();
                buf[i].data = dataT();
                buf[i].lastAccess = 0;
                numitems--;
                return true;
            }
        }
        return false;
    }
    void set( keyT key, dataT data )
    {
        int oldestAccessTime = -1;
        int oldestIndex = 0;
        for ( int i=0; i<size; i++ ) {
            if ( buf[i].key == key ) {
                buf[i].data = data;
                buf[i].lastAccess = ++lastAccess;
                return;
            }
            int at = buf[i].lastAccess;
            if ( at < oldestAccessTime || oldestAccessTime==-1 ) {
                oldestAccessTime = at;
                oldestIndex = i;
            }
        }
        checkOverflow(oldestAccessTime);
        if ( buf[oldestIndex].key==keyT() )
            numitems++;
        buf[oldestIndex].key = key;
        buf[oldestIndex].data = data;
        buf[oldestIndex].lastAccess = ++lastAccess;
        return;
    }
    ~LVCacheMap()
    {
        delete[] buf;
    }
};

#endif // __LV_REF_CACHE_H_INCLUDED__