2 Copyright (C) 2000-2004 SKYRIX Software AG
4 This file is part of OGo
6 OGo is free software; you can redistribute it and/or modify it under
7 the terms of the GNU Lesser General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 OGo is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
14 License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with OGo; see the file COPYING. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 #include "SOGoLRUCache.h"
25 @interface SOGoLRUCacheItem : NSObject
31 - (id)initWithObject:(id)_obj;
38 @implementation SOGoLRUCacheItem
40 - (id)initWithObject:(id)_obj {
43 ASSIGN(self->object, _obj);
54 - (unsigned)useCount {
55 return self->useCount;
60 @implementation SOGoLRUCache
62 - (id)initWithCacheSize:(unsigned)_size {
66 self->entries = [[NSMutableDictionary alloc] initWithCapacity:_size];
72 [self->entries release];
76 - (void)addObject:(id)_obj forKey:(id)_key {
77 SOGoLRUCacheItem *item;
79 NSAssert(_obj, @"Attempt to insert nil object!");
81 if([self->entries count] >= self->size) {
82 /* need to find minimum and get rid of it */
83 NSEnumerator *keyEnum;
84 SOGoLRUCacheItem *item;
85 id key, leastUsedItemKey;
86 unsigned minimumUseCount = INT_MAX;
88 keyEnum = [self->entries keyEnumerator];
89 while((key = [keyEnum nextObject])) {
90 item = [self->entries objectForKey:key];
91 if([item useCount] < minimumUseCount) {
92 minimumUseCount = [item useCount];
93 leastUsedItemKey = key;
96 [self->entries removeObjectForKey:leastUsedItemKey];
98 item = [[SOGoLRUCacheItem alloc] initWithObject:_obj];
99 [self->entries setObject:item forKey:_key];
103 - (id)objectForKey:(id)_key {
104 SOGoLRUCacheItem *item;
106 item = [self->entries objectForKey:_key];
109 return [item object];