FSTEagerGarbageCollector.mm 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 "Firestore/Source/Local/FSTEagerGarbageCollector.h"
  17. #include <set>
  18. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  19. using firebase::firestore::model::DocumentKey;
  20. NS_ASSUME_NONNULL_BEGIN
  21. #pragma mark - FSTMultiReferenceSet
  22. @interface FSTEagerGarbageCollector ()
  23. /** The garbage collectible sources to double-check during garbage collection. */
  24. @property(nonatomic, strong, readonly) NSMutableArray<id<FSTGarbageSource>> *sources;
  25. @end
  26. @implementation FSTEagerGarbageCollector {
  27. /** A set of potentially garbage keys. */
  28. std::set<DocumentKey> _potentialGarbage;
  29. }
  30. - (instancetype)init {
  31. self = [super init];
  32. if (self) {
  33. _sources = [NSMutableArray array];
  34. }
  35. return self;
  36. }
  37. - (BOOL)isEager {
  38. return YES;
  39. }
  40. - (void)addGarbageSource:(id<FSTGarbageSource>)garbageSource {
  41. [self.sources addObject:garbageSource];
  42. garbageSource.garbageCollector = self;
  43. }
  44. - (void)removeGarbageSource:(id<FSTGarbageSource>)garbageSource {
  45. [self.sources removeObject:garbageSource];
  46. garbageSource.garbageCollector = nil;
  47. }
  48. - (void)addPotentialGarbageKey:(const DocumentKey &)key {
  49. _potentialGarbage.insert(key);
  50. }
  51. - (std::set<DocumentKey>)collectGarbage {
  52. NSMutableArray<id<FSTGarbageSource>> *sources = self.sources;
  53. std::set<DocumentKey> actualGarbage;
  54. for (const DocumentKey &key : _potentialGarbage) {
  55. BOOL isGarbage = YES;
  56. for (id<FSTGarbageSource> source in sources) {
  57. if ([source containsKey:key]) {
  58. isGarbage = NO;
  59. break;
  60. }
  61. }
  62. if (isGarbage) {
  63. actualGarbage.insert(key);
  64. }
  65. }
  66. // Clear locally retained potential keys and returned confirmed garbage.
  67. _potentialGarbage.clear();
  68. return actualGarbage;
  69. }
  70. @end
  71. NS_ASSUME_NONNULL_END