FImmutableTree.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseDatabase/Sources/Core/Utilities/FImmutableTree.h"
  17. #import "FirebaseDatabase/Sources/Core/Utilities/FPath.h"
  18. #import "FirebaseDatabase/Sources/Utilities/FUtilities.h"
  19. #import "FirebaseDatabase/Sources/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.h"
  20. @interface FImmutableTree ()
  21. @property(nonatomic, strong, readwrite) id value;
  22. /**
  23. * Maps NSString -> FImmutableTree<T>, where <T> is type of value.
  24. */
  25. @property(nonatomic, strong, readwrite) FImmutableSortedDictionary *children;
  26. @end
  27. @implementation FImmutableTree
  28. @synthesize value;
  29. @synthesize children;
  30. - (id)initWithValue:(id)aValue {
  31. self = [super init];
  32. if (self) {
  33. self.value = aValue;
  34. self.children = [FImmutableTree emptyChildren];
  35. }
  36. return self;
  37. }
  38. - (id)initWithValue:(id)aValue
  39. children:(FImmutableSortedDictionary *)childrenMap {
  40. self = [super init];
  41. if (self) {
  42. self.value = aValue;
  43. self.children = childrenMap;
  44. }
  45. return self;
  46. }
  47. + (FImmutableSortedDictionary *)emptyChildren {
  48. static dispatch_once_t emptyChildrenToken;
  49. static FImmutableSortedDictionary *emptyChildren;
  50. dispatch_once(&emptyChildrenToken, ^{
  51. emptyChildren = [FImmutableSortedDictionary
  52. dictionaryWithComparator:[FUtilities stringComparator]];
  53. });
  54. return emptyChildren;
  55. }
  56. + (FImmutableTree *)empty {
  57. static dispatch_once_t emptyImmutableTreeToken;
  58. static FImmutableTree *emptyTree = nil;
  59. dispatch_once(&emptyImmutableTreeToken, ^{
  60. emptyTree = [[FImmutableTree alloc] initWithValue:nil];
  61. });
  62. return emptyTree;
  63. }
  64. - (BOOL)isEmpty {
  65. return self.value == nil && [self.children isEmpty];
  66. }
  67. /**
  68. * Given a path and a predicate, return the first node and the path to that node
  69. * where the predicate returns true
  70. * // TODO Do a perf test. If we're creating a bunch of FTuplePathValue objects
  71. * on the way back out, it may be better to pass down a pathSoFar FPath
  72. */
  73. - (FTuplePathValue *)findRootMostMatchingPath:(FPath *)relativePath
  74. predicate:(BOOL (^)(id value))predicate {
  75. if (self.value != nil && predicate(self.value)) {
  76. return [[FTuplePathValue alloc] initWithPath:[FPath empty]
  77. value:self.value];
  78. } else {
  79. if ([relativePath isEmpty]) {
  80. return nil;
  81. } else {
  82. NSString *front = [relativePath getFront];
  83. FImmutableTree *child = [self.children get:front];
  84. if (child != nil) {
  85. FTuplePathValue *childExistingPathAndValue =
  86. [child findRootMostMatchingPath:[relativePath popFront]
  87. predicate:predicate];
  88. if (childExistingPathAndValue != nil) {
  89. FPath *fullPath = [[[FPath alloc] initWith:front]
  90. child:childExistingPathAndValue.path];
  91. return [[FTuplePathValue alloc]
  92. initWithPath:fullPath
  93. value:childExistingPathAndValue.value];
  94. } else {
  95. return nil;
  96. }
  97. } else {
  98. // No child matching path
  99. return nil;
  100. }
  101. }
  102. }
  103. }
  104. /**
  105. * Find, if it exists, the shortest subpath of the given path that points a
  106. * defined value in the tree
  107. */
  108. - (FTuplePathValue *)findRootMostValueAndPath:(FPath *)relativePath {
  109. return [self findRootMostMatchingPath:relativePath
  110. predicate:^BOOL(__unsafe_unretained id value) {
  111. return YES;
  112. }];
  113. }
  114. - (id)rootMostValueOnPath:(FPath *)path {
  115. return [self rootMostValueOnPath:path
  116. matching:^BOOL(id value) {
  117. return YES;
  118. }];
  119. }
  120. - (id)rootMostValueOnPath:(FPath *)path matching:(BOOL (^)(id))predicate {
  121. if (self.value != nil && predicate(self.value)) {
  122. return self.value;
  123. } else if (path.isEmpty) {
  124. return nil;
  125. } else {
  126. return [[self.children get:path.getFront]
  127. rootMostValueOnPath:[path popFront]
  128. matching:predicate];
  129. }
  130. }
  131. - (id)leafMostValueOnPath:(FPath *)path {
  132. return [self leafMostValueOnPath:path
  133. matching:^BOOL(id value) {
  134. return YES;
  135. }];
  136. }
  137. - (id)leafMostValueOnPath:(FPath *)relativePath
  138. matching:(BOOL (^)(id))predicate {
  139. __block id currentValue = self.value;
  140. __block FImmutableTree *currentTree = self;
  141. [relativePath enumerateComponentsUsingBlock:^(NSString *key, BOOL *stop) {
  142. currentTree = [currentTree.children get:key];
  143. if (currentTree == nil) {
  144. *stop = YES;
  145. } else {
  146. id treeValue = currentTree.value;
  147. if (treeValue != nil && predicate(treeValue)) {
  148. currentValue = treeValue;
  149. }
  150. }
  151. }];
  152. return currentValue;
  153. }
  154. - (BOOL)containsValueMatching:(BOOL (^)(id))predicate {
  155. if (self.value != nil && predicate(self.value)) {
  156. return YES;
  157. } else {
  158. __block BOOL found = NO;
  159. [self.children enumerateKeysAndObjectsUsingBlock:^(
  160. NSString *key, FImmutableTree *subtree, BOOL *stop) {
  161. found = [subtree containsValueMatching:predicate];
  162. if (found)
  163. *stop = YES;
  164. }];
  165. return found;
  166. }
  167. }
  168. - (FImmutableTree *)subtreeAtPath:(FPath *)relativePath {
  169. if ([relativePath isEmpty]) {
  170. return self;
  171. } else {
  172. NSString *front = [relativePath getFront];
  173. FImmutableTree *childTree = [self.children get:front];
  174. if (childTree != nil) {
  175. return [childTree subtreeAtPath:[relativePath popFront]];
  176. } else {
  177. return [FImmutableTree empty];
  178. }
  179. }
  180. }
  181. /**
  182. * Sets a value at the specified path
  183. */
  184. - (FImmutableTree *)setValue:(id)newValue atPath:(FPath *)relativePath {
  185. if ([relativePath isEmpty]) {
  186. return [[FImmutableTree alloc] initWithValue:newValue
  187. children:self.children];
  188. } else {
  189. NSString *front = [relativePath getFront];
  190. FImmutableTree *child = [self.children get:front];
  191. if (child == nil) {
  192. child = [FImmutableTree empty];
  193. }
  194. FImmutableTree *newChild = [child setValue:newValue
  195. atPath:[relativePath popFront]];
  196. FImmutableSortedDictionary *newChildren =
  197. [self.children insertKey:front withValue:newChild];
  198. return [[FImmutableTree alloc] initWithValue:self.value
  199. children:newChildren];
  200. }
  201. }
  202. /**
  203. * Remove the value at the specified path
  204. */
  205. - (FImmutableTree *)removeValueAtPath:(FPath *)relativePath {
  206. if ([relativePath isEmpty]) {
  207. if ([self.children isEmpty]) {
  208. return [FImmutableTree empty];
  209. } else {
  210. return [[FImmutableTree alloc] initWithValue:nil
  211. children:self.children];
  212. }
  213. } else {
  214. NSString *front = [relativePath getFront];
  215. FImmutableTree *child = [self.children get:front];
  216. if (child) {
  217. FImmutableTree *newChild =
  218. [child removeValueAtPath:[relativePath popFront]];
  219. FImmutableSortedDictionary *newChildren;
  220. if ([newChild isEmpty]) {
  221. newChildren = [self.children removeKey:front];
  222. } else {
  223. newChildren = [self.children insertKey:front
  224. withValue:newChild];
  225. }
  226. if (self.value == nil && [newChildren isEmpty]) {
  227. return [FImmutableTree empty];
  228. } else {
  229. return [[FImmutableTree alloc] initWithValue:self.value
  230. children:newChildren];
  231. }
  232. } else {
  233. return self;
  234. }
  235. }
  236. }
  237. /**
  238. * Gets a value from the tree
  239. */
  240. - (id)valueAtPath:(FPath *)relativePath {
  241. if ([relativePath isEmpty]) {
  242. return self.value;
  243. } else {
  244. NSString *front = [relativePath getFront];
  245. FImmutableTree *child = [self.children get:front];
  246. if (child) {
  247. return [child valueAtPath:[relativePath popFront]];
  248. } else {
  249. return nil;
  250. }
  251. }
  252. }
  253. /**
  254. * Replaces the subtree at the specified path with the given new tree
  255. */
  256. - (FImmutableTree *)setTree:(FImmutableTree *)newTree
  257. atPath:(FPath *)relativePath {
  258. if ([relativePath isEmpty]) {
  259. return newTree;
  260. } else {
  261. NSString *front = [relativePath getFront];
  262. FImmutableTree *child = [self.children get:front];
  263. if (child == nil) {
  264. child = [FImmutableTree empty];
  265. }
  266. FImmutableTree *newChild = [child setTree:newTree
  267. atPath:[relativePath popFront]];
  268. FImmutableSortedDictionary *newChildren;
  269. if ([newChild isEmpty]) {
  270. newChildren = [self.children removeKey:front];
  271. } else {
  272. newChildren = [self.children insertKey:front withValue:newChild];
  273. }
  274. return [[FImmutableTree alloc] initWithValue:self.value
  275. children:newChildren];
  276. }
  277. }
  278. /**
  279. * Performs a depth first fold on this tree. Transforms a tree into a single
  280. * value, given a function that operates on the path to a node, an optional
  281. * current value, and a map of the child names to folded subtrees
  282. */
  283. - (id)foldWithBlock:(id (^)(FPath *path, id value,
  284. NSDictionary *foldedChildren))block {
  285. return [self foldWithPathSoFar:[FPath empty] withBlock:block];
  286. }
  287. /**
  288. * Recursive helper for public facing foldWithBlock: method
  289. */
  290. - (id)foldWithPathSoFar:(FPath *)pathSoFar
  291. withBlock:(id (^)(FPath *path, id value,
  292. NSDictionary *foldedChildren))block {
  293. __block NSMutableDictionary *accum = [[NSMutableDictionary alloc] init];
  294. [self.children
  295. enumerateKeysAndObjectsUsingBlock:^(
  296. NSString *childKey, FImmutableTree *childTree, BOOL *stop) {
  297. accum[childKey] =
  298. [childTree foldWithPathSoFar:[pathSoFar childFromString:childKey]
  299. withBlock:block];
  300. }];
  301. return block(pathSoFar, self.value, accum);
  302. }
  303. /**
  304. * Find the first matching value on the given path. Return the result of
  305. * applying block to it.
  306. */
  307. - (id)findOnPath:(FPath *)path
  308. andApplyBlock:(id (^)(FPath *path, id value))block {
  309. return [self findOnPath:path pathSoFar:[FPath empty] andApplyBlock:block];
  310. }
  311. - (id)findOnPath:(FPath *)pathToFollow
  312. pathSoFar:(FPath *)pathSoFar
  313. andApplyBlock:(id (^)(FPath *path, id value))block {
  314. id result = self.value ? block(pathSoFar, self.value) : nil;
  315. if (result != nil) {
  316. return result;
  317. } else {
  318. if ([pathToFollow isEmpty]) {
  319. return nil;
  320. } else {
  321. NSString *front = [pathToFollow getFront];
  322. FImmutableTree *nextChild = [self.children get:front];
  323. if (nextChild != nil) {
  324. return [nextChild findOnPath:[pathToFollow popFront]
  325. pathSoFar:[pathSoFar childFromString:front]
  326. andApplyBlock:block];
  327. } else {
  328. return nil;
  329. }
  330. }
  331. }
  332. }
  333. /**
  334. * Call the block on each value along the path for as long as that function
  335. * returns true
  336. * @return The path to the deepest location inspected
  337. */
  338. - (FPath *)forEachOnPath:(FPath *)path whileBlock:(BOOL (^)(FPath *, id))block {
  339. return [self forEachOnPath:path pathSoFar:[FPath empty] whileBlock:block];
  340. }
  341. - (FPath *)forEachOnPath:(FPath *)pathToFollow
  342. pathSoFar:(FPath *)pathSoFar
  343. whileBlock:(BOOL (^)(FPath *, id))block {
  344. if ([pathToFollow isEmpty]) {
  345. if (self.value) {
  346. block(pathSoFar, self.value);
  347. }
  348. return pathSoFar;
  349. } else {
  350. BOOL shouldContinue = YES;
  351. if (self.value) {
  352. shouldContinue = block(pathSoFar, self.value);
  353. }
  354. if (shouldContinue) {
  355. NSString *front = [pathToFollow getFront];
  356. FImmutableTree *nextChild = [self.children get:front];
  357. if (nextChild) {
  358. return
  359. [nextChild forEachOnPath:[pathToFollow popFront]
  360. pathSoFar:[pathSoFar childFromString:front]
  361. whileBlock:block];
  362. } else {
  363. return pathSoFar;
  364. }
  365. } else {
  366. return pathSoFar;
  367. }
  368. }
  369. }
  370. - (FImmutableTree *)forEachOnPath:(FPath *)path
  371. performBlock:(void (^)(FPath *path, id value))block {
  372. return [self forEachOnPath:path pathSoFar:[FPath empty] performBlock:block];
  373. }
  374. - (FImmutableTree *)forEachOnPath:(FPath *)pathToFollow
  375. pathSoFar:(FPath *)pathSoFar
  376. performBlock:(void (^)(FPath *path, id value))block {
  377. if ([pathToFollow isEmpty]) {
  378. return self;
  379. } else {
  380. if (self.value) {
  381. block(pathSoFar, self.value);
  382. }
  383. NSString *front = [pathToFollow getFront];
  384. FImmutableTree *nextChild = [self.children get:front];
  385. if (nextChild) {
  386. return [nextChild forEachOnPath:[pathToFollow popFront]
  387. pathSoFar:[pathSoFar childFromString:front]
  388. performBlock:block];
  389. } else {
  390. return [FImmutableTree empty];
  391. }
  392. }
  393. }
  394. /**
  395. * Calls the given block for each node in the tree that has a value. Called in
  396. * depth-first order
  397. */
  398. - (void)forEach:(void (^)(FPath *path, id value))block {
  399. [self forEachPathSoFar:[FPath empty] withBlock:block];
  400. }
  401. - (void)forEachPathSoFar:(FPath *)pathSoFar
  402. withBlock:(void (^)(FPath *path, id value))block {
  403. [self.children
  404. enumerateKeysAndObjectsUsingBlock:^(
  405. NSString *childKey, FImmutableTree *childTree, BOOL *stop) {
  406. [childTree forEachPathSoFar:[pathSoFar childFromString:childKey]
  407. withBlock:block];
  408. }];
  409. if (self.value) {
  410. block(pathSoFar, self.value);
  411. }
  412. }
  413. - (void)forEachChild:(void (^)(NSString *childKey, id childValue))block {
  414. [self.children
  415. enumerateKeysAndObjectsUsingBlock:^(
  416. NSString *childKey, FImmutableTree *childTree, BOOL *stop) {
  417. if (childTree.value) {
  418. block(childKey, childTree.value);
  419. }
  420. }];
  421. }
  422. - (BOOL)isEqual:(id)object {
  423. if (![object isKindOfClass:[FImmutableTree class]]) {
  424. return NO;
  425. }
  426. FImmutableTree *other = (FImmutableTree *)object;
  427. return (self.value == other.value || [self.value isEqual:other.value]) &&
  428. [self.children isEqual:other.children];
  429. }
  430. - (NSUInteger)hash {
  431. return self.children.hash * 31 + [self.value hash];
  432. }
  433. - (NSString *)description {
  434. NSMutableString *string = [[NSMutableString alloc] init];
  435. [string appendString:@"FImmutableTree { value="];
  436. [string appendString:(self.value ? [self.value description] : @"<nil>")];
  437. [string appendString:@", children={"];
  438. [self.children
  439. enumerateKeysAndObjectsUsingBlock:^(
  440. NSString *childKey, FImmutableTree *childTree, BOOL *stop) {
  441. [string appendString:@" "];
  442. [string appendString:childKey];
  443. [string appendString:@"="];
  444. [string appendString:[childTree.value description]];
  445. }];
  446. [string appendString:@" } }"];
  447. return [NSString stringWithString:string];
  448. }
  449. - (NSString *)debugDescription {
  450. return [self description];
  451. }
  452. @end