/ NSSharedKeySet.m
NSSharedKeySet.m
1 // 2 // NSSharedKeySet.m 3 // CoreFoundation 4 // 5 // Copyright (c) 2014 Apportable. All rights reserved. 6 // 7 8 #import "NSSharedKeySet.h" 9 10 11 @implementation NSSharedKeySet 12 13 + (id)keySetWithKeys:(NSArray *)keyArray 14 { 15 NSUInteger count = [keyArray count]; 16 id *keys = malloc(sizeof(id) * count); 17 [keyArray getObjects:keys range:NSMakeRange(0, count)]; 18 NSSharedKeySet *keySet = [[NSSharedKeySet alloc] initWithKeys:keys count:count]; 19 free(keys); 20 return [keySet autorelease]; 21 } 22 23 - (id)init 24 { 25 return [self initWithKeys:NULL count:0]; 26 } 27 28 - (id)initWithKeys:(id *)keys count:(NSUInteger)count 29 { 30 self = [super init]; 31 32 if (self) 33 { 34 if (count == 0) 35 { 36 _keys = malloc(sizeof(id) * 1); 37 } 38 else 39 { 40 _keys = malloc(sizeof(id) * count); 41 } 42 43 for (int i = 0; i < count; i++) 44 { 45 _keys[i] = [keys[i] retain]; 46 } 47 48 _numKey = count; 49 } 50 51 return self; 52 } 53 54 - (void)dealloc 55 { 56 if (_keys != NULL) 57 { 58 free(_keys); 59 } 60 61 [super dealloc]; 62 } 63 64 - (id)copyWithZone:(NSZone *)zone 65 { 66 return [self retain]; 67 } 68 69 - (NSUInteger)keySetCount 70 { 71 if (_subSharedKeySet) 72 { 73 return [_subSharedKeySet keySetCount] + 1; 74 } 75 else 76 { 77 return 0; 78 } 79 } 80 81 - (NSUInteger)count 82 { 83 return _numKey; 84 } 85 86 - (NSUInteger)maximumIndex 87 { 88 return [self count] - 1; 89 } 90 91 - (BOOL)isEmpty 92 { 93 return _numKey == 0; 94 } 95 96 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len 97 { 98 if (state->state == _numKey) 99 { 100 return 0; 101 } 102 103 if (state->extra[0] == 0) 104 { 105 state->extra[0] = _numKey; 106 } 107 108 NSUInteger num = 0; 109 NSUInteger curr = state->state; 110 111 while (num < len && curr < _numKey) 112 { 113 buffer[num] = _keys[curr]; 114 num++; 115 curr++; 116 } 117 118 state->state = curr; 119 state->itemsPtr = buffer; 120 121 state->mutationsPtr = &state->extra[0]; 122 return num; 123 } 124 125 - (id)keyAtIndex:(NSUInteger)index 126 { 127 return _keys[index]; 128 } 129 130 - (NSArray*)allKeys 131 { 132 return [NSArray arrayWithObjects:_keys count:_numKey]; 133 } 134 135 - (NSUInteger)indexForKey:(id)key 136 { 137 for (NSUInteger i = 0; i < _numKey; i++) 138 { 139 if (_keys[i] == key) 140 { 141 return i; 142 } 143 144 if ([_keys[i] isEqual:key]) 145 { 146 return i; 147 } 148 } 149 150 return NSNotFound; 151 } 152 153 @end