aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firebase/Database/Snapshot/FChildrenNode.m
blob: d53ae806cb7e0ffd08a8da384dc6892915fe8a53 (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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Copyright 2017 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "FChildrenNode.h"
#import "FEmptyNode.h"
#import "FConstants.h"
#import "FStringUtilities.h"
#import "FUtilities.h"
#import "FNamedNode.h"
#import "FMaxNode.h"
#import "FTransformedEnumerator.h"
#import "FSnapshotUtilities.h"
#import "FTransformedEnumerator.h"
#import "FPriorityIndex.h"
#import "FUtilities.h"

@interface FChildrenNode ()
@property (nonatomic, strong) NSString *lazyHash;
@end

@implementation FChildrenNode

// Note: The only reason we allow nil priority is to for EmptyNode, since we can't use
// EmptyNode as the priority of EmptyNode.  We might want to consider making EmptyNode its own
// class instead of an empty ChildrenNode.

- (id)init {
    return [self initWithPriority:nil children:[FImmutableSortedDictionary dictionaryWithComparator:[FUtilities keyComparator]]];
}

- (id)initWithChildren:(FImmutableSortedDictionary *)someChildren {
    return [self initWithPriority:nil children:someChildren];
}

- (id)initWithPriority:(id<FNode>)aPriority children:(FImmutableSortedDictionary *)someChildren {
    if (someChildren.isEmpty && aPriority != nil && ![aPriority isEmpty]) {
        [NSException raise:NSInvalidArgumentException format:@"Can't create empty node with priority!"];
    }
    self = [super init];
    if(self) {
        self.children = someChildren;
        self.priorityNode = aPriority;
    }
    return self;
}

- (NSString *) description {
    return [[self valForExport:YES] description];
}

#pragma mark -
#pragma mark FNode methods


- (BOOL) isLeafNode {
    return NO;
}

- (id<FNode>) getPriority {
    if (self.priorityNode) {
        return self.priorityNode;
    } else {
        return [FEmptyNode emptyNode];
    }

}

- (id<FNode>) updatePriority:(id<FNode>)aPriority {
    if ([self.children isEmpty]) {
        return [FEmptyNode emptyNode];
    } else {
        return [[FChildrenNode alloc] initWithPriority:aPriority children:self.children];
    }
}

- (id<FNode>) getImmediateChild:(NSString *) childName {
    if ([childName isEqualToString:@".priority"]) {
        return [self getPriority];
    } else {
        id <FNode> child = [self.children objectForKey:childName];
        return (child == nil) ? [FEmptyNode emptyNode] : child;
    }
}

- (id<FNode>) getChild:(FPath *)path {
    NSString* front = [path getFront];
    if(front == nil) {
        return self;
    }
    else {
        return [[self getImmediateChild:front] getChild:[path popFront]];
    }
}

- (BOOL)hasChild:(NSString *)childName {
    return ![self getImmediateChild:childName].isEmpty;
}


- (id<FNode>) updateImmediateChild:(NSString *)childName withNewChild:(id<FNode>)newChildNode {
    NSAssert(newChildNode != nil, @"Should always be passing nodes.");

    if ([childName isEqualToString:@".priority"]) {
        return [self updatePriority:newChildNode];
    } else {
        FImmutableSortedDictionary *newChildren;
        if (newChildNode.isEmpty) {
            newChildren = [self.children removeObjectForKey:childName];
        } else {
            newChildren = [self.children setObject:newChildNode forKey:childName];
        }
        if (newChildren.isEmpty) {
            return [FEmptyNode emptyNode];
        } else {
            return [[FChildrenNode alloc] initWithPriority:self.getPriority children:newChildren];
        }
    }
}

- (id<FNode>) updateChild:(FPath *)path withNewChild:(id<FNode>)newChildNode {
    NSString* front = [path getFront];
    if(front == nil) {
        return newChildNode;
    } else {
        NSAssert(![front isEqualToString:@".priority"] || path.length == 1, @".priority must be the last token in a path.");
        id<FNode> newImmediateChild = [[self getImmediateChild:front] updateChild:[path popFront] withNewChild:newChildNode];
        return [self updateImmediateChild:front withNewChild:newImmediateChild];
    }
}

- (BOOL) isEmpty {
    return [self.children isEmpty];
}

- (int) numChildren {
    return [self.children count];
}

- (id) val {
    return [self valForExport:NO];
}

- (id) valForExport:(BOOL)exp {
    if([self isEmpty]) {
        return [NSNull null];
    }

    __block int numKeys = 0;
    __block NSInteger maxKey = 0;
    __block BOOL allIntegerKeys = YES;

    NSMutableDictionary* obj = [[NSMutableDictionary alloc] initWithCapacity:[self.children count]];
    [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> childNode, BOOL *stop) {
        [obj setObject:[childNode valForExport:exp] forKey:key];

        numKeys++;

        // If we already found a string key, don't bother with any of this
        if (!allIntegerKeys) {
            return;
        }

        // Treat leading zeroes that are not exactly "0" as strings
        NSString* firstChar = [key substringWithRange:NSMakeRange(0, 1)];
        if ([firstChar isEqualToString:@"0"] && [key length] > 1) {
            allIntegerKeys = NO;
        } else {
            NSNumber *keyAsNum = [FUtilities intForString:key];
            if (keyAsNum != nil) {
                NSInteger keyAsInt = [keyAsNum integerValue];
                if (keyAsInt > maxKey) {
                    maxKey = keyAsInt;
                }
            } else {
                allIntegerKeys = NO;
            }
        }
    }];

    if (!exp && allIntegerKeys && maxKey < 2 * numKeys) {
        // convert to an array
        NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:maxKey + 1];
        for (int i = 0; i <= maxKey; ++i) {
            NSString* keyString = [NSString stringWithFormat:@"%i", i];
            id child = obj[keyString];
            if (child != nil) {
                [array addObject:child];
            } else {
                [array addObject:[NSNull null]];
            }
        }
        return array;
    } else {

        if(exp && [self getPriority] != nil && !self.getPriority.isEmpty) {
            obj[kPayloadPriority] = [self.getPriority val];
        }

        return obj;
    }
}

