aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/third_party/Immutable/FSTLLRBValueNode.m
blob: e2590a19e43467049ba0018e3a4842b4d3184106 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#import "Firestore/third_party/Immutable/FSTLLRBValueNode.h"

#import "Firestore/third_party/Immutable/FSTLLRBEmptyNode.h"

NS_ASSUME_NONNULL_BEGIN

@interface FSTLLRBValueNode ()
@property(nonatomic, assign) FSTLLRBColor color;
@property(nonatomic, assign) NSUInteger count;
@property(nonatomic, strong) id key;
@property(nonatomic, strong) id value;
@property(nonatomic, strong) id<FSTLLRBNode> right;
@end

@implementation FSTLLRBValueNode

- (NSString *)colorDescription {
  NSString *color = @"unspecified";
  if (self.color == FSTLLRBColorRed) {
    color = @"red";
  } else if (self.color == FSTLLRBColorBlack) {
    color = @"black";
  }
  return color;
}

- (NSString *)description {
  NSString *color = self.colorDescription;
  return [NSString stringWithFormat:@"[key=%@ val=%@ color=%@]", self.key, self.value, color];
}

// Designated initializer.
- (instancetype)initWithKey:(id _Nullable)aKey
                  withValue:(id _Nullable)aValue
                  withColor:(FSTLLRBColor)aColor
                   withLeft:(id<FSTLLRBNode> _Nullable)aLeft
                  withRight:(id<FSTLLRBNode> _Nullable)aRight {
  self = [super init];
  if (self) {
    _key = aKey;
    _value = aValue;
    _color = aColor != FSTLLRBColorUnspecified ? aColor : FSTLLRBColorRed;
    _left = aLeft != nil ? aLeft : [FSTLLRBEmptyNode emptyNode];
    _right = aRight != nil ? aRight : [FSTLLRBEmptyNode emptyNode];
    _count = NSNotFound;
  }
  return self;
}

- (instancetype)copyWith:(id _Nullable)aKey
               withValue:(id _Nullable)aValue
               withColor:(FSTLLRBColor)aColor
                withLeft:(id<FSTLLRBNode> _Nullable)aLeft
               withRight:(id<FSTLLRBNode> _Nullable)aRight {
  return [[FSTLLRBValueNode alloc]
      initWithKey:(aKey != nil) ? aKey : self.key
        withValue:(aValue != nil) ? aValue : self.value
        withColor:(aColor != FSTLLRBColorUnspecified) ? aColor : self.color
         withLeft:(aLeft != nil) ? aLeft : self.left
        withRight:(aRight != nil) ? aRight : self.right];
}

- (void)setLeft:(nullable id<FSTLLRBNode>)left {
  // Setting the left node should be only done by the builder, so doing it after someone has
  // memoized count is an error.
  NSAssert(_count == NSNotFound, @"Can't update left node after using count");
  _left = left;
}

- (NSUInteger)count {
  if (_count == NSNotFound) {
    _count = _left.count + 1 + _right.count;
  }
  return _count;
}

- (BOOL)isEmpty {
  return NO;
}

/**
 * Early terminates if action returns YES.
 *
 * @return The first truthy value returned by action, or the last falsey value returned by action.
 */
- (BOOL)inorderTraversal:(BOOL (^)(id key, id value))action {
  return [self.left inorderTraversal:action] || action(self.key, self.value) ||
         [self.right inorderTraversal:action];
}

- (BOOL)reverseTraversal:(BOOL (^)(id key, id value))action {
  return [self.right reverseTraversal:action] || action(self.key, self.value) ||
         [self.left reverseTraversal:action];
}

- (id<FSTLLRBNode>)min {
  if ([self.left isEmpty]) {
    return self;
  } else {
    return [self.left min];
  }
}

- (nullable id)minKey {
  return [[self min] key];
}

- (nullable id)maxKey {
  if ([self.right isEmpty]) {
    return self.key;
  } else {
    return [self.right maxKey];
  }
}

- (id<FSTLLRBNode>)insertKey:(id)aKey forValue:(id)aValue withComparator:(NSComparator)aComparator {
  NSComparisonResult cmp = aComparator(aKey, self.key);
  FSTLLRBValueNode *n = self;

  if (cmp == NSOrderedAscending) {
    n = [n copyWith:nil
          withValue:nil
          withColor:FSTLLRBColorUnspecified
           withLeft:[n.left insertKey:aKey forValue:aValue withComparator:aComparator]
          withRight:nil];
  } else if (cmp == NSOrderedSame) {
    n = [n copyWith:nil
          withValue:aValue
          withColor:FSTLLRBColorUnspecified
           withLeft:nil
          withRight:nil];
  } else {
    n = [n copyWith:nil
          withValue:nil
          withColor:FSTLLRBColorUnspecified
           withLeft:nil
          withRight:[n.right insertKey:aKey forValue:aValue withComparator:aComparator]];
  }

  return [n fixUp];
}

- (id<FSTLLRBNode>)removeMin {
  if ([self.left isEmpty]) {
    return [FSTLLRBEmptyNode emptyNode];
  }

  FSTLLRBValueNode *n = self;
  if (![n.left isRed] && ![n.left.left isRed]) {
    n = [n moveRedLeft];
  }

  n = [n copyWith:nil
        withValue:nil
        withColor:FSTLLRBColorUnspecified
         withLeft:[(FSTLLRBValueNode *)n.left removeMin]
        withRight:nil];
  return [n fixUp];
}

