Oolite
Loading...
Searching...
No Matches
OOCache.m
Go to the documentation of this file.
1/*
2
3OOCache.m
4By Jens Ayton
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
26/* IMPLEMENTATION NOTES
27 A cache needs to be able to implement three types of operation
28 efficiently:
29 * Retrieving: looking up an element by key.
30 * Inserting: setting the element associated with a key.
31 * Deleting: removing a single element.
32 * Pruning: removing one or more least-recently used elements.
33
34 An NSMutableDictionary performs the first three operations efficiently but
35 has no support for pruning - specifically no support for finding the
36 least-recently-accessed element. Using standard Foundation containers, it
37 would be necessary to use several dictionaries and arrays, which would be
38 quite inefficient since small NSArrays aren’t very good at head insertion
39 or deletion. Alternatively, a standard dictionary whose value objects
40 maintain an age-sorted list could be used.
41
42 I chose instead to implement a custom scheme from scratch. It uses two
43 parallel data structures: a doubly-linked list sorted by age, and a splay
44 tree to implement insertion/deletion. The implementation is largely
45 procedural C. Deserialization, pruning and modification tracking is done
46 in the ObjC class; everything else is done in C functions.
47
48 A SPLAY TREE is a type of semi-balanced binary search tree with certain
49 useful properties:
50 * Simplicity. All look-up and restructuring operations are based on a
51 single operation, splaying, which brings the node with the desired key
52 (or the node whose key is "left" of the desired key, if there is no
53 exact match) to the root, while maintaining the binary search tree
54 invariant. Splaying itself is sufficient for look-up; insertion and
55 deletion work by splaying and then manipulating at the root.
56 * Self-optimization. Because each look-up brings the sought element to
57 the root, often-used elements tend to stay near the top. (Oolite often
58 performs sequences of identical look-ups, for instance when creating
59 an asteroid field, or the racing ring set-up which uses lots of
60 identical ring segments; during combat, missiles, canisters and hull
61 plates will be commonly used.) Also, this means that for a retrieve-
62 attempt/insert sequence, the retrieve attempt will optimize the tree
63 for the insertion.
64 * Efficiency. In addition to the self-optimization, splay trees have a
65 small code size and no storage overhead for flags.
66 The amortized worst-case cost of splaying (cost averaged over a
67 worst-case sequence of operations) is O(log n); a single worst-case
68 splay is O(n), but that worst-case also improves the balance of the
69 tree, so you can't have two worst cases in a row. Insertion and
70 deletion are also O(log n), consisting of a splay plus an O(1)
71 operation.
72 References for splay trees:
73 * http://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf
74 Original research paper.
75 * http://www.ibr.cs.tu-bs.de/courses/ss98/audii/applets/BST/SplayTree-Example.html
76 Java applet demonstrating splaying.
77 * http://www.link.cs.cmu.edu/link/ftp-site/splaying/top-down-splay.c
78 Sample implementation by one of the inventors. The TreeSplay(),
79 TreeInsert() and CacheRemove() functions are based on this.
80
81 The AGE LIST is a doubly-linked list, ordered from oldest to youngest.
82 Whenever an element is retrieved or inserted, it is promoted to the
83 youngest end of the age list. Pruning proceeds from the oldest end of the
84 age list.
85
86 if (autoPrune)
87 {
88 PRUNING is batched, handling 20% of the cache at once. This is primarily
89 because deletion somewhat pessimizes the tree (see "Self-optimization"
90 below). It also provides a bit of code coherency. To reduce pruning
91 batches while in flight, pruning is also performed before serialization
92 (which in turn is done, if the cache has changed, whenever the user
93 docks). This has the effect that the number of items in the cache on disk
94 never exceeds 80% of the prune threshold. This is probably not actually
95 poinful, since pruning should be a very small portion of the per-frame run
96 time in any case. Premature optimization and all that jazz.
97 Pruning performs at most 0.2n deletions, and is thus O(n log n).
98 }
99 else
100 {
101 PRUNING is performed manually by calling -prune.
102 }
103
104 If the macro OOCACHE_PERFORM_INTEGRITY_CHECKS is set to a non-zero value,
105 the integrity of the tree and the age list will be checked before and
106 after each high-level operation. This is an inherently O(n) operation.
107*/
108
109#import "OOCache.h"
110#import "OOStringParsing.h"
111
112#ifndef OOCACHE_PERFORM_INTEGRITY_CHECKS
113#define OOCACHE_PERFORM_INTEGRITY_CHECKS 0
114#endif
115
116// Protocol used internally to squash idiotic warnings in gnu-gcc.
117@protocol OOCacheComparable <NSObject, NSCopying>
118- (NSComparisonResult)compare:(id<OOCacheComparable>)other;
119- (id)copy;
120@end
121
124
126 // Splay tree root
128
129 // Ends of age list
131
132 unsigned count;
133 NSString* name;
134};
135
137 // Payload
138 id<OOCacheComparable> key;
140
141 // Splay tree
143
144 // Age list
146};
147
148enum { kCountUnknown = -1U };
149
150static NSString* const kSerializedEntryKeyKey = @"key";
151static NSString* const kSerializedEntryKeyValue = @"value";
152
153static OOCacheImpl* CacheAllocate(void);
154static void CacheFree(OOCacheImpl* cache);
155
156static BOOL CacheInsert(OOCacheImpl* cache, id key, id value);
157static BOOL CacheRemove(OOCacheImpl* cache, id key);
158static BOOL CacheRemoveOldest(OOCacheImpl* cache, NSString* logKey);
159static id CacheRetrieve(OOCacheImpl* cache, id key);
160static unsigned CacheGetCount(OOCacheImpl* cache);
161static NSArray* CacheArrayOfContentsByAge(OOCacheImpl* cache);
162static NSArray* CacheArrayOfNodesByAge(OOCacheImpl* cache);
163static NSString* CacheGetName(OOCacheImpl* cache);
164static void CacheSetName(OOCacheImpl* cache, NSString* name);
165
166#if OOCACHE_PERFORM_INTEGRITY_CHECKS
167static NSString* const kOOLogCacheIntegrityCheck = @"dataCache.integrityCheck";
168static void CacheCheckIntegrity(OOCacheImpl* cache, NSString* context);
169
170#define CHECK_INTEGRITY(context) CacheCheckIntegrity(cache, (context))
171#else
172#define CHECK_INTEGRITY(context) \
173 do { \
174 } while (0)
175#endif
176
177@interface OOCache (Private)
178
179- (void)loadFromArray:(NSArray*)inArray;
180
181@end
182
183@implementation OOCache
184
185- (void)dealloc
186{
187 CHECK_INTEGRITY(@"dealloc");
189
190 [super dealloc];
191}
192
193- (NSString*)description
194{
195 return [NSString stringWithFormat:@"<%@ %p>{\"%@\", %u elements, prune threshold=%u, auto-prune=%s dirty=%s}", [self class], self, [self name], CacheGetCount(cache), pruneThreshold, autoPrune ? "yes" : "no", dirty ? "yes" : "no"];
196}
197
198- (id)init
199{
200 return [self initWithPList:nil];
201}
202
203- (id)initWithPList:(id)pList
204{
205 BOOL OK = YES;
206
207 self = [super init];
208 OK = self != nil;
209
210 if (OK) {
212 if (cache == NULL)
213 OK = NO;
214 }
215
216 if (pList != nil) {
217 if (OK)
218 OK = [pList isKindOfClass:[NSArray class]];
219 if (OK)
220 [self loadFromArray:pList];
221 }
222 if (OK) {
224 autoPrune = YES;
225 }
226
227 if (!OK) {
228 [self release];
229 self = nil;
230 }
231
232 return self;
233}
234
236{
238
239 return nil;
240}
241
242- (id)objectForKey:(id)key
243{
244 id result = nil;
245
246 CHECK_INTEGRITY(@"objectForKey: before");
247
248 result = CacheRetrieve(cache, key);
249 // Note: while reordering the age list technically makes the cache dirty, it's not worth rewriting it just for that, so we don't flag it.
250
251 CHECK_INTEGRITY(@"objectForKey: after");
252
253 return [[result retain] autorelease];
254}
255
256- (void)setObject:(id)value forKey:(id)key
257{
258 CHECK_INTEGRITY(@"setObject:forKey: before");
259
260 if (CacheInsert(cache, key, value)) {
261 dirty = YES;
262 if (autoPrune)
263 [self prune];
264 }
265
266 CHECK_INTEGRITY(@"setObject:forKey: after");
267}
268
269- (void)removeObjectForKey:(id)key
270{
271 CHECK_INTEGRITY(@"removeObjectForKey: before");
272
273 if (CacheRemove(cache, key))
274 dirty = YES;
275
276 CHECK_INTEGRITY(@"removeObjectForKey: after");
277}
278
279- (void)setPruneThreshold:(unsigned)threshold
280{
281 threshold = MAX(threshold, (unsigned)kOOCacheMinimumPruneThreshold);
282 if (threshold != pruneThreshold) {
283 pruneThreshold = threshold;
284 if (autoPrune)
285 [self prune];
286 }
287}
288
289- (unsigned)pruneThreshold
290{
291 return pruneThreshold;
292}
293
294- (void)setAutoPrune:(BOOL)flag
295{
296 BOOL prune = (flag != NO);
297 if (prune != autoPrune) {
299 [self prune];
300 }
301}
302
304{
305 return autoPrune;
306}
307
308- (void)prune
309{
310 unsigned pruneCount;
311 unsigned desiredCount;
312 unsigned count;
313
314 // Order of operations is to ensure rounding down.
315 if (autoPrune)
316 desiredCount = (pruneThreshold * 4) / 5;
317 else
318 desiredCount = pruneThreshold;
319
321 return;
322
323 pruneCount = count - desiredCount;
324
325 NSString* logKey = [NSString stringWithFormat:@"dataCache.prune.%@", CacheGetName(cache)];
326 OOLog(logKey, @"Pruning cache \"%@\" - removing %u entries", CacheGetName(cache), pruneCount);
327 OOLogIndentIf(logKey);
328
329 while (pruneCount--)
330 CacheRemoveOldest(cache, logKey);
331
332 OOLogOutdentIf(logKey);
333}
334
335- (BOOL)dirty
336{
337 return dirty;
338}
339
341{
342 dirty = NO;
343}
344
345- (NSString*)name
346{
347 return CacheGetName(cache);
348}
349
350- (void)setName:(NSString*)name
351{
353}
354
355- (NSArray*)objectsByAge
356{
358}
359
360@end
361
362@implementation OOCache (Private)
363
364- (void)loadFromArray:(NSArray*)array
365{
366 NSDictionary* entry = nil;
367 NSString* key = nil;
368 id value = nil;
369
370 if (array == nil)
371 return;
372
373 foreach (entry, array) {
374 if ([entry isKindOfClass:[NSDictionary class]]) {
375 key = [entry objectForKey:kSerializedEntryKeyKey];
376 value = [entry objectForKey:kSerializedEntryKeyValue];
377 if ([key isKindOfClass:[NSString class]] && value != nil) {
378 [self setObject:value forKey:key];
379 }
380 }
381 }
382}
383
384@end
385
386/***** Most of the implementation. In C. Because I'm inconsistent and slightly m. *****/
387
388static OOCacheNode* CacheNodeAllocate(id<OOCacheComparable> key, id value);
389static void CacheNodeFree(OOCacheImpl* cache, OOCacheNode* node);
390static id CacheNodeGetValue(OOCacheNode* node);
391static void CacheNodeSetValue(OOCacheNode* node, id value);
392
393#if OOCACHE_PERFORM_INTEGRITY_CHECKS
394static NSString* CacheNodeGetDescription(OOCacheNode* node);
395#endif
396
397static OOCacheNode* TreeSplay(OOCacheNode** root, id<OOCacheComparable> key);
398static OOCacheNode* TreeInsert(OOCacheImpl* cache, id<OOCacheComparable> key, id value);
399
400#if OOCACHE_PERFORM_INTEGRITY_CHECKS
401static unsigned TreeCountNodes(OOCacheNode* node);
402static OOCacheNode* TreeCheckIntegrity(OOCacheImpl* cache, OOCacheNode* node, OOCacheNode* expectedParent, NSString* context);
403#endif
404
405static void AgeListMakeYoungest(OOCacheImpl* cache, OOCacheNode* node);
406static void AgeListRemove(OOCacheImpl* cache, OOCacheNode* node);
407
408#if OOCACHE_PERFORM_INTEGRITY_CHECKS
409static void AgeListCheckIntegrity(OOCacheImpl* cache, NSString* context);
410#endif
411
412/***** CacheImpl functions *****/
413
415{
416 return calloc(sizeof(OOCacheImpl), 1);
417}
418
419static void CacheFree(OOCacheImpl* cache)
420{
421 if (cache == NULL)
422 return;
423
424 CacheNodeFree(cache, cache->root);
425 [cache->name autorelease];
426 free(cache);
427}
428
429static BOOL CacheInsert(OOCacheImpl* cache, id key, id value)
430{
431 OOCacheNode* node = NULL;
432
433 if (cache == NULL || key == nil || value == nil)
434 return NO;
435
436 node = TreeInsert(cache, key, value);
437 if (node != NULL) {
438 AgeListMakeYoungest(cache, node);
439 return YES;
440 } else
441 return NO;
442}
443
444static BOOL CacheRemove(OOCacheImpl* cache, id key)
445{
446 OOCacheNode *node = NULL, *newRoot = NULL;
447
448 node = TreeSplay(&cache->root, key);
449 if (node != NULL) {
450 if (node->leftChild == NULL)
451 newRoot = node->rightChild;
452 else {
453 newRoot = node->leftChild;
454 TreeSplay(&newRoot, key);
455 newRoot->rightChild = node->rightChild;
456 }
457 node->leftChild = NULL;
458 node->rightChild = NULL;
459
460 cache->root = newRoot;
461 --cache->count;
462
463 AgeListRemove(cache, node);
464 CacheNodeFree(cache, node);
465
466 return YES;
467 } else
468 return NO;
469}
470
471static BOOL CacheRemoveOldest(OOCacheImpl* cache, NSString* logKey)
472{
473 // This could be more efficient, but does it need to be?
474 if (cache == NULL || cache->oldest == NULL)
475 return NO;
476
477 OOLog(logKey, @"Pruning cache \"%@\": removing %@", cache->name, cache->oldest->key);
478 return CacheRemove(cache, cache->oldest->key);
479}
480
481static id CacheRetrieve(OOCacheImpl* cache, id key)
482{
483 OOCacheNode* node = NULL;
484 id result = nil;
485
486 if (cache == NULL || key == NULL)
487 return nil;
488
489 node = TreeSplay(&cache->root, key);
490 if (node != NULL) {
491 result = CacheNodeGetValue(node);
492 AgeListMakeYoungest(cache, node);
493 }
494 return result;
495}
496
498{
499 OOCacheNode* node = NULL;
500 NSMutableArray* result = nil;
501
502 if (cache == NULL || cache->count == 0)
503 return nil;
504
505 result = [NSMutableArray arrayWithCapacity:cache->count];
506
507 for (node = cache->youngest; node != NULL; node = node->older) {
508 [result addObject:node->value];
509 }
510 return result;
511}
512
513static NSArray* CacheArrayOfNodesByAge(OOCacheImpl* cache)
514{
515 OOCacheNode* node = NULL;
516 NSMutableArray* result = nil;
517
518 if (cache == NULL || cache->count == 0)
519 return nil;
520
521 result = [NSMutableArray arrayWithCapacity:cache->count];
522
523 for (node = cache->oldest; node != NULL; node = node->younger) {
524 [result addObject:[NSDictionary dictionaryWithObjectsAndKeys:node->key, kSerializedEntryKeyKey, node->value, kSerializedEntryKeyValue, nil]];
525 }
526 return result;
527}
528
529static NSString* CacheGetName(OOCacheImpl* cache)
530{
531 return cache->name;
532}
533
534static void CacheSetName(OOCacheImpl* cache, NSString* name)
535{
536 [cache->name autorelease];
537 cache->name = [name copy];
538}
539
540static unsigned CacheGetCount(OOCacheImpl* cache)
541{
542 return cache->count;
543}
544
545#if OOCACHE_PERFORM_INTEGRITY_CHECKS
546
547static void CacheCheckIntegrity(OOCacheImpl* cache, NSString* context)
548{
549 unsigned trueCount;
550
551 cache->root = TreeCheckIntegrity(cache, cache->root, NULL, context);
552
553 trueCount = TreeCountNodes(cache->root);
554 if (kCountUnknown == cache->count)
555 cache->count = trueCount;
556 else if (cache->count != trueCount) {
557 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): count is %u, but should be %u.", context, cache->name, cache->count, trueCount);
558 cache->count = trueCount;
559 }
560
561 AgeListCheckIntegrity(cache, context);
562}
563
564#endif // OOCACHE_PERFORM_INTEGRITY_CHECKS
565
566/***** CacheNode functions *****/
567
568// CacheNodeAllocate(): create a cache node for a key, value pair, without inserting it in the structures.
569static OOCacheNode* CacheNodeAllocate(id<OOCacheComparable> key, id value)
570{
571 OOCacheNode* result = NULL;
572
573 if (key == nil || value == nil)
574 return NULL;
575
576 result = calloc(sizeof *result, 1);
577 if (result != NULL) {
578 result->key = [key copy];
579 result->value = [value retain];
580 }
581
582 return result;
583}
584
585// CacheNodeFree(): recursively delete a cache node and its children in the splay tree. To delete an individual node, first clear its child pointers.
586static void CacheNodeFree(OOCacheImpl* cache, OOCacheNode* node)
587{
588 id key, value;
589
590 if (node == NULL)
591 return;
592
593 AgeListRemove(cache, node);
594
595 key = node->key;
596 node->key = nil;
597 [key release];
598
599 value = node->value;
600 node->value = nil;
601 [value release];
602
603 CacheNodeFree(cache, node->leftChild);
604 CacheNodeFree(cache, node->rightChild);
605
606 free(node);
607}
608
609// CacheNodeGetValue(): retrieve the value of a cache node
611{
612 if (node == NULL)
613 return nil;
614
615 return node->value;
616}
617
618// CacheNodeSetValue(): change the value of a cache node (as when setObject:forKey: is called for an existing key).
619static void CacheNodeSetValue(OOCacheNode* node, id value)
620{
621 if (node == NULL)
622 return;
623
624 id tmp = node->value;
625 node->value = [value retain];
626 [tmp release];
627}
628
629#if OOCACHE_PERFORM_INTEGRITY_CHECKS
630// CacheNodeGetDescription(): get a description of a cache node for debugging purposes.
631static NSString* CacheNodeGetDescription(OOCacheNode* node)
632{
633 if (node == NULL)
634 return @"0[null]";
635
636 return [NSString stringWithFormat:@"%p[\"%@\"]", node, node->key];
637}
638#endif // OOCACHE_PERFORM_INTEGRITY_CHECKS
639
640/***** Tree functions *****/
641
642/* TreeSplay()
643 This is the fundamental operation of a splay tree. It searches for a node
644 with a given key, and rebalances the tree so that the found node becomes
645 the root. If no match is found, the node moved to the root is the one that
646 would have been found before the target, and will thus be a neighbour of
647 the target if the key is subsequently inserted.
648*/
649static OOCacheNode* TreeSplay(OOCacheNode** root, id<OOCacheComparable> key)
650{
651 NSComparisonResult order;
652 OOCacheNode N = { .leftChild = NULL, .rightChild = NULL };
653 OOCacheNode *node = NULL, *temp = NULL, *l = &N, *r = &N;
654 BOOL exact = NO;
655
656 if (root == NULL || *root == NULL || key == nil)
657 return NULL;
658
659 node = *root;
660
661 for (;;) {
662#ifndef NDEBUG
663 if (node == NULL) {
664 OOLog(@"node.error", @"%@", @"node is NULL");
665 } else if (node->key == NULL) {
666 OOLog(@"node.error", @"%@", @"node->key is NULL");
667 }
668#endif
669 order = [key compare:node->key];
670 if (order == NSOrderedAscending) {
671 // Closest match is in left subtree
672 if (node->leftChild == NULL)
673 break;
674 if ([key compare:node->leftChild->key] == NSOrderedAscending) {
675 // Rotate right
676 temp = node->leftChild;
677 node->leftChild = temp->rightChild;
678 temp->rightChild = node;
679 node = temp;
680 if (node->leftChild == NULL)
681 break;
682 }
683 // Link right
684 r->leftChild = node;
685 r = node;
686 node = node->leftChild;
687 } else if (order == NSOrderedDescending) {
688 // Closest match is in right subtree
689 if (node->rightChild == NULL)
690 break;
691 if ([key compare:node->rightChild->key] == NSOrderedDescending) {
692 // Rotate left
693 temp = node->rightChild;
694 node->rightChild = temp->leftChild;
695 temp->leftChild = node;
696 node = temp;
697 if (node->rightChild == NULL)
698 break;
699 }
700 // Link left
701 l->rightChild = node;
702 l = node;
703 node = node->rightChild;
704 } else {
705 // Found exact match
706 exact = YES;
707 break;
708 }
709 }
710
711 // Assemble
712 l->rightChild = node->leftChild;
713 r->leftChild = node->rightChild;
714 node->leftChild = N.rightChild;
715 node->rightChild = N.leftChild;
716
717 *root = node;
718 return exact ? node : NULL;
719}
720
721static OOCacheNode* TreeInsert(OOCacheImpl* cache, id<OOCacheComparable> key, id value)
722{
723 OOCacheNode *closest = NULL,
724 *node = NULL;
725 NSComparisonResult order;
726
727 if (cache == NULL || key == nil || value == nil)
728 return NULL;
729
730 if (cache->root == NULL) {
731 node = CacheNodeAllocate(key, value);
732 cache->root = node;
733 cache->count = 1;
734 } else {
735 node = TreeSplay(&cache->root, key);
736 if (node != NULL) {
737 // Exact match: key already exists, reuse its node
738 CacheNodeSetValue(node, value);
739 } else {
740 closest = cache->root;
741 node = CacheNodeAllocate(key, value);
742 if (EXPECT_NOT(node == NULL))
743 return NULL;
744
745 order = [key compare:closest->key];
746
747 if (order == NSOrderedAscending) {
748 // Insert to left
749 node->leftChild = closest->leftChild;
750 node->rightChild = closest;
751 closest->leftChild = NULL;
752 cache->root = node;
753 ++cache->count;
754 } else if (order == NSOrderedDescending) {
755 // Insert to right
756 node->rightChild = closest->rightChild;
757 node->leftChild = closest;
758 closest->rightChild = NULL;
759 cache->root = node;
760 ++cache->count;
761 } else {
762 // Key already exists, which we should have caught above
763 OOLog(@"dataCache.inconsistency", @"%s() internal inconsistency for cache \"%@\", insertion failed.", __PRETTY_FUNCTION__, cache->name);
764 CacheNodeFree(cache, node);
765 return NULL;
766 }
767 }
768 }
769
770 return node;
771}
772
773#if OOCACHE_PERFORM_INTEGRITY_CHECKS
774static unsigned TreeCountNodes(OOCacheNode* node)
775{
776 if (node == NULL)
777 return 0;
778 return 1 + TreeCountNodes(node->leftChild) + TreeCountNodes(node->rightChild);
779}
780
781// TreeCheckIntegrity(): verify the links and contents of a (sub-)tree. If successful, returns the root of the subtree (which could theoretically be changed), otherwise returns NULL.
782static OOCacheNode* TreeCheckIntegrity(OOCacheImpl* cache, OOCacheNode* node, OOCacheNode* expectedParent, NSString* context)
783{
784 NSComparisonResult order;
785 BOOL OK = YES;
786
787 if (node == NULL)
788 return NULL;
789
790 if (OK && node->key == nil) {
791 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): node \"%@\" has nil key; deleting subtree.", context, cache->name, CacheNodeGetDescription(node));
792 OK = NO;
793 }
794
795 if (OK && node->value == nil) {
796 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): node \"%@\" has nil value, deleting.", context, cache->name, CacheNodeGetDescription(node));
797 OK = NO;
798 }
799 if (OK && node->leftChild != NULL) {
800 order = [node->key compare:node->leftChild->key];
801 if (order != NSOrderedDescending) {
802 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): node %@'s left child %@ is not correctly ordered. Deleting subtree.", context, cache->name, CacheNodeGetDescription(node), CacheNodeGetDescription(node->leftChild));
803 CacheNodeFree(cache, node->leftChild);
804 node->leftChild = NULL;
805 cache->count = kCountUnknown;
806 } else {
807 node->leftChild = TreeCheckIntegrity(cache, node->leftChild, node, context);
808 }
809 }
810 if (node->rightChild != NULL) {
811 order = [node->key compare:node->rightChild->key];
812 if (order != NSOrderedAscending) {
813 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): node \"%@\"'s right child \"%@\" is not correctly ordered. Deleting subtree.", context, cache->name, CacheNodeGetDescription(node), CacheNodeGetDescription(node->rightChild));
814 CacheNodeFree(cache, node->rightChild);
815 node->rightChild = NULL;
816 cache->count = kCountUnknown;
817 } else {
818 node->rightChild = TreeCheckIntegrity(cache, node->rightChild, node, context);
819 }
820 }
821
822 if (OK)
823 return node;
824 else {
825 cache->count = kCountUnknown;
826 CacheNodeFree(cache, node);
827 return NULL;
828 }
829}
830#endif // OOCACHE_PERFORM_INTEGRITY_CHECKS
831
832/***** Age list functions *****/
833
834// AgeListMakeYoungest(): place a given cache node at the youngest end of the age list.
836{
837 if (cache == NULL || node == NULL)
838 return;
839
840 AgeListRemove(cache, node);
841 node->older = cache->youngest;
842 if (NULL != cache->youngest)
843 cache->youngest->younger = node;
844 cache->youngest = node;
845 if (cache->oldest == NULL)
846 cache->oldest = node;
847}
848
849// AgeListRemove(): remove a cache node from the age-sorted tree. Does not affect its position in the splay tree.
850static void AgeListRemove(OOCacheImpl* cache, OOCacheNode* node)
851{
852 OOCacheNode* younger = NULL;
853 OOCacheNode* older = NULL;
854
855 if (node == NULL)
856 return;
857
858 younger = node->younger;
859 older = node->older;
860
861 if (cache->youngest == node)
862 cache->youngest = older;
863 if (cache->oldest == node)
864 cache->oldest = younger;
865
866 node->younger = NULL;
867 node->older = NULL;
868
869 if (younger != NULL)
870 younger->older = older;
871 if (older != NULL)
872 older->younger = younger;
873}
874
875#if OOCACHE_PERFORM_INTEGRITY_CHECKS
876
877static void AgeListCheckIntegrity(OOCacheImpl* cache, NSString* context)
878{
879 OOCacheNode *node = NULL, *next = NULL;
880 unsigned seenCount = 0;
881
882 if (cache == NULL || context == NULL)
883 return;
884
885 node = cache->youngest;
886
887 if (node)
888 for (;;) {
889 next = node->older;
890 ++seenCount;
891 if (next == NULL)
892 break;
893
894 if (next->younger != node) {
895 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): node \"%@\" has invalid older link (should be \"%@\", is \"%@\"); repairing.", context, cache->name, CacheNodeGetDescription(next), CacheNodeGetDescription(node), CacheNodeGetDescription(next->older));
896 next->older = node;
897 }
898 node = next;
899 }
900
901 if (seenCount != cache->count) {
902 // This is especially bad since this function is called just after verifying that the count field reflects the number of objects in the tree.
903 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): expected %u nodes, found %u. Cannot repair; clearing cache.", context, cache->name, cache->count, seenCount);
904
905 /* Start of temporary extra logging */
906 node = cache->youngest;
907
908 if (node) {
909 for (;;) {
910 next = node->older;
911 ++seenCount;
912 if (next == NULL)
913 break;
914
915 if (node->key != NULL) {
916 OOLog(kOOLogCacheIntegrityCheck, @"Key is: %@", node->key);
917 } else {
918 OOLog(kOOLogCacheIntegrityCheck, @"Key is: NULL");
919 }
920
921 if (node->value != NULL) {
922 OOLog(kOOLogCacheIntegrityCheck, @"Value is: %@", node->value);
923 } else {
924 OOLog(kOOLogCacheIntegrityCheck, @"Value is: NULL");
925 }
926
927 node = next;
928 }
929 }
930 /* End of temporary extra logging */
931
932 cache->count = 0;
933 CacheNodeFree(cache, cache->root);
934 cache->root = NULL;
935 cache->youngest = NULL;
936 cache->oldest = NULL;
937 return;
938 }
939
940 if (node != cache->oldest) {
941 OOLog(kOOLogCacheIntegrityCheck, @"Integrity check (%@ for \"%@\"): oldest pointer in cache is wrong (should be \"%@\", is \"%@\"); repairing.", context, cache->name, CacheNodeGetDescription(node), CacheNodeGetDescription(cache->oldest));
942 cache->oldest = node;
943 }
944}
945
946#endif // OOCACHE_PERFORM_INTEGRITY_CHECKS
947
948#if DEBUG_GRAPHVIZ
949
950/* NOTE: enabling AGE_LIST can result in graph rendering times of many hours,
951 because determining paths for non-constraint arcs is NP-hard. In particular,
952 I gave up on rendering a dump of a fairly minimal cache manager after
953 three and a half hours. Individual caches were fine.
954*/
955#define AGE_LIST 0
956
957@implementation OOCache (DebugGraphViz)
958
959- (void)appendNodesFromSubTree:(OOCacheNode*)subTree toString:(NSMutableString*)ioString
960{
961 [ioString appendFormat:@"\tn%p [label=\"<f0> | <f1> %@ | <f2>\"];\n", subTree, EscapedGraphVizString([subTree->key description])];
962
963 if (subTree->leftChild != NULL) {
964 [self appendNodesFromSubTree:subTree->leftChild toString:ioString];
965 [ioString appendFormat:@"\tn%p:f0 -> n%p:f1;\n", subTree, subTree->leftChild];
966 }
967 if (subTree->rightChild != NULL) {
968 [self appendNodesFromSubTree:subTree->rightChild toString:ioString];
969 [ioString appendFormat:@"\tn%p:f2 -> n%p:f1;\n", subTree, subTree->rightChild];
970 }
971}
972
973- (NSString*)generateGraphVizBodyWithRootNamed:(NSString*)rootName
974{
975 NSMutableString* result = nil;
976
977 result = [NSMutableString string];
978
979 // Root node representing cache
980 [result appendFormat:@"\t%@ [label=\"Cache \\\"%@\\\"\" shape=box];\n"
981 "\tnode [shape=record];\n\t\n",
982 rootName, EscapedGraphVizString([self name])];
983
984 if (cache == NULL)
985 return result;
986
987 // Cache
988 [self appendNodesFromSubTree:cache->root toString:result];
989
990 // Arc from cache object to root node
991 [result appendString:@"\tedge [color=black constraint=true];\n"];
992 [result appendFormat:@"\t%@ -> n%p:f1;\n", rootName, cache->root];
993
994#if AGE_LIST
995 OOCacheNode* node = NULL;
996 // Arcs representing age list
997 [result appendString:@"\t\n\t// Age-sorted list in blue\n\tedge [color=blue constraint=false];\n"];
998 node = cache->oldest;
999 while (node->younger != NULL) {
1000 [result appendFormat:@"\tn%p:f2 -> n%p:f0;\n", node, node->younger];
1001 node = node->younger;
1002 }
1003#endif
1004
1005 return result;
1006}
1007
1008- (NSString*)generateGraphViz
1009{
1010 NSMutableString* result = nil;
1011
1012 result = [NSMutableString string];
1013
1014 // Header
1015 [result appendFormat:
1016 @"// OOCache dump\n\n"
1017 "digraph cache\n"
1018 "{\n"
1019 "\tgraph [charset=\"UTF-8\", label=\"OOCache \"%@\" debug dump\", labelloc=t, labeljust=l];\n\t\n",
1020 [self name]];
1021
1022 [result appendString:[self generateGraphVizBodyWithRootNamed:@"cache"]];
1023
1024 [result appendString:@"}\n"];
1025
1026 return result;
1027}
1028
1029- (void)writeGraphVizToURL:(NSURL*)url
1030{
1031 NSString* graphViz = nil;
1032 NSData* data = nil;
1033
1034 graphViz = [self generateGraphViz];
1035 data = [graphViz dataUsingEncoding:NSUTF8StringEncoding];
1036
1037 if (data != nil) {
1038 [data writeToURL:url atomically:YES];
1039 }
1040}
1041
1042- (void)writeGraphVizToPath:(NSString*)path
1043{
1044 [self writeGraphVizToURL:[NSURL fileURLWithPath:path]];
1045}
1046
1047@end
1048#endif
@ kOOCacheDefaultPruneThreshold
Definition OOCache.h:50
@ kOOCacheNoPrune
Definition OOCache.h:51
@ kOOCacheMinimumPruneThreshold
Definition OOCache.h:49
static void AgeListMakeYoungest(OOCacheImpl *cache, OOCacheNode *node)
Definition OOCache.m:835
static NSString *const kSerializedEntryKeyKey
Definition OOCache.m:150
static NSString * CacheGetName(OOCacheImpl *cache)
Definition OOCache.m:529
static void CacheNodeSetValue(OOCacheNode *node, id value)
Definition OOCache.m:619
static OOCacheNode * CacheNodeAllocate(id< OOCacheComparable > key, id value)
Definition OOCache.m:569
@ kCountUnknown
Definition OOCache.m:148
static void CacheFree(OOCacheImpl *cache)
Definition OOCache.m:419
static NSArray * CacheArrayOfContentsByAge(OOCacheImpl *cache)
Definition OOCache.m:497
static unsigned CacheGetCount(OOCacheImpl *cache)
Definition OOCache.m:540
#define CHECK_INTEGRITY(context)
Definition OOCache.m:172
struct OOCacheImpl OOCacheImpl
Definition OOCache.m:122
static OOCacheNode * TreeInsert(OOCacheImpl *cache, id< OOCacheComparable > key, id value)
Definition OOCache.m:721
static NSArray * CacheArrayOfNodesByAge(OOCacheImpl *cache)
Definition OOCache.m:513
static BOOL CacheRemoveOldest(OOCacheImpl *cache, NSString *logKey)
Definition OOCache.m:471
static OOCacheImpl * CacheAllocate(void)
Definition OOCache.m:414
struct OOCacheNode OOCacheNode
Definition OOCache.m:123
static id CacheNodeGetValue(OOCacheNode *node)
Definition OOCache.m:610
static id CacheRetrieve(OOCacheImpl *cache, id key)
Definition OOCache.m:481
static void AgeListRemove(OOCacheImpl *cache, OOCacheNode *node)
Definition OOCache.m:850
static void CacheNodeFree(OOCacheImpl *cache, OOCacheNode *node)
Definition OOCache.m:586
static BOOL CacheRemove(OOCacheImpl *cache, id key)
Definition OOCache.m:444
static NSString *const kSerializedEntryKeyValue
Definition OOCache.m:151
static void CacheSetName(OOCacheImpl *cache, NSString *name)
Definition OOCache.m:534
static BOOL CacheInsert(OOCacheImpl *cache, id key, id value)
Definition OOCache.m:429
static OOCacheNode * TreeSplay(OOCacheNode **root, id< OOCacheComparable > key)
Definition OOCache.m:649
#define EXPECT_NOT(x)
#define OOLogOutdentIf(class)
Definition OOLogging.h:112
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define OOLogIndentIf(class)
Definition OOLogging.h:107
#define MAX(A, B)
Definition OOMaths.h:94
unsigned count
return nil
BOOL dirty
Definition OOCache.m:335
void dealloc()
Definition OOCache.m:185
void markClean()
Definition OOCache.m:340
NSString * name()
Definition OOCache.m:345
NSArray * objectsByAge()
Definition OOCache.m:355
id pListRepresentation()
Definition OOCache.m:235
NSString * description()
Definition OOCache.m:193
struct OOCacheImpl * cache
Definition OOCache.h:56
id initWithPList:(id pList)
Definition OOCache.m:203
void prune()
Definition OOCache.m:308
id init()
Definition OOCache.m:198
void setObject:forKey:(id value,[forKey] id key)
Definition OOCache.m:256
BOOL autoPrune
Definition OOCache.m:303
void loadFromArray:(NSArray *inArray)
Definition OOCache.m:364
unsigned pruneThreshold
Definition OOCache.m:289
unsigned count
Definition OOCache.m:132
OOCacheNode * root
Definition OOCache.m:127
OOCacheNode * youngest
Definition OOCache.m:130
NSString * name
Definition OOCache.m:133
OOCacheNode * oldest
Definition OOCache.m:130
OOCacheNode * rightChild
Definition OOCache.m:142
OOCacheNode * older
Definition OOCache.m:145
OOCacheNode * younger
Definition OOCache.m:145
id< OOCacheComparable > key
Definition OOCache.m:138
OOCacheNode * leftChild
Definition OOCache.m:142