aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Source/Model/FSTFieldValue.mm
blob: 6a13511f6f6d482f9c02eaf7996f23e9749679eb (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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
/*
 * 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 "Firestore/Source/Model/FSTFieldValue.h"

#import "FIRDocumentSnapshot.h"
#import "FIRTimestamp.h"

#import "Firestore/Source/API/FIRGeoPoint+Internal.h"
#import "Firestore/Source/Model/FSTDocumentKey.h"
#import "Firestore/Source/Util/FSTClasses.h"

#include "Firestore/core/src/firebase/firestore/model/database_id.h"
#include "Firestore/core/src/firebase/firestore/model/field_path.h"
#include "Firestore/core/src/firebase/firestore/util/comparison.h"
#include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
#include "Firestore/core/src/firebase/firestore/util/string_apple.h"

namespace util = firebase::firestore::util;
using firebase::firestore::model::DatabaseId;
using firebase::firestore::model::FieldPath;
using firebase::firestore::util::Comparator;
using firebase::firestore::util::CompareMixedNumber;
using firebase::firestore::util::DoubleBitwiseEquals;
using firebase::firestore::util::DoubleBitwiseHash;
using firebase::firestore::util::MakeStringView;
using firebase::firestore::util::ReverseOrder;
using firebase::firestore::util::WrapCompare;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - FSTFieldValueOptions

@implementation FSTFieldValueOptions

- (instancetype)initWithServerTimestampBehavior:(FSTServerTimestampBehavior)serverTimestampBehavior
                   timestampsInSnapshotsEnabled:(BOOL)timestampsInSnapshotsEnabled {
  self = [super init];

  if (self) {
    _serverTimestampBehavior = serverTimestampBehavior;
    _timestampsInSnapshotsEnabled = timestampsInSnapshotsEnabled;
  }
  return self;
}

@end

#pragma mark - FSTFieldValue

@interface FSTFieldValue ()
- (NSComparisonResult)defaultCompare:(FSTFieldValue *)other;
@end

@implementation FSTFieldValue

- (FSTTypeOrder)typeOrder {
  @throw FSTAbstractMethodException();  // NOLINT
}

- (id)value {
  @throw FSTAbstractMethodException();  // NOLINT
}

- (id)valueWithOptions:(FSTFieldValueOptions *)options {
  return [self value];
}

- (BOOL)isEqual:(id)other {
  @throw FSTAbstractMethodException();  // NOLINT
}

- (NSUInteger)hash {
  @throw FSTAbstractMethodException();  // NOLINT
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  @throw FSTAbstractMethodException();  // NOLINT
}

- (NSString *)description {
  return [[self value] description];
}

- (NSComparisonResult)defaultCompare:(FSTFieldValue *)other {
  if (self.typeOrder > other.typeOrder) {
    return NSOrderedDescending;
  } else {
    HARD_ASSERT(self.typeOrder < other.typeOrder,
                "defaultCompare should not be used for values of same type.");
    return NSOrderedAscending;
  }
}

@end

#pragma mark - FSTNullValue

@implementation FSTNullValue

+ (instancetype)nullValue {
  static FSTNullValue *sharedInstance = nil;
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    sharedInstance = [[FSTNullValue alloc] init];
  });
  return sharedInstance;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderNull;
}

- (id)value {
  return [NSNull null];
}

- (BOOL)isEqual:(id)other {
  return [other isKindOfClass:[self class]];
}

- (NSUInteger)hash {
  return 47;
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[self class]]) {
    return NSOrderedSame;
  } else {
    return [self defaultCompare:other];
  }
}

@end

#pragma mark - FSTBooleanValue

@interface FSTBooleanValue ()
@property(nonatomic, assign, readonly) BOOL internalValue;
@end

@implementation FSTBooleanValue

+ (instancetype)trueValue {
  static FSTBooleanValue *sharedInstance = nil;
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    sharedInstance = [[FSTBooleanValue alloc] initWithValue:YES];
  });
  return sharedInstance;
}

+ (instancetype)falseValue {
  static FSTBooleanValue *sharedInstance = nil;
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    sharedInstance = [[FSTBooleanValue alloc] initWithValue:NO];
  });
  return sharedInstance;
}

+ (instancetype)booleanValue:(BOOL)value {
  return value ? [FSTBooleanValue trueValue] : [FSTBooleanValue falseValue];
}

- (id)initWithValue:(BOOL)value {
  self = [super init];
  if (self) {
    _internalValue = value;
  }
  return self;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderBoolean;
}

- (id)value {
  return self.internalValue ? @YES : @NO;
}

- (BOOL)isEqual:(id)other {
  // Since we create shared instances for true / false, we can use reference equality.
  return self == other;
}

- (NSUInteger)hash {
  return self.internalValue ? 1231 : 1237;
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTBooleanValue class]]) {
    return WrapCompare<bool>(self.internalValue, ((FSTBooleanValue *)other).internalValue);
  } else {
    return [self defaultCompare:other];
  }
}

@end

#pragma mark - FSTNumberValue

@implementation FSTNumberValue

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderNumber;
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if (![other isKindOfClass:[FSTNumberValue class]]) {
    return [self defaultCompare:other];
  } else {
    if ([self isKindOfClass:[FSTDoubleValue class]]) {
      double thisDouble = ((FSTDoubleValue *)self).internalValue;
      if ([other isKindOfClass:[FSTDoubleValue class]]) {
        return WrapCompare(thisDouble, ((FSTDoubleValue *)other).internalValue);
      } else {
        HARD_ASSERT([other isKindOfClass:[FSTIntegerValue class]], "Unknown number value: %s",
                    other);
        auto result = CompareMixedNumber(thisDouble, ((FSTIntegerValue *)other).internalValue);
        return static_cast<NSComparisonResult>(result);
      }
    } else {
      int64_t thisInt = ((FSTIntegerValue *)self).internalValue;
      if ([other isKindOfClass:[FSTIntegerValue class]]) {
        return WrapCompare(thisInt, ((FSTIntegerValue *)other).internalValue);
      } else {
        HARD_ASSERT([other isKindOfClass:[FSTDoubleValue class]], "Unknown number value: %s",
                    other);
        double otherDouble = ((FSTDoubleValue *)other).internalValue;
        auto result = ReverseOrder(CompareMixedNumber(otherDouble, thisInt));
        return static_cast<NSComparisonResult>(result);
      }
    }
  }
}

@end

#pragma mark - FSTIntegerValue

@interface FSTIntegerValue ()
@property(nonatomic, assign, readonly) int64_t internalValue;
@end

@implementation FSTIntegerValue

+ (instancetype)integerValue:(int64_t)value {
  return [[FSTIntegerValue alloc] initWithValue:value];
}

- (id)initWithValue:(int64_t)value {
  self = [super init];
  if (self) {
    _internalValue = value;
  }
  return self;
}

- (id)value {
  return @(self.internalValue);
}

- (BOOL)isEqual:(id)other {
  // NOTE: DoubleValue and LongValue instances may compare: the same, but that doesn't make them
  // equal via isEqual:
  return [other isKindOfClass:[FSTIntegerValue class]] &&
         self.internalValue == ((FSTIntegerValue *)other).internalValue;
}

- (NSUInteger)hash {
  return (((NSUInteger)self.internalValue) ^ (NSUInteger)(self.internalValue >> 32));
}

// NOTE: compare: is implemented in NumberValue.

@end

#pragma mark - FSTDoubleValue

@interface FSTDoubleValue ()
@property(nonatomic, assign, readonly) double internalValue;
@end

@implementation FSTDoubleValue

+ (instancetype)doubleValue:(double)value {
  // Normalize NaNs to match the behavior on the backend (which uses Double.doubletoLongBits()).
  if (isnan(value)) {
    return [FSTDoubleValue nanValue];
  }
  return [[FSTDoubleValue alloc] initWithValue:value];
}

+ (instancetype)nanValue {
  static FSTDoubleValue *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[FSTDoubleValue alloc] initWithValue:NAN];
  });
  return sharedInstance;
}

- (id)initWithValue:(double)value {
  self = [super init];
  if (self) {
    _internalValue = value;
  }
  return self;
}

- (id)value {
  return @(self.internalValue);
}

- (BOOL)isEqual:(id)other {
  // NOTE: DoubleValue and LongValue instances may compare: the same, but that doesn't make them
  // equal via isEqual:

  // NOTE: isEqual: should compare NaN equal to itself and -0.0 not equal to 0.0.

  return [other isKindOfClass:[FSTDoubleValue class]] &&
         DoubleBitwiseEquals(self.internalValue, ((FSTDoubleValue *)other).internalValue);
}

- (NSUInteger)hash {
  return DoubleBitwiseHash(self.internalValue);
}

// NOTE: compare: is implemented in NumberValue.

@end

#pragma mark - FSTStringValue

/**
 * Specialization of Comparator for NSStrings.
 */
template <>
struct Comparator<NSString *> {
  bool operator()(NSString *left, NSString *right) const {
    Comparator<absl::string_view> lessThan;
    return lessThan(MakeStringView(left), MakeStringView(right));
  }
};

@interface FSTStringValue ()
@property(nonatomic, copy, readonly) NSString *internalValue;
@end

// TODO(b/37267885): Add truncation support
@implementation FSTStringValue

+ (instancetype)stringValue:(NSString *)value {
  return [[FSTStringValue alloc] initWithValue:value];
}

- (id)initWithValue:(NSString *)value {
  self = [super init];
  if (self) {
    _internalValue = [value copy];
  }
  return self;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderString;
}

- (id)value {
  return self.internalValue;
}

- (BOOL)isEqual:(id)other {
  return [other isKindOfClass:[FSTStringValue class]] &&
         [self.internalValue isEqualToString:((FSTStringValue *)other).internalValue];
}

- (NSUInteger)hash {
  return self.internalValue ? 1 : 0;
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTStringValue class]]) {
    return WrapCompare(self.internalValue, ((FSTStringValue *)other).internalValue);
  } else {
    return [self defaultCompare:other];
  }
}