- (id<FSTLLRBNode>)fixUp {
  FSTLLRBValueNode *n = self;
  if ([n.right isRed] && ![n.left isRed]) n = [n rotateLeft];
  if ([n.left isRed] && [n.left.left isRed]) n = [n rotateRight];
  if ([n.left isRed] && [n.right isRed]) n = [n colorFlip];
  return n;
}

- (FSTLLRBValueNode *)moveRedLeft {
  FSTLLRBValueNode *n = [self colorFlip];
  if ([n.right.left isRed]) {
    n = [n copyWith:nil
          withValue:nil
          withColor:FSTLLRBColorUnspecified
           withLeft:nil
          withRight:[(FSTLLRBValueNode *)n.right rotateRight]];
    n = [n rotateLeft];
    n = [n colorFlip];
  }
  return n;
}

- (FSTLLRBValueNode *)moveRedRight {
  FSTLLRBValueNode *n = [self colorFlip];
  if ([n.left.left isRed]) {
    n = [n rotateRight];
    n = [n colorFlip];
  }
  return n;
}

- (id<FSTLLRBNode>)rotateLeft {
  id<FSTLLRBNode> nl = [self copyWith:nil
                            withValue:nil
                            withColor:FSTLLRBColorRed
                             withLeft:nil
                            withRight:self.right.left];
  return [self.right copyWith:nil withValue:nil withColor:self.color withLeft:nl withRight:nil];
}

- (id<FSTLLRBNode>)rotateRight {
  id<FSTLLRBNode> nr = [self copyWith:nil
                            withValue:nil
                            withColor:FSTLLRBColorRed
                             withLeft:self.left.right
                            withRight:nil];
  return [self.left copyWith:nil withValue:nil withColor:self.color withLeft:nil withRight:nr];
}

- (id<FSTLLRBNode>)colorFlip {
  FSTLLRBColor color = self.color == FSTLLRBColorBlack ? FSTLLRBColorRed : FSTLLRBColorBlack;
  FSTLLRBColor leftColor =
      self.left.color == FSTLLRBColorBlack ? FSTLLRBColorRed : FSTLLRBColorBlack;
  FSTLLRBColor rightColor =
      self.right.color == FSTLLRBColorBlack ? FSTLLRBColorRed : FSTLLRBColorBlack;

  id<FSTLLRBNode> nleft =
      [self.left copyWith:nil withValue:nil withColor:leftColor withLeft:nil withRight:nil];
  id<FSTLLRBNode> nright =
      [self.right copyWith:nil withValue:nil withColor:rightColor withLeft:nil withRight:nil];

  return [self copyWith:nil withValue:nil withColor:color withLeft:nleft withRight:nright];
}

- (id<FSTLLRBNode>)remove:(id)aKey withComparator:(NSComparator)comparator {
  id<FSTLLRBNode> smallest;
  FSTLLRBValueNode *n = self;

  if (comparator(aKey, n.key) == NSOrderedAscending) {
    if (![n.left isEmpty] && ![n.left isRed] && ![n.left.left isRed]) {
      n = [n moveRedLeft];
    }
    n = [n copyWith:nil
          withValue:nil
          withColor:FSTLLRBColorUnspecified
           withLeft:[n.left remove:aKey withComparator:comparator]
          withRight:nil];
  } else {
    if ([n.left isRed]) {
      n = [n rotateRight];
    }

    if (![n.right isEmpty] && ![n.right isRed] && ![n.right.left isRed]) {
      n = [n moveRedRight];
    }

    if (comparator(aKey, n.key) == NSOrderedSame) {
      if ([n.right isEmpty]) {
        return [FSTLLRBEmptyNode emptyNode];
      } else {
        smallest = [n.right min];
        n = [n copyWith:smallest.key
              withValue:smallest.value
              withColor:FSTLLRBColorUnspecified
               withLeft:nil
              withRight:[(FSTLLRBValueNode *)n.right removeMin]];
      }
    }
    n = [n copyWith:nil
          withValue:nil
          withColor:FSTLLRBColorUnspecified
           withLeft:nil
          withRight:[n.right remove:aKey withComparator:comparator]];
  }
  return [n fixUp];
}

- (BOOL)isRed {
  return self.color == FSTLLRBColorRed;
}

- (BOOL)checkMaxDepth {
  int blackDepth = [self check];
  if (pow(2.0, blackDepth) <= ([self count] + 1)) {
    return YES;
  } else {
    return NO;
  }
}

- (int)check {
  int blackDepth = 0;

  if ([self isRed] && [self.left isRed]) {
    @throw
        [[NSException alloc] initWithName:@"check" reason:@"Red node has a red child" userInfo:nil];
  }

  if ([self.right isRed]) {
    @throw [[NSException alloc] initWithName:@"check" reason:@"Right child is red" userInfo:nil];
  }

  blackDepth = [self.left check];
  if (blackDepth != [self.right check]) {
    NSString *err =
        [NSString stringWithFormat:@"(%@ -> %@)blackDepth: %d ; self.right check: %d", self.value,
                                   self.colorDescription, blackDepth, [self.right check]];
    @throw [[NSException alloc] initWithName:@"check" reason:err userInfo:nil];
  } else {
    int ret = blackDepth + ([self isRed] ? 0 : 1);
    return ret;
  }
}

@end

NS_ASSUME_NONNULL_END