- (NSString *) dataHash {
    if (self.lazyHash == nil) {
        NSMutableString *toHash = [[NSMutableString alloc] init];

        if (!self.getPriority.isEmpty) {
            [toHash appendString:@"priority:"];
            [FSnapshotUtilities appendHashRepresentationForLeafNode:(FLeafNode *)self.getPriority
                                                           toString:toHash
                                                        hashVersion:FDataHashVersionV1];
            [toHash appendString:@":"];
        }

        __block BOOL sawPriority = NO;
        [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
            sawPriority = sawPriority || [[node getPriority] isEmpty];
            *stop = sawPriority;
        }];
        if (sawPriority) {
            NSMutableArray *array = [NSMutableArray array];
            [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
                FNamedNode *namedNode = [[FNamedNode alloc] initWithName:key andNode:node];
                [array addObject:namedNode];
            }];
            [array sortUsingComparator:^NSComparisonResult(FNamedNode *namedNode1, FNamedNode *namedNode2) {
                return [[FPriorityIndex priorityIndex] compareNamedNode:namedNode1 toNamedNode:namedNode2];
            }];
            [array enumerateObjectsUsingBlock:^(FNamedNode *namedNode, NSUInteger idx, BOOL *stop) {
                NSString *childHash = [namedNode.node dataHash];
                if (![childHash isEqualToString:@""]) {
                    [toHash appendFormat:@":%@:%@", namedNode.name, childHash];
                }
            }];
        } else {
            [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
                NSString *childHash = [node dataHash];
                if (![childHash isEqualToString:@""]) {
                    [toHash appendFormat:@":%@:%@", key, childHash];
                }
            }];
        }
        self.lazyHash = [toHash isEqualToString:@""] ? @"" : [FStringUtilities base64EncodedSha1:toHash];
    }
    return self.lazyHash;
}

