FSTTreeSortedDictionary.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. #import "Firestore/third_party/Immutable/FSTTreeSortedDictionary.h"
  2. #import "Firestore/third_party/Immutable/FSTLLRBEmptyNode.h"
  3. #import "Firestore/third_party/Immutable/FSTLLRBValueNode.h"
  4. #import "Firestore/third_party/Immutable/FSTTreeSortedDictionaryEnumerator.h"
  5. NS_ASSUME_NONNULL_BEGIN
  6. @interface FSTTreeSortedDictionary ()
  7. - (FSTTreeSortedDictionary *)dictionaryBySettingObject:(id)aValue forKey:(id)aKey;
  8. @property(nonatomic, strong) id<FSTLLRBNode> root;
  9. @property(nonatomic, copy, readwrite) NSComparator comparator;
  10. @end
  11. @implementation FSTTreeSortedDictionary
  12. + (FSTTreeSortedDictionary *)dictionaryWithDictionary:(NSDictionary *)dictionary
  13. comparator:(NSComparator)comparator {
  14. __block FSTTreeSortedDictionary *dict =
  15. [[FSTTreeSortedDictionary alloc] initWithComparator:comparator];
  16. [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  17. dict = [dict dictionaryBySettingObject:obj forKey:key];
  18. }];
  19. return dict;
  20. }
  21. - (id)initWithComparator:(NSComparator)aComparator {
  22. return [self initWithComparator:aComparator withRoot:[FSTLLRBEmptyNode emptyNode]];
  23. }
  24. // Designated initializer.
  25. - (id)initWithComparator:(NSComparator)aComparator withRoot:(id<FSTLLRBNode>)aRoot {
  26. self = [super init];
  27. if (self) {
  28. self.root = aRoot;
  29. self.comparator = aComparator;
  30. }
  31. return self;
  32. }
  33. /**
  34. * Returns a copy of the map, with the specified key/value added or replaced.
  35. */
  36. - (FSTTreeSortedDictionary *)dictionaryBySettingObject:(id)aValue forKey:(id)aKey {
  37. return [[FSTTreeSortedDictionary alloc]
  38. initWithComparator:self.comparator
  39. withRoot:[[self.root insertKey:aKey forValue:aValue withComparator:self.comparator]
  40. copyWith:nil
  41. withValue:nil
  42. withColor:FSTLLRBColorBlack
  43. withLeft:nil
  44. withRight:nil]];
  45. }
  46. - (FSTTreeSortedDictionary *)dictionaryByRemovingObjectForKey:(id)aKey {
  47. // Remove is somewhat expensive even if the key doesn't exist (the tree does rebalancing and
  48. // stuff). So avoid it.
  49. if (![self containsKey:aKey]) {
  50. return self;
  51. } else {
  52. return [[FSTTreeSortedDictionary alloc]
  53. initWithComparator:self.comparator
  54. withRoot:[[self.root remove:aKey withComparator:self.comparator]
  55. copyWith:nil
  56. withValue:nil
  57. withColor:FSTLLRBColorBlack
  58. withLeft:nil
  59. withRight:nil]];
  60. }
  61. }
  62. - (nullable id)objectForKey:(id)key {
  63. NSComparisonResult cmp;
  64. id<FSTLLRBNode> node = self.root;
  65. while (![node isEmpty]) {
  66. cmp = self.comparator(key, node.key);
  67. if (cmp == NSOrderedSame) {
  68. return node.value;
  69. } else if (cmp == NSOrderedAscending) {
  70. node = node.left;
  71. } else {
  72. node = node.right;
  73. }
  74. }
  75. return nil;
  76. }
  77. - (NSUInteger)indexOfKey:(id)key {
  78. NSUInteger prunedNodes = 0;
  79. id<FSTLLRBNode> node = self.root;
  80. while (![node isEmpty]) {
  81. NSComparisonResult cmp = self.comparator(key, node.key);
  82. if (cmp == NSOrderedSame) {
  83. return prunedNodes + node.left.count;
  84. } else if (cmp == NSOrderedAscending) {
  85. node = node.left;
  86. } else if (cmp == NSOrderedDescending) {
  87. prunedNodes += node.left.count + 1;
  88. node = node.right;
  89. }
  90. }
  91. return NSNotFound;
  92. }
  93. - (BOOL)isEmpty {
  94. return [self.root isEmpty];
  95. }
  96. - (NSUInteger)count {
  97. return [self.root count];
  98. }
  99. - (id)minKey {
  100. return [self.root minKey];
  101. }
  102. - (id)maxKey {
  103. return [self.root maxKey];
  104. }
  105. - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id, id, BOOL *))block {
  106. [self enumerateKeysAndObjectsReverse:NO usingBlock:block];
  107. }
  108. - (void)enumerateKeysAndObjectsReverse:(BOOL)reverse usingBlock:(void (^)(id, id, BOOL *))block {
  109. if (reverse) {
  110. __block BOOL stop = NO;
  111. [self.root reverseTraversal:^BOOL(id key, id value) {
  112. block(key, value, &stop);
  113. return stop;
  114. }];
  115. } else {
  116. __block BOOL stop = NO;
  117. [self.root inorderTraversal:^BOOL(id key, id value) {
  118. block(key, value, &stop);
  119. return stop;
  120. }];
  121. }
  122. }
  123. - (BOOL)containsKey:(id)key {
  124. return ([self objectForKey:key] != nil);
  125. }
  126. - (NSEnumerator *)keyEnumerator {
  127. return [[FSTTreeSortedDictionaryEnumerator alloc] initWithImmutableSortedDictionary:self
  128. startKey:nil
  129. endKey:nil
  130. isReverse:NO];
  131. }
  132. - (NSEnumerator *)keyEnumeratorFrom:(id)startKey {
  133. return [[FSTTreeSortedDictionaryEnumerator alloc] initWithImmutableSortedDictionary:self
  134. startKey:startKey
  135. endKey:nil
  136. isReverse:NO];
  137. }
  138. - (NSEnumerator *)keyEnumeratorFrom:(id)startKey to:(nullable id)endKey {
  139. return [[FSTTreeSortedDictionaryEnumerator alloc] initWithImmutableSortedDictionary:self
  140. startKey:startKey
  141. endKey:endKey
  142. isReverse:NO];
  143. }
  144. - (NSEnumerator *)reverseKeyEnumerator {
  145. return [[FSTTreeSortedDictionaryEnumerator alloc] initWithImmutableSortedDictionary:self
  146. startKey:nil
  147. endKey:nil
  148. isReverse:YES];
  149. }
  150. - (NSEnumerator *)reverseKeyEnumeratorFrom:(id)startKey {
  151. return [[FSTTreeSortedDictionaryEnumerator alloc] initWithImmutableSortedDictionary:self
  152. startKey:startKey
  153. endKey:nil
  154. isReverse:YES];
  155. }
  156. #pragma mark -
  157. #pragma mark Tree Builder
  158. // Code to efficiently build a red black tree.
  159. typedef struct {
  160. unsigned int bits;
  161. unsigned short count;
  162. unsigned short current;
  163. } Base12List;
  164. unsigned int LogBase2(unsigned int num) {
  165. return (unsigned int)(log(num) / log(2));
  166. }
  167. /**
  168. * Works like an iterator, so it moves to the next bit. Do not call more than list->count times.
  169. * @return whether or not the next bit is a 1 in base {1,2}.
  170. */
  171. BOOL Base12ListNext(Base12List *list) {
  172. BOOL result = !(list->bits & (0x1 << list->current));
  173. list->current--;
  174. return result;
  175. }
  176. static inline unsigned BitMask(int x) {
  177. return ((size_t)x >= sizeof(unsigned) * CHAR_BIT) ? (unsigned)-1 : (1U << x) - 1;
  178. }
  179. /**
  180. * We represent the base{1,2} number as the combination of a binary number and a number of bits that
  181. * we care about. We iterate backwards, from most significant bit to least, to build up the llrb
  182. * nodes. 0 base 2 => 1 base {1,2}, 1 base 2 => 2 base {1,2}
  183. */
  184. Base12List *NewBase12List(unsigned int length) {
  185. size_t sz = sizeof(Base12List);
  186. Base12List *list = calloc(1, sz);
  187. // Calculate the number of bits that we care about
  188. list->count = (unsigned short)LogBase2(length + 1);
  189. unsigned int mask = BitMask(list->count);
  190. list->bits = (length + 1) & mask;
  191. list->current = list->count - 1;
  192. return list;
  193. }
  194. void FreeBase12List(Base12List *list) {
  195. free(list);
  196. }
  197. + (nullable id<FSTLLRBNode>)buildBalancedTree:(NSArray *)keys
  198. dictionary:(NSDictionary *)dictionary
  199. subArrayStartIndex:(NSUInteger)startIndex
  200. length:(NSUInteger)length {
  201. length = MIN(keys.count - startIndex, length); // Bound length by the actual length of the array
  202. if (length == 0) {
  203. return nil;
  204. } else if (length == 1) {
  205. id key = keys[startIndex];
  206. return [[FSTLLRBValueNode alloc] initWithKey:key
  207. withValue:dictionary[key]
  208. withColor:FSTLLRBColorBlack
  209. withLeft:nil
  210. withRight:nil];
  211. } else {
  212. NSUInteger middle = length / 2;
  213. id<FSTLLRBNode> left = [FSTTreeSortedDictionary buildBalancedTree:keys
  214. dictionary:dictionary
  215. subArrayStartIndex:startIndex
  216. length:middle];
  217. id<FSTLLRBNode> right = [FSTTreeSortedDictionary buildBalancedTree:keys
  218. dictionary:dictionary
  219. subArrayStartIndex:(startIndex + middle + 1)
  220. length:middle];
  221. id key = keys[startIndex + middle];
  222. return [[FSTLLRBValueNode alloc] initWithKey:key
  223. withValue:dictionary[key]
  224. withColor:FSTLLRBColorBlack
  225. withLeft:left
  226. withRight:right];
  227. }
  228. }
  229. + (nullable id<FSTLLRBNode>)rootFrom12List:(Base12List *)base12List
  230. keyList:(NSArray *)keyList
  231. dictionary:(NSDictionary *)dictionary {
  232. __block FSTLLRBValueNode *root = nil;
  233. __block FSTLLRBValueNode *node = nil;
  234. __block NSUInteger index = keyList.count;
  235. void (^buildPennant)(FSTLLRBColor, NSUInteger) = ^(FSTLLRBColor color, NSUInteger chunkSize) {
  236. NSUInteger startIndex = index - chunkSize + 1;
  237. index -= chunkSize;
  238. id key = keyList[index];
  239. FSTLLRBValueNode *childTree = [self buildBalancedTree:keyList
  240. dictionary:dictionary
  241. subArrayStartIndex:startIndex
  242. length:(chunkSize - 1)];
  243. FSTLLRBValueNode *pennant = [[FSTLLRBValueNode alloc] initWithKey:key
  244. withValue:dictionary[key]
  245. withColor:color
  246. withLeft:nil
  247. withRight:childTree];
  248. if (node) {
  249. // This is the only place this property is set.
  250. node.left = pennant;
  251. node = pennant;
  252. } else {
  253. root = pennant;
  254. node = pennant;
  255. }
  256. };
  257. for (int i = 0; i < base12List->count; ++i) {
  258. BOOL isOne = Base12ListNext(base12List);
  259. NSUInteger chunkSize = (NSUInteger)pow(2.0, base12List->count - (i + 1));
  260. if (isOne) {
  261. buildPennant(FSTLLRBColorBlack, chunkSize);
  262. } else {
  263. buildPennant(FSTLLRBColorBlack, chunkSize);
  264. buildPennant(FSTLLRBColorRed, chunkSize);
  265. }
  266. }
  267. return root;
  268. }
  269. /**
  270. * Uses the algorithm linked here:
  271. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  272. */
  273. + (FSTImmutableSortedDictionary *)fromDictionary:(NSDictionary *)dictionary
  274. withComparator:(NSComparator)comparator {
  275. // Steps:
  276. // 0. Sort the array
  277. // 1. Calculate the 1-2 number
  278. // 2. Build From 1-2 number
  279. // 0. for each digit in 1-2 number
  280. // 0. calculate chunk size
  281. // 1. build 1 or 2 pennants of that size
  282. // 2. attach pennants and update node pointer
  283. // 1. return root
  284. NSMutableArray *sortedKeyList = [NSMutableArray arrayWithCapacity:dictionary.count];
  285. [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  286. [sortedKeyList addObject:key];
  287. }];
  288. [sortedKeyList sortUsingComparator:comparator];
  289. [sortedKeyList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  290. if (idx > 0) {
  291. if (comparator(sortedKeyList[idx - 1], obj) != NSOrderedAscending) {
  292. [NSException raise:NSInvalidArgumentException
  293. format:
  294. @"Can't create FSTImmutableSortedDictionary "
  295. @"with keys with same ordering!"];
  296. }
  297. }
  298. }];
  299. Base12List *list = NewBase12List((unsigned int)sortedKeyList.count);
  300. id<FSTLLRBNode> root = [self rootFrom12List:list keyList:sortedKeyList dictionary:dictionary];
  301. FreeBase12List(list);
  302. if (root != nil) {
  303. return [[FSTTreeSortedDictionary alloc] initWithComparator:comparator withRoot:root];
  304. } else {
  305. return [[FSTTreeSortedDictionary alloc] initWithComparator:comparator];
  306. }
  307. }
  308. @end
  309. NS_ASSUME_NONNULL_END