-
Notifications
You must be signed in to change notification settings - Fork 933
/
FICImageTable.m
741 lines (583 loc) · 29.8 KB
/
FICImageTable.m
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//
// FICImageTable.m
// FastImageCache
//
// Copyright (c) 2013 Path, Inc.
// See LICENSE for full license agreement.
//
#import "FICImageTable.h"
#import "FICImageFormat.h"
#import "FICImageCache.h"
#import "FICImageTableChunk.h"
#import "FICImageTableEntry.h"
#import "FICUtilities.h"
#import "FICImageCache+FICErrorLogging.h"
#pragma mark External Definitions
NSString *const FICImageTableEntryDataVersionKey = @"FICImageTableEntryDataVersionKey";
NSString *const FICImageTableScreenScaleKey = @"FICImageTableScreenScaleKey";
#pragma mark - Internal Definitions
static NSString *const FICImageTableMetadataFileExtension = @"metadata";
static NSString *const FICImageTableFileExtension = @"imageTable";
static NSString *const FICImageTableIndexMapKey = @"indexMap";
static NSString *const FICImageTableContextMapKey = @"contextMap";
static NSString *const FICImageTableMRUArrayKey = @"mruArray";
static NSString *const FICImageTableFormatKey = @"format";
#pragma mark - Class Extension
@interface FICImageTable () {
FICImageFormat *_imageFormat;
CGFloat _screenScale;
NSInteger _imageRowLength;
NSString *_filePath;
int _fileDescriptor;
off_t _fileLength;
NSUInteger _entryCount;
NSInteger _entryLength;
NSUInteger _entriesPerChunk;
NSInteger _imageLength;
size_t _chunkLength;
NSInteger _chunkCount;
NSMutableDictionary *_chunkDictionary;
NSCountedSet *_chunkSet;
NSRecursiveLock *_lock;
CFMutableDictionaryRef _indexNumbers;
// Image table metadata
NSMutableDictionary *_indexMap; // Key: entity UUID, value: integer index into the table file
NSMutableDictionary *_sourceImageMap; // Key: entity UUID, value: source image UUID
NSMutableIndexSet *_occupiedIndexes;
NSMutableOrderedSet *_MRUEntries;
NSCountedSet *_inUseEntries;
NSDictionary *_imageFormatDictionary;
NSString *_fileDataProtectionMode;
BOOL _canAccessData;
}
@property (nonatomic, weak) FICImageCache *imageCache;
@end
#pragma mark
@implementation FICImageTable
@synthesize imageFormat =_imageFormat;
#pragma mark - Property Accessors (Public)
- (NSString *)tableFilePath {
NSString *tableFilePath = [[_imageFormat name] stringByAppendingPathExtension:FICImageTableFileExtension];
tableFilePath = [[FICImageTable directoryPath] stringByAppendingPathComponent:tableFilePath];
return tableFilePath;
}
- (NSString *)metadataFilePath {
NSString *metadataFilePath = [[_imageFormat name] stringByAppendingPathExtension:FICImageTableMetadataFileExtension];
metadataFilePath = [[FICImageTable directoryPath] stringByAppendingPathComponent:metadataFilePath];
return metadataFilePath;
}
#pragma mark - Class-Level Definitions
+ (int)pageSize {
static int __pageSize = 0;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__pageSize = getpagesize();
});
return __pageSize;
}
+ (NSString *)directoryPath {
static NSString *__directoryPath = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
__directoryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageTables"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
BOOL directoryExists = [fileManager fileExistsAtPath:__directoryPath];
if (directoryExists == NO) {
[fileManager createDirectoryAtPath:__directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
}
});
return __directoryPath;
}
#pragma mark - Object Lifecycle
- (instancetype)initWithFormat:(FICImageFormat *)imageFormat imageCache:(FICImageCache *)imageCache {
self = [super init];
if (self != nil) {
if (imageFormat == nil) {
[NSException raise:NSInvalidArgumentException format:@"*** FIC Exception: %s must pass in an image format.", __PRETTY_FUNCTION__];
}
if (imageCache == nil) {
[NSException raise:NSInvalidArgumentException format:@"*** FIC Exception: %s must pass in an image cache.", __PRETTY_FUNCTION__];
}
self.imageCache = imageCache;
_lock = [[NSRecursiveLock alloc] init];
_indexNumbers = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
_imageFormat = [imageFormat copy];
_imageFormatDictionary = [imageFormat dictionaryRepresentation];
_screenScale = [[UIScreen mainScreen] scale];
CGSize pixelSize = [_imageFormat pixelSize];
NSInteger bytesPerPixel = [_imageFormat bytesPerPixel];
_imageRowLength = (NSInteger)FICByteAlignForCoreAnimation(pixelSize.width * bytesPerPixel);
_imageLength = _imageRowLength * (NSInteger)pixelSize.height;
_chunkDictionary = [[NSMutableDictionary alloc] init];
_chunkSet = [[NSCountedSet alloc] init];
_indexMap = [[NSMutableDictionary alloc] init];
_occupiedIndexes = [[NSMutableIndexSet alloc] init];
_MRUEntries = [[NSMutableOrderedSet alloc] init];
_inUseEntries = [NSCountedSet set];
_sourceImageMap = [[NSMutableDictionary alloc] init];
_filePath = [[self tableFilePath] copy];
[self _loadMetadata];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:_filePath] == NO) {
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setValue:[_imageFormat protectionModeString] forKeyPath:NSFileProtectionKey];
[fileManager createFileAtPath:_filePath contents:nil attributes:attributes];
}
NSDictionary *attributes = [fileManager attributesOfItemAtPath:_filePath error:NULL];
_fileDataProtectionMode = [attributes objectForKey:NSFileProtectionKey];
_fileDescriptor = open([_filePath fileSystemRepresentation], O_RDWR | O_CREAT, 0666);
if (_fileDescriptor >= 0) {
// The size of each entry in the table needs to be page-aligned. This will cause each entry to have a page-aligned base
// address, which will help us avoid Core Animation having to copy our images when we eventually set them on layers.
_entryLength = (NSInteger)FICByteAlign(_imageLength + sizeof(FICImageTableEntryMetadata), [FICImageTable pageSize]);
// Each chunk will map in n entries. Try to keep the chunkLength around 2MB.
NSInteger goalChunkLength = 2 * (1024 * 1024);
NSInteger goalEntriesPerChunk = goalChunkLength / _entryLength;
_entriesPerChunk = MAX(4, goalEntriesPerChunk);
if ([self _maximumCount] > [_imageFormat maximumCount]) {
NSString *message = [NSString stringWithFormat:@"*** FIC Warning: growing desired maximumCount (%ld) for format %@ to fill a chunk (%d)", (long)[_imageFormat maximumCount], [_imageFormat name], [self _maximumCount]];
[self.imageCache _logMessage:message];
}
_chunkLength = (size_t)(_entryLength * _entriesPerChunk);
_fileLength = lseek(_fileDescriptor, 0, SEEK_END);
_entryCount = (NSInteger)(_fileLength / _entryLength);
_chunkCount = (_entryCount + _entriesPerChunk - 1) / _entriesPerChunk;
if ([_indexMap count] > _entryCount) {
// It's possible that someone deleted the image table file but left behind the metadata file. If this happens, the metadata
// will obviously become out of sync with the image table file, so we need to reset the image table.
[self reset];
}
} else {
// If something goes wrong and we can't open the image table file, then we have no choice but to release and nil self.
NSString *message = [NSString stringWithFormat:@"*** FIC Error: %s could not open the image table file at path %@. The image table was not created.", __PRETTY_FUNCTION__, _filePath];
[self.imageCache _logMessage:message];
self = nil;
}
}
return self;
}
- (instancetype)init {
return [self initWithFormat:nil imageCache:nil];
}
- (void)dealloc {
if (_fileDescriptor >= 0) {
close(_fileDescriptor);
}
}
#pragma mark - Working with Chunks
- (FICImageTableChunk *)_cachedChunkAtIndex:(NSInteger)index {
return [_chunkDictionary objectForKey:@(index)];
}
- (void)_setChunk:(FICImageTableChunk *)chunk index:(NSInteger)index {
NSNumber *indexNumber = @(index);
if (chunk != nil) {
[_chunkDictionary setObject:chunk forKey:indexNumber];
} else {
[_chunkDictionary removeObjectForKey:indexNumber];
}
}
- (FICImageTableChunk *)_chunkAtIndex:(NSInteger)index {
FICImageTableChunk *chunk = nil;
if (index < _chunkCount) {
chunk = [self _cachedChunkAtIndex:index];
if (chunk == nil) {
size_t chunkLength = _chunkLength;
off_t chunkOffset = index * (off_t)_chunkLength;
if (chunkOffset + chunkLength > _fileLength) {
chunkLength = (size_t)(_fileLength - chunkOffset);
}
chunk = [[FICImageTableChunk alloc] initWithFileDescriptor:_fileDescriptor index:index length:chunkLength];
[self _setChunk:chunk index:index];
}
}
if (!chunk) {
NSString *message = [NSString stringWithFormat:@"*** FIC Error: %s failed to get chunk for index %ld.", __PRETTY_FUNCTION__, (long)index];
[self.imageCache _logMessage:message];
}
return chunk;
}
#pragma mark - Storing, Retrieving, and Deleting Entries
- (void)setEntryForEntityUUID:(NSString *)entityUUID sourceImageUUID:(NSString *)sourceImageUUID imageDrawingBlock:(FICEntityImageDrawingBlock)imageDrawingBlock {
if (entityUUID != nil && sourceImageUUID != nil && imageDrawingBlock != NULL) {
[_lock lock];
NSInteger newEntryIndex = [self _indexOfEntryForEntityUUID:entityUUID];
if (newEntryIndex == NSNotFound) {
newEntryIndex = [self _nextEntryIndex];
if (newEntryIndex >= _entryCount) {
// Determine how many chunks we need to support new entry index.
// Number of entries should always be a multiple of _entriesPerChunk
NSInteger numberOfEntriesRequired = newEntryIndex + 1;
NSInteger newChunkCount = _entriesPerChunk > 0 ? ((numberOfEntriesRequired + _entriesPerChunk - 1) / _entriesPerChunk) : 0;
NSInteger newEntryCount = newChunkCount * _entriesPerChunk;
[self _setEntryCount:newEntryCount];
}
}
if (newEntryIndex < _entryCount) {
CGSize pixelSize = [_imageFormat pixelSize];
CGBitmapInfo bitmapInfo = [_imageFormat bitmapInfo];
CGColorSpaceRef colorSpace = [_imageFormat isGrayscale] ? CGColorSpaceCreateDeviceGray() : CGColorSpaceCreateDeviceRGB();
NSInteger bitsPerComponent = [_imageFormat bitsPerComponent];
// Create context whose backing store *is* the mapped file data
FICImageTableEntry *entryData = [self _entryDataAtIndex:newEntryIndex];
if (entryData != nil) {
[entryData setEntityUUIDBytes:FICUUIDBytesWithString(entityUUID)];
[entryData setSourceImageUUIDBytes:FICUUIDBytesWithString(sourceImageUUID)];
// Update our book-keeping
[_indexMap setObject:[NSNumber numberWithUnsignedInteger:newEntryIndex] forKey:entityUUID];
[_occupiedIndexes addIndex:newEntryIndex];
[_sourceImageMap setObject:sourceImageUUID forKey:entityUUID];
// Update MRU array
[self _entryWasAccessedWithEntityUUID:entityUUID];
[self saveMetadata];
// Unique, unchanging pointer for this entry's index
NSNumber *indexNumber = [self _numberForEntryAtIndex:newEntryIndex];
// Relinquish the image table lock before calling potentially slow imageDrawingBlock to unblock other FIC operations
[_lock unlock];
CGContextRef context = CGBitmapContextCreate([entryData bytes], pixelSize.width, pixelSize.height, bitsPerComponent, _imageRowLength, colorSpace, bitmapInfo);
CGContextTranslateCTM(context, 0, pixelSize.height);
CGContextScaleCTM(context, _screenScale, -_screenScale);
@synchronized(indexNumber) {
// Call drawing block to allow client to draw into the context
imageDrawingBlock(context, [_imageFormat imageSize]);
CGContextRelease(context);
// Write the data back to the filesystem
[entryData flush];
}
} else {
[_lock unlock];
}
CGColorSpaceRelease(colorSpace);
} else {
[_lock unlock];
}
}
}
- (UIImage *)newImageForEntityUUID:(NSString *)entityUUID sourceImageUUID:(NSString *)sourceImageUUID preheatData:(BOOL)preheatData {
UIImage *image = nil;
if (entityUUID != nil && sourceImageUUID != nil) {
[_lock lock];
FICImageTableEntry *entryData = [self _entryDataForEntityUUID:entityUUID];
if (entryData != nil) {
NSString *entryEntityUUID = FICStringWithUUIDBytes([entryData entityUUIDBytes]);
NSString *entrySourceImageUUID = FICStringWithUUIDBytes([entryData sourceImageUUIDBytes]);
BOOL entityUUIDIsCorrect = entityUUID == nil || [entityUUID isEqualToString:entryEntityUUID];
BOOL sourceImageUUIDIsCorrect = sourceImageUUID == nil || [sourceImageUUID isEqualToString:entrySourceImageUUID];
NSNumber *indexNumber = [self _numberForEntryAtIndex:[entryData index]];
@synchronized(indexNumber) {
if (entityUUIDIsCorrect == NO || sourceImageUUIDIsCorrect == NO) {
// The UUIDs don't match, so we need to invalidate the entry.
[self deleteEntryForEntityUUID:entityUUID];
} else {
[self _entryWasAccessedWithEntityUUID:entityUUID];
// Create CGImageRef whose backing store *is* the mapped image table entry. We avoid a memcpy this way.
CGDataProviderRef dataProvider = CGDataProviderCreateWithData((__bridge_retained void *)entryData, [entryData bytes], [entryData imageLength], _FICReleaseImageData);
[_inUseEntries addObject:entityUUID];
__weak FICImageTable *weakSelf = self;
[entryData executeBlockOnDealloc:^{
[weakSelf removeInUseForEntityUUID:entityUUID];
}];
CGSize pixelSize = [_imageFormat pixelSize];
CGBitmapInfo bitmapInfo = [_imageFormat bitmapInfo];
NSInteger bitsPerComponent = [_imageFormat bitsPerComponent];
NSInteger bitsPerPixel = [_imageFormat bytesPerPixel] * 8;
CGColorSpaceRef colorSpace = [_imageFormat isGrayscale] ? CGColorSpaceCreateDeviceGray() : CGColorSpaceCreateDeviceRGB();
CGImageRef imageRef = CGImageCreate(pixelSize.width, pixelSize.height, bitsPerComponent, bitsPerPixel, _imageRowLength, colorSpace, bitmapInfo, dataProvider, NULL, false, (CGColorRenderingIntent)0);
CGDataProviderRelease(dataProvider);
CGColorSpaceRelease(colorSpace);
if (imageRef != NULL) {
image = [[UIImage alloc] initWithCGImage:imageRef scale:_screenScale orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
} else {
NSString *message = [NSString stringWithFormat:@"*** FIC Error: %s could not create a new CGImageRef for entity UUID %@.", __PRETTY_FUNCTION__, entityUUID];
[self.imageCache _logMessage:message];
}
if (image != nil && preheatData) {
[entryData preheat];
}
}
}
}
[_lock unlock];
}
return image;
}
static void _FICReleaseImageData(void *info, const void *data, size_t size) {
if (info) {
CFRelease(info);
}
}
- (void)removeInUseForEntityUUID:(NSString *)entityUUID {
[_lock lock];
[_inUseEntries removeObject:entityUUID];
[_lock unlock];
}
- (void)deleteEntryForEntityUUID:(NSString *)entityUUID {
if (entityUUID != nil) {
[_lock lock];
NSInteger index = [self _indexOfEntryForEntityUUID:entityUUID];
if (index != NSNotFound) {
[_sourceImageMap removeObjectForKey:entityUUID];
[_indexMap removeObjectForKey:entityUUID];
[_occupiedIndexes removeIndex:index];
NSInteger index = [_MRUEntries indexOfObject:entityUUID];
if (index != NSNotFound) {
[_MRUEntries removeObjectAtIndex:index];
}
[self saveMetadata];
}
[_lock unlock];
}
}
#pragma mark - Checking for Entry Existence
- (BOOL)entryExistsForEntityUUID:(NSString *)entityUUID sourceImageUUID:(NSString *)sourceImageUUID {
BOOL imageExists = NO;
[_lock lock];
FICImageTableEntry *entryData = [self _entryDataForEntityUUID:entityUUID];
if (entryData != nil && sourceImageUUID != nil) {
NSString *existingEntityUUID = FICStringWithUUIDBytes([entryData entityUUIDBytes]);
BOOL entityUUIDIsCorrect = [entityUUID isEqualToString:existingEntityUUID];
NSString *existingSourceImageUUID = FICStringWithUUIDBytes([entryData sourceImageUUIDBytes]);
BOOL sourceImageUUIDIsCorrect = [sourceImageUUID isEqualToString:existingSourceImageUUID];
if (entityUUIDIsCorrect == NO || sourceImageUUIDIsCorrect == NO) {
// The source image UUIDs don't match, so the image data should be deleted for this entity.
[self deleteEntryForEntityUUID:entityUUID];
entryData = nil;
}
}
[_lock unlock];
imageExists = entryData != nil;
return imageExists;
}
#pragma mark - Working with Entries
- (int)_maximumCount {
return (int)MAX([_imageFormat maximumCount], _entriesPerChunk);
}
- (void)_setEntryCount:(NSInteger)entryCount {
if (entryCount != _entryCount) {
off_t fileLength = entryCount * _entryLength;
int result = ftruncate(_fileDescriptor, fileLength);
if (result != 0) {
NSString *message = [NSString stringWithFormat:@"*** FIC Error: %s ftruncate returned %d, error = %d, fd = %d, filePath = %@, length = %lld", __PRETTY_FUNCTION__, result, errno, _fileDescriptor, _filePath, fileLength];
[self.imageCache _logMessage:message];
} else {
_fileLength = fileLength;
_entryCount = entryCount;
_chunkCount = _entriesPerChunk > 0 ? ((_entryCount + _entriesPerChunk - 1) / _entriesPerChunk) : 0;
NSDictionary *chunkDictionary = [_chunkDictionary copy];
for (FICImageTableChunk *chunk in [chunkDictionary allValues]) {
if ([chunk length] != _chunkLength) {
// Issue 31: https://github.com/path/FastImageCache/issues/31
// Somehow, we have a partial chunk whose length needs to be adjusted
// since we changed our file length.
[self _setChunk:nil index:[chunk index]];
}
}
}
}
}
// There's inherently a race condition between when you ask whether the data is
// accessible and when you try to use that data. Sidestep this issue altogether
// by using NSFileProtectionNone
- (BOOL)canAccessEntryData {
BOOL result = YES;
if ([_fileDataProtectionMode isEqualToString:NSFileProtectionComplete]) {
result = [[UIApplication sharedApplication] isProtectedDataAvailable];
} else if ([_fileDataProtectionMode isEqualToString:NSFileProtectionCompleteUntilFirstUserAuthentication]) {
// For "complete until first auth", if we were previously able to access data, then we'll still be able to
// access it. If we haven't yet been able to access data, we'll need to try until we are successful.
if (_canAccessData == NO) {
if ([[UIApplication sharedApplication] isProtectedDataAvailable]) {
// we are unlocked, so we're good to go.
_canAccessData = YES;
} else {
// we are locked, so try to access data.
_canAccessData = [NSData dataWithContentsOfMappedFile:_filePath] != nil;
}
}
}
return result;
}
- (FICImageTableEntry *)_entryDataAtIndex:(NSInteger)index {
FICImageTableEntry *entryData = nil;
[_lock lock];
BOOL canAccessData = [self canAccessEntryData];
if (index < _entryCount && canAccessData) {
off_t entryOffset = index * _entryLength;
size_t chunkIndex = (size_t)(entryOffset / _chunkLength);
FICImageTableChunk *chunk = [self _chunkAtIndex:chunkIndex];
if (chunk != nil) {
off_t chunkOffset = chunkIndex * _chunkLength;
off_t entryOffsetInChunk = entryOffset - chunkOffset;
void *mappedChunkAddress = [chunk bytes];
void *mappedEntryAddress = mappedChunkAddress + entryOffsetInChunk;
entryData = [[FICImageTableEntry alloc] initWithImageTableChunk:chunk bytes:mappedEntryAddress length:_entryLength];
if (entryData) {
[entryData setImageCache:self.imageCache];
[entryData setIndex:index];
[_chunkSet addObject:chunk];
__weak FICImageTable *weakSelf = self;
[entryData executeBlockOnDealloc:^{
[weakSelf _entryWasDeallocatedFromChunk:chunk];
}];
}
}
}
[_lock unlock];
if (!entryData) {
NSString *message = nil;
if (canAccessData) {
message = [NSString stringWithFormat:@"*** FIC Error: %s failed to get entry for index %ld.", __PRETTY_FUNCTION__, (long)index];
} else {
message = [NSString stringWithFormat:@"*** FIC Error: %s. Cannot get entry data because imageTable's file has data protection enabled and that data is not currently accessible.", __PRETTY_FUNCTION__];
}
[self.imageCache _logMessage:message];
}
return entryData;
}
- (void)_entryWasDeallocatedFromChunk:(FICImageTableChunk *)chunk {
[_lock lock];
[_chunkSet removeObject:chunk];
if ([_chunkSet countForObject:chunk] == 0) {
[self _setChunk:nil index:[chunk index]];
}
[_lock unlock];
}
- (NSInteger)_nextEntryIndex {
NSMutableIndexSet *unoccupiedIndexes = [[NSMutableIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, _entryCount)];
[unoccupiedIndexes removeIndexes:_occupiedIndexes];
NSInteger index = [unoccupiedIndexes firstIndex];
if (index == NSNotFound) {
index = _entryCount;
}
if (index >= [self _maximumCount] && [_MRUEntries count]) {
// Evict the oldest/least-recently accessed entry here
NSString *oldestEvictableEntityUUID = [self oldestEvictableEntityUUID];
if (oldestEvictableEntityUUID) {
[self deleteEntryForEntityUUID:oldestEvictableEntityUUID];
index = [self _nextEntryIndex];
}
}
if (index >= [self _maximumCount]) {
NSString *message = [NSString stringWithFormat:@"FICImageTable - unable to evict entry from table '%@' to make room. New index %ld, desired max %d", [_imageFormat name], (long)index, [self _maximumCount]];
[self.imageCache _logMessage:message];
}
return index;
}
- (NSString *)oldestEvictableEntityUUID {
NSString *uuid = nil;
for (NSInteger i = [_MRUEntries count] - 1; i >= 0; i--) {
NSString *candidateUUID = [_MRUEntries objectAtIndex:i];
if (![_inUseEntries containsObject:candidateUUID]) {
uuid = candidateUUID;
break;
}
}
return uuid;
}
- (NSInteger)_indexOfEntryForEntityUUID:(NSString *)entityUUID {
NSInteger index = NSNotFound;
if (_indexMap != nil && entityUUID != nil) {
NSNumber *indexNumber = [_indexMap objectForKey:entityUUID];
index = indexNumber ? [indexNumber integerValue] : NSNotFound;
if (index != NSNotFound && index >= _entryCount) {
[_indexMap removeObjectForKey:entityUUID];
[_occupiedIndexes removeIndex:index];
[_sourceImageMap removeObjectForKey:entityUUID];
index = NSNotFound;
}
}
return index;
}
- (FICImageTableEntry *)_entryDataForEntityUUID:(NSString *)entityUUID {
FICImageTableEntry *entryData = nil;
NSInteger index = [self _indexOfEntryForEntityUUID:entityUUID];
if (index != NSNotFound) {
entryData = [self _entryDataAtIndex:index];
}
return entryData;
}
- (void)_entryWasAccessedWithEntityUUID:(NSString *)entityUUID {
// Update MRU array
NSInteger index = [_MRUEntries indexOfObject:entityUUID];
if (index == NSNotFound) {
[_MRUEntries insertObject:entityUUID atIndex:0];
} else if (index != 0) {
[_MRUEntries removeObjectAtIndex:index];
[_MRUEntries insertObject:entityUUID atIndex:0];
}
}
// Unchanging pointer value for a given entry index to synchronize on
- (NSNumber *)_numberForEntryAtIndex:(NSInteger)index {
NSNumber *resultNumber = (__bridge id)CFDictionaryGetValue(_indexNumbers, (const void *)index);
if (!resultNumber) {
resultNumber = [NSNumber numberWithInteger:index];
CFDictionarySetValue(_indexNumbers, (const void *)index, (__bridge void *)resultNumber);
}
return resultNumber;
}
#pragma mark - Working with Metadata
- (void)saveMetadata {
[_lock lock];
NSDictionary *metadataDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[_indexMap copy], FICImageTableIndexMapKey,
[_sourceImageMap copy], FICImageTableContextMapKey,
[[_MRUEntries array] copy], FICImageTableMRUArrayKey,
[_imageFormatDictionary copy], FICImageTableFormatKey, nil];
[_lock unlock];
static dispatch_queue_t __metadataQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__metadataQueue = dispatch_queue_create("com.path.FastImageCache.ImageTableMetadataQueue", NULL);
});
dispatch_async(__metadataQueue, ^{
NSData *data = [NSPropertyListSerialization dataWithPropertyList:metadataDictionary format:NSPropertyListBinaryFormat_v1_0 options:0 error:NULL];
BOOL fileWriteResult = [data writeToFile:[self metadataFilePath] atomically:NO];
if (fileWriteResult == NO) {
NSString *message = [NSString stringWithFormat:@"*** FIC Error: %s couldn't write metadata for format %@", __PRETTY_FUNCTION__, [_imageFormat name]];
[self.imageCache _logMessage:message];
}
});
}
- (void)_loadMetadata {
NSString *metadataFilePath = [[_filePath stringByDeletingPathExtension] stringByAppendingPathExtension:FICImageTableMetadataFileExtension];
NSData *metadataData = [NSData dataWithContentsOfMappedFile:metadataFilePath];
if (metadataData != nil) {
NSDictionary *metadataDictionary = (NSDictionary *)[NSPropertyListSerialization propertyListWithData:metadataData options:0 format:NULL error:NULL];
NSDictionary *formatDictionary = [metadataDictionary objectForKey:FICImageTableFormatKey];
if ([formatDictionary isEqualToDictionary:_imageFormatDictionary] == NO) {
// Something about this image format has changed, so the existing metadata is no longer valid. The image table file
// must be deleted and recreated.
[[NSFileManager defaultManager] removeItemAtPath:_filePath error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:metadataFilePath error:NULL];
metadataDictionary = nil;
NSString *message = [NSString stringWithFormat:@"*** FIC Notice: Image format %@ has changed; deleting data and starting over.", [_imageFormat name]];
[self.imageCache _logMessage:message];
}
[_indexMap setDictionary:[metadataDictionary objectForKey:FICImageTableIndexMapKey]];
for (NSNumber *index in [_indexMap allValues]) {
[_occupiedIndexes addIndex:[index intValue]];
}
[_sourceImageMap setDictionary:[metadataDictionary objectForKey:FICImageTableContextMapKey]];
[_MRUEntries removeAllObjects];
NSArray *mruArray = [metadataDictionary objectForKey:FICImageTableMRUArrayKey];
if (mruArray) {
[_MRUEntries addObjectsFromArray:mruArray];
}
}
}
#pragma mark - Resetting the Image Table
- (void)reset {
[_lock lock];
[_indexMap removeAllObjects];
[_occupiedIndexes removeAllIndexes];
[_inUseEntries removeAllObjects];
[_MRUEntries removeAllObjects];
[_sourceImageMap removeAllObjects];
[_chunkDictionary removeAllObjects];
[_chunkSet removeAllObjects];
[self _setEntryCount:0];
[self saveMetadata];
[_lock unlock];
}
@end