- (NSComparisonResult)compare:(id <FNode>)other {
    // children nodes come last, unless this is actually an empty node, then we come first.
    if (self.isEmpty) {
        if (other.isEmpty) {
            return NSOrderedSame;
        } else {
            return NSOrderedAscending;
        }
    } else if (other.isLeafNode || other.isEmpty) {
        return NSOrderedDescending;
    } else if (other == [FMaxNode maxNode]) {
        return NSOrderedAscending;
    } else {
        // Must be another node with children.
        return NSOrderedSame;
    }
}

- (BOOL)isEqual:(id <FNode>)other {
    if (other == self) {
        return YES;
    } else if (other == nil) {
        return NO;
    } else if (other.isLeafNode) {
        return NO;
    } else if (self.isEmpty && [other isEmpty]) {
        // Empty nodes do not have priority
        return YES;
    } else {
        FChildrenNode *otherChildrenNode = other;
        if (![self.getPriority isEqual:other.getPriority]) {
            return NO;
        } else if (self.children.count == otherChildrenNode.children.count) {
            __block BOOL equal = YES;
            [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
                id<FNode> child = [otherChildrenNode getImmediateChild:key];
                if (![child isEqual:node]) {
                    equal = NO;
                    *stop = YES;
                }
            }];
            return equal;
        } else {
            return NO;
        }
    }
}

- (NSUInteger)hash {
    __block NSUInteger hashCode = 0;
    [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
        hashCode = 31 * hashCode + key.hash;
        hashCode = 17 * hashCode + node.hash;
    }];
    return 17 * hashCode + self.priorityNode.hash;
}

- (void) enumerateChildrenAndPriorityUsingBlock:(void (^)(NSString *, id<FNode>, BOOL *))block
{
    if ([self.getPriority isEmpty]) {
        [self enumerateChildrenUsingBlock:block];
    } else {
        __block BOOL passedPriorityKey = NO;
        [self enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
            if (!passedPriorityKey && [FUtilities compareKey:key toKey:@".priority"] == NSOrderedDescending) {
                passedPriorityKey = YES;
                BOOL stopAfterPriority = NO;
                block(@".priority", [self getPriority], &stopAfterPriority);
                if (stopAfterPriority) return;
            }
            block(key, node, stop);
        }];
    }
}

- (void) enumerateChildrenUsingBlock:(void (^)(NSString *, id<FNode>, BOOL *))block
{
    [self.children enumerateKeysAndObjectsUsingBlock:block];
}

- (void) enumerateChildrenReverse:(BOOL)reverse usingBlock:(void (^)(NSString *, id<FNode>, BOOL *))block
{
    [self.children enumerateKeysAndObjectsReverse:reverse usingBlock:block];
}

- (NSEnumerator *)childEnumerator
{
    return [[FTransformedEnumerator alloc] initWithEnumerator:self.children.keyEnumerator andTransform:^id(NSString *key) {
        return [FNamedNode nodeWithName:key node:[self getImmediateChild:key]];
    }];
}

- (NSString *) predecessorChildKey:(NSString *)childKey
{
    return [self.children getPredecessorKey:childKey];
}

#pragma mark -
#pragma mark FChildrenNode specific methods

- (id) childrenGetter:(id)key {
    return [self.children objectForKey:key];
}

- (FNamedNode *)firstChild
{
    NSString *childKey = self.children.minKey;
    if (childKey) {
        return [[FNamedNode alloc] initWithName:childKey andNode:[self getImmediateChild:childKey]];
    } else {
        return nil;
    }
}

- (FNamedNode *)lastChild
{
    NSString *childKey = self.children.maxKey;
    if (childKey) {
        return [[FNamedNode alloc] initWithName:childKey andNode:[self getImmediateChild:childKey]];
    } else {
        return nil;
    }
}

@end