@end

#pragma mark - FSTTimestampValue

@interface FSTTimestampValue ()
@property(nonatomic, strong, readonly) FIRTimestamp *internalValue;
@end

@implementation FSTTimestampValue

+ (instancetype)timestampValue:(FIRTimestamp *)value {
  return [[FSTTimestampValue alloc] initWithValue:value];
}

- (id)initWithValue:(FIRTimestamp *)value {
  self = [super init];
  if (self) {
    _internalValue = value;  // FIRTimestamp is immutable.
  }
  return self;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderTimestamp;
}

- (id)value {
  return self.internalValue;
}

- (id)valueWithOptions:(FSTFieldValueOptions *)options {
  if (options.timestampsInSnapshotsEnabled) {
    return self.value;
  } else {
    return [self.value dateValue];
  }
}

- (BOOL)isEqual:(id)other {
  return [other isKindOfClass:[FSTTimestampValue class]] &&
         [self.internalValue isEqual:((FSTTimestampValue *)other).internalValue];
}

- (NSUInteger)hash {
  return [self.internalValue hash];
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTTimestampValue class]]) {
    return [self.internalValue compare:((FSTTimestampValue *)other).internalValue];
  } else if ([other isKindOfClass:[FSTServerTimestampValue class]]) {
    // Concrete timestamps come before server timestamps.
    return NSOrderedAscending;
  } else {
    return [self defaultCompare:other];
  }
}

@end
#pragma mark - FSTServerTimestampValue

@implementation FSTServerTimestampValue

+ (instancetype)serverTimestampValueWithLocalWriteTime:(FIRTimestamp *)localWriteTime
                                         previousValue:(nullable FSTFieldValue *)previousValue {
  return [[FSTServerTimestampValue alloc] initWithLocalWriteTime:localWriteTime
                                                   previousValue:previousValue];
}

- (id)initWithLocalWriteTime:(FIRTimestamp *)localWriteTime
               previousValue:(nullable FSTFieldValue *)previousValue {
  self = [super init];
  if (self) {
    _localWriteTime = localWriteTime;
    _previousValue = previousValue;
  }
  return self;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderTimestamp;
}

- (id)value {
  return [NSNull null];
}

- (id)valueWithOptions:(FSTFieldValueOptions *)options {
  switch (options.serverTimestampBehavior) {
    case FSTServerTimestampBehaviorNone:
      return [NSNull null];
    case FSTServerTimestampBehaviorEstimate:
      return [[FSTTimestampValue timestampValue:self.localWriteTime] valueWithOptions:options];
    case FSTServerTimestampBehaviorPrevious:
      return self.previousValue ? [self.previousValue valueWithOptions:options] : [NSNull null];
    default:
      HARD_FAIL("Unexpected server timestamp option: %s", options.serverTimestampBehavior);
  }
}

- (BOOL)isEqual:(id)other {
  return [other isKindOfClass:[FSTServerTimestampValue class]] &&
         [self.localWriteTime isEqual:((FSTServerTimestampValue *)other).localWriteTime];
}

- (NSUInteger)hash {
  return [self.localWriteTime hash];
}

- (NSString *)description {
  return [NSString stringWithFormat:@"<ServerTimestamp localTime=%@>", self.localWriteTime];
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTServerTimestampValue class]]) {
    return [self.localWriteTime compare:((FSTServerTimestampValue *)other).localWriteTime];
  } else if ([other isKindOfClass:[FSTTimestampValue class]]) {
    // Server timestamps come after all concrete timestamps.
    return NSOrderedDescending;
  } else {
    return [self defaultCompare:other];
  }
}

@end

#pragma mark - FSTGeoPointValue

@interface FSTGeoPointValue ()
@property(nonatomic, strong, readonly) FIRGeoPoint *internalValue;
@end

@implementation FSTGeoPointValue

+ (instancetype)geoPointValue:(FIRGeoPoint *)value {
  return [[FSTGeoPointValue alloc] initWithValue:value];
}

- (id)initWithValue:(FIRGeoPoint *)value {
  self = [super init];
  if (self) {
    _internalValue = value;  // FIRGeoPoint is immutable.
  }
  return self;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderGeoPoint;
}

- (id)value {
  return self.internalValue;
}

- (BOOL)isEqual:(id)other {
  return [other isKindOfClass:[FSTGeoPointValue class]] &&
         [self.internalValue isEqual:((FSTGeoPointValue *)other).internalValue];
}

- (NSUInteger)hash {
  return [self.internalValue hash];
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTGeoPointValue class]]) {
    return [self.internalValue compare:((FSTGeoPointValue *)other).internalValue];
  } else {
    return [self defaultCompare:other];
  }
}

@end
#pragma mark - FSTBlobValue

static NSComparisonResult CompareBytes(NSData *left, NSData *right) {
  NSUInteger minLength = MIN(left.length, right.length);
  int result = memcmp(left.bytes, right.bytes, minLength);
  if (result < 0) {
    return NSOrderedAscending;
  } else if (result > 0) {
    return NSOrderedDescending;
  } else if (left.length < right.length) {
    return NSOrderedAscending;
  } else if (left.length > right.length) {
    return NSOrderedDescending;
  } else {
    return NSOrderedSame;
  }
}

@interface FSTBlobValue ()
@property(nonatomic, copy, readonly) NSData *internalValue;
@end

// TODO(b/37267885): Add truncation support
@implementation FSTBlobValue

+ (instancetype)blobValue:(NSData *)value {
  return [[FSTBlobValue alloc] initWithValue:value];
}

- (id)initWithValue:(NSData *)value {
  self = [super init];
  if (self) {
    _internalValue = [value copy];
  }
  return self;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderBlob;
}

- (id)value {
  return self.internalValue;
}

- (BOOL)isEqual:(id)other {
  return [other isKindOfClass:[FSTBlobValue class]] &&
         [self.internalValue isEqual:((FSTBlobValue *)other).internalValue];
}

- (NSUInteger)hash {
  return [self.internalValue hash];
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTBlobValue class]]) {
    return CompareBytes(self.internalValue, ((FSTBlobValue *)other).internalValue);
  } else {
    return [self defaultCompare:other];
  }
}

@end

#pragma mark - FSTReferenceValue

@interface FSTReferenceValue ()
@property(nonatomic, strong, readonly) FSTDocumentKey *key;
@end

@implementation FSTReferenceValue

+ (instancetype)referenceValue:(FSTDocumentKey *)value databaseID:(const DatabaseId *)databaseID {
  return [[FSTReferenceValue alloc] initWithValue:value databaseID:databaseID];
}

- (id)initWithValue:(FSTDocumentKey *)value databaseID:(const DatabaseId *)databaseID {
  self = [super init];
  if (self) {
    _key = value;
    _databaseID = databaseID;
  }
  return self;
}

- (id)value {
  return self.key;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderReference;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTReferenceValue class]]) {
    return NO;
  }

  FSTReferenceValue *otherRef = (FSTReferenceValue *)other;
  return [self.key isEqualToKey:otherRef.key] && *self.databaseID == *otherRef.databaseID;
}

- (NSUInteger)hash {
  NSUInteger result = self.databaseID->Hash();
  result = 31 * result + [self.key hash];
  return result;
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTReferenceValue class]]) {
    FSTReferenceValue *ref = (FSTReferenceValue *)other;
    NSComparisonResult cmp = [util::WrapNSStringNoCopy(self.databaseID->project_id())
        compare:util::WrapNSStringNoCopy(ref.databaseID->project_id())];
    if (cmp != NSOrderedSame) {
      return cmp;
    }
    cmp = [util::WrapNSStringNoCopy(self.databaseID->database_id())
        compare:util::WrapNSStringNoCopy(ref.databaseID->database_id())];
    return cmp != NSOrderedSame ? cmp : [self.key compare:ref.key];
  } else {
    return [self defaultCompare:other];
  }
}

@end

#pragma mark - FSTObjectValue

static const NSComparator StringComparator = ^NSComparisonResult(NSString *left, NSString *right) {
  return WrapCompare(left, right);
};

@interface FSTObjectValue ()
@property(nonatomic, strong, readonly)
    FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *internalValue;
@end

@implementation FSTObjectValue

+ (instancetype)objectValue {
  static FSTObjectValue *sharedEmptyInstance = nil;
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *empty =
        [FSTImmutableSortedDictionary dictionaryWithComparator:StringComparator];
    sharedEmptyInstance = [[FSTObjectValue alloc] initWithImmutableDictionary:empty];
  });
  return sharedEmptyInstance;
}

- (instancetype)initWithImmutableDictionary:
    (FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *)value {
  self = [super init];
  if (self) {
    _internalValue = value;  // FSTImmutableSortedDictionary is immutable.
  }
  return self;
}

- (id)initWithDictionary:(NSDictionary<NSString *, FSTFieldValue *> *)value {
  FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *dictionary =
      [FSTImmutableSortedDictionary dictionaryWithDictionary:value comparator:StringComparator];
  return [self initWithImmutableDictionary:dictionary];
}

- (id)value {
  NSMutableDictionary *result = [NSMutableDictionary dictionary];
  [self.internalValue
      enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
        result[key] = [obj value];
      }];
  return result;
}

- (id)valueWithOptions:(FSTFieldValueOptions *)options {
  NSMutableDictionary *result = [NSMutableDictionary dictionary];
  [self.internalValue
      enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
        result[key] = [obj valueWithOptions:options];
      }];
  return result;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderObject;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTObjectValue class]]) {
    return NO;
  }

  FSTObjectValue *otherObj = other;
  return [self.internalValue isEqual:otherObj.internalValue];
}

- (NSUInteger)hash {
  return [self.internalValue hash];
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTObjectValue class]]) {
    FSTImmutableSortedDictionary *selfDict = self.internalValue;
    FSTImmutableSortedDictionary *otherDict = ((FSTObjectValue *)other).internalValue;
    NSEnumerator *enumerator1 = [selfDict keyEnumerator];
    NSEnumerator *enumerator2 = [otherDict keyEnumerator];
    NSString *key1 = [enumerator1 nextObject];
    NSString *key2 = [enumerator2 nextObject];
    while (key1 && key2) {
      NSComparisonResult keyCompare = [key1 compare:key2];
      if (keyCompare != NSOrderedSame) {
        return keyCompare;
      }
      NSComparisonResult valueCompare = [selfDict[key1] compare:otherDict[key2]];
      if (valueCompare != NSOrderedSame) {
        return valueCompare;
      }
      key1 = [enumerator1 nextObject];
      key2 = [enumerator2 nextObject];
    }
    // Only equal if both enumerators are exhausted.
    return WrapCompare(key1 != nil, key2 != nil);
  } else {
    return [self defaultCompare:other];
  }
}

- (nullable FSTFieldValue *)valueForPath:(const FieldPath &)fieldPath {
  FSTFieldValue *value = self;
  for (size_t i = 0, max = fieldPath.size(); value && i < max; i++) {
    if (![value isMemberOfClass:[FSTObjectValue class]]) {
      return nil;
    }

    NSString *fieldName = util::WrapNSStringNoCopy(fieldPath[i]);
    value = ((FSTObjectValue *)value).internalValue[fieldName];
  }

  return value;
}

