FSTEagerGarbageCollector.m 2.4 KB

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