- (FSTObjectValue *)objectBySettingValue:(FSTFieldValue *)value
                                 forPath:(const FieldPath &)fieldPath {
  HARD_ASSERT(fieldPath.size() > 0, "Cannot set value with an empty path");

  NSString *childName = util::WrapNSString(fieldPath.first_segment());
  if (fieldPath.size() == 1) {
    // Recursive base case:
    return [self objectBySettingValue:value forField:childName];
  } else {
    // Nested path. Recursively generate a new sub-object and then wrap a new FSTObjectValue
    // around the result.
    FSTFieldValue *child = [_internalValue objectForKey:childName];
    FSTObjectValue *childObject;
    if ([child isKindOfClass:[FSTObjectValue class]]) {
      childObject = (FSTObjectValue *)child;
    } else {
      // If the child is not found or is a primitive type, pretend as if an empty object lived
      // there.
      childObject = [FSTObjectValue objectValue];
    }
    FSTFieldValue *newChild = [childObject objectBySettingValue:value forPath:fieldPath.PopFirst()];
    return [self objectBySettingValue:newChild forField:childName];
  }
}

- (FSTObjectValue *)objectByDeletingPath:(const FieldPath &)fieldPath {
  HARD_ASSERT(fieldPath.size() > 0, "Cannot delete an empty path");
  NSString *childName = util::WrapNSString(fieldPath.first_segment());
  if (fieldPath.size() == 1) {
    return [[FSTObjectValue alloc]
        initWithImmutableDictionary:[_internalValue dictionaryByRemovingObjectForKey:childName]];
  } else {
    FSTFieldValue *child = _internalValue[childName];
    if ([child isKindOfClass:[FSTObjectValue class]]) {
      FSTObjectValue *newChild =
          [((FSTObjectValue *)child) objectByDeletingPath:fieldPath.PopFirst()];
      return [self objectBySettingValue:newChild forField:childName];
    } else {
      // If the child is not found or is a primitive type, make no modifications
      return self;
    }
  }
}

- (FSTObjectValue *)objectBySettingValue:(FSTFieldValue *)value forField:(NSString *)field {
  return [[FSTObjectValue alloc]
      initWithImmutableDictionary:[_internalValue dictionaryBySettingObject:value forKey:field]];
}

@end

@interface FSTArrayValue ()
@property(nonatomic, strong, readonly) NSArray<FSTFieldValue *> *internalValue;
@end

#pragma mark - FSTArrayValue

@implementation FSTArrayValue

- (id)initWithValueNoCopy:(NSArray<FSTFieldValue *> *)value {
  self = [super init];
  if (self) {
    // Does not copy, assumes the caller has already copied.
    _internalValue = value;
  }
  return self;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[self class]]) {
    return NO;
  }

  // NSArray's isEqual does the right thing for our purposes.
  FSTArrayValue *otherArray = other;
  return [self.internalValue isEqual:otherArray.internalValue];
}

- (NSUInteger)hash {
  return [self.internalValue hash];
}

- (id)value {
  NSMutableArray *result = [NSMutableArray arrayWithCapacity:_internalValue.count];
  [self.internalValue enumerateObjectsUsingBlock:^(FSTFieldValue *obj, NSUInteger idx, BOOL *stop) {
    [result addObject:[obj value]];
  }];
  return result;
}

- (id)valueWithOptions:(FSTFieldValueOptions *)options {
  NSMutableArray *result = [NSMutableArray arrayWithCapacity:_internalValue.count];
  [self.internalValue enumerateObjectsUsingBlock:^(FSTFieldValue *obj, NSUInteger idx, BOOL *stop) {
    [result addObject:[obj valueWithOptions:options]];
  }];
  return result;
}

- (FSTTypeOrder)typeOrder {
  return FSTTypeOrderArray;
}

- (NSComparisonResult)compare:(FSTFieldValue *)other {
  if ([other isKindOfClass:[FSTArrayValue class]]) {
    NSArray<FSTFieldValue *> *selfArray = self.internalValue;
    NSArray<FSTFieldValue *> *otherArray = ((FSTArrayValue *)other).internalValue;
    NSUInteger minLength = MIN(selfArray.count, otherArray.count);
    for (NSUInteger i = 0; i < minLength; i++) {
      NSComparisonResult cmp = [selfArray[i] compare:otherArray[i]];
      if (cmp != NSOrderedSame) {
        return cmp;
      }
    }
    return WrapCompare<int64_t>(selfArray.count, otherArray.count);
  } else {
    return [self defaultCompare:other];
  }
}

@end

NS_ASSUME_NONNULL_END