FSTFieldValue.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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/Model/FSTFieldValue.h"
  17. #import "FIRDocumentSnapshot.h"
  18. #import "FIRTimestamp.h"
  19. #import "Firestore/Source/API/FIRGeoPoint+Internal.h"
  20. #import "Firestore/Source/Model/FSTDocumentKey.h"
  21. #import "Firestore/Source/Util/FSTAssert.h"
  22. #import "Firestore/Source/Util/FSTClasses.h"
  23. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  24. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  25. #include "Firestore/core/src/firebase/firestore/util/comparison.h"
  26. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  27. namespace util = firebase::firestore::util;
  28. using firebase::firestore::model::DatabaseId;
  29. using firebase::firestore::model::FieldPath;
  30. using firebase::firestore::util::Comparator;
  31. using firebase::firestore::util::CompareMixedNumber;
  32. using firebase::firestore::util::DoubleBitwiseEquals;
  33. using firebase::firestore::util::DoubleBitwiseHash;
  34. using firebase::firestore::util::MakeStringView;
  35. using firebase::firestore::util::ReverseOrder;
  36. using firebase::firestore::util::WrapCompare;
  37. NS_ASSUME_NONNULL_BEGIN
  38. #pragma mark - FSTFieldValueOptions
  39. @implementation FSTFieldValueOptions
  40. - (instancetype)initWithServerTimestampBehavior:(FSTServerTimestampBehavior)serverTimestampBehavior
  41. timestampsInSnapshotsEnabled:(BOOL)timestampsInSnapshotsEnabled {
  42. self = [super init];
  43. if (self) {
  44. _serverTimestampBehavior = serverTimestampBehavior;
  45. _timestampsInSnapshotsEnabled = timestampsInSnapshotsEnabled;
  46. }
  47. return self;
  48. }
  49. @end
  50. #pragma mark - FSTFieldValue
  51. @interface FSTFieldValue ()
  52. - (NSComparisonResult)defaultCompare:(FSTFieldValue *)other;
  53. @end
  54. @implementation FSTFieldValue
  55. - (FSTTypeOrder)typeOrder {
  56. @throw FSTAbstractMethodException(); // NOLINT
  57. }
  58. - (id)value {
  59. @throw FSTAbstractMethodException(); // NOLINT
  60. }
  61. - (id)valueWithOptions:(FSTFieldValueOptions *)options {
  62. return [self value];
  63. }
  64. - (BOOL)isEqual:(id)other {
  65. @throw FSTAbstractMethodException(); // NOLINT
  66. }
  67. - (NSUInteger)hash {
  68. @throw FSTAbstractMethodException(); // NOLINT
  69. }
  70. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  71. @throw FSTAbstractMethodException(); // NOLINT
  72. }
  73. - (NSString *)description {
  74. return [[self value] description];
  75. }
  76. - (NSComparisonResult)defaultCompare:(FSTFieldValue *)other {
  77. if (self.typeOrder > other.typeOrder) {
  78. return NSOrderedDescending;
  79. } else {
  80. FSTAssert(self.typeOrder < other.typeOrder,
  81. @"defaultCompare should not be used for values of same type.");
  82. return NSOrderedAscending;
  83. }
  84. }
  85. @end
  86. #pragma mark - FSTNullValue
  87. @implementation FSTNullValue
  88. + (instancetype)nullValue {
  89. static FSTNullValue *sharedInstance = nil;
  90. static dispatch_once_t onceToken;
  91. dispatch_once(&onceToken, ^{
  92. sharedInstance = [[FSTNullValue alloc] init];
  93. });
  94. return sharedInstance;
  95. }
  96. - (FSTTypeOrder)typeOrder {
  97. return FSTTypeOrderNull;
  98. }
  99. - (id)value {
  100. return [NSNull null];
  101. }
  102. - (BOOL)isEqual:(id)other {
  103. return [other isKindOfClass:[self class]];
  104. }
  105. - (NSUInteger)hash {
  106. return 47;
  107. }
  108. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  109. if ([other isKindOfClass:[self class]]) {
  110. return NSOrderedSame;
  111. } else {
  112. return [self defaultCompare:other];
  113. }
  114. }
  115. @end
  116. #pragma mark - FSTBooleanValue
  117. @interface FSTBooleanValue ()
  118. @property(nonatomic, assign, readonly) BOOL internalValue;
  119. @end
  120. @implementation FSTBooleanValue
  121. + (instancetype)trueValue {
  122. static FSTBooleanValue *sharedInstance = nil;
  123. static dispatch_once_t onceToken;
  124. dispatch_once(&onceToken, ^{
  125. sharedInstance = [[FSTBooleanValue alloc] initWithValue:YES];
  126. });
  127. return sharedInstance;
  128. }
  129. + (instancetype)falseValue {
  130. static FSTBooleanValue *sharedInstance = nil;
  131. static dispatch_once_t onceToken;
  132. dispatch_once(&onceToken, ^{
  133. sharedInstance = [[FSTBooleanValue alloc] initWithValue:NO];
  134. });
  135. return sharedInstance;
  136. }
  137. + (instancetype)booleanValue:(BOOL)value {
  138. return value ? [FSTBooleanValue trueValue] : [FSTBooleanValue falseValue];
  139. }
  140. - (id)initWithValue:(BOOL)value {
  141. self = [super init];
  142. if (self) {
  143. _internalValue = value;
  144. }
  145. return self;
  146. }
  147. - (FSTTypeOrder)typeOrder {
  148. return FSTTypeOrderBoolean;
  149. }
  150. - (id)value {
  151. return self.internalValue ? @YES : @NO;
  152. }
  153. - (BOOL)isEqual:(id)other {
  154. // Since we create shared instances for true / false, we can use reference equality.
  155. return self == other;
  156. }
  157. - (NSUInteger)hash {
  158. return self.internalValue ? 1231 : 1237;
  159. }
  160. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  161. if ([other isKindOfClass:[FSTBooleanValue class]]) {
  162. return WrapCompare<bool>(self.internalValue, ((FSTBooleanValue *)other).internalValue);
  163. } else {
  164. return [self defaultCompare:other];
  165. }
  166. }
  167. @end
  168. #pragma mark - FSTNumberValue
  169. @implementation FSTNumberValue
  170. - (FSTTypeOrder)typeOrder {
  171. return FSTTypeOrderNumber;
  172. }
  173. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  174. if (![other isKindOfClass:[FSTNumberValue class]]) {
  175. return [self defaultCompare:other];
  176. } else {
  177. if ([self isKindOfClass:[FSTDoubleValue class]]) {
  178. double thisDouble = ((FSTDoubleValue *)self).internalValue;
  179. if ([other isKindOfClass:[FSTDoubleValue class]]) {
  180. return WrapCompare(thisDouble, ((FSTDoubleValue *)other).internalValue);
  181. } else {
  182. FSTAssert([other isKindOfClass:[FSTIntegerValue class]], @"Unknown number value: %@",
  183. other);
  184. auto result = CompareMixedNumber(thisDouble, ((FSTIntegerValue *)other).internalValue);
  185. return static_cast<NSComparisonResult>(result);
  186. }
  187. } else {
  188. int64_t thisInt = ((FSTIntegerValue *)self).internalValue;
  189. if ([other isKindOfClass:[FSTIntegerValue class]]) {
  190. return WrapCompare(thisInt, ((FSTIntegerValue *)other).internalValue);
  191. } else {
  192. FSTAssert([other isKindOfClass:[FSTDoubleValue class]], @"Unknown number value: %@", other);
  193. double otherDouble = ((FSTDoubleValue *)other).internalValue;
  194. auto result = ReverseOrder(CompareMixedNumber(otherDouble, thisInt));
  195. return static_cast<NSComparisonResult>(result);
  196. }
  197. }
  198. }
  199. }
  200. @end
  201. #pragma mark - FSTIntegerValue
  202. @interface FSTIntegerValue ()
  203. @property(nonatomic, assign, readonly) int64_t internalValue;
  204. @end
  205. @implementation FSTIntegerValue
  206. + (instancetype)integerValue:(int64_t)value {
  207. return [[FSTIntegerValue alloc] initWithValue:value];
  208. }
  209. - (id)initWithValue:(int64_t)value {
  210. self = [super init];
  211. if (self) {
  212. _internalValue = value;
  213. }
  214. return self;
  215. }
  216. - (id)value {
  217. return @(self.internalValue);
  218. }
  219. - (BOOL)isEqual:(id)other {
  220. // NOTE: DoubleValue and LongValue instances may compare: the same, but that doesn't make them
  221. // equal via isEqual:
  222. return [other isKindOfClass:[FSTIntegerValue class]] &&
  223. self.internalValue == ((FSTIntegerValue *)other).internalValue;
  224. }
  225. - (NSUInteger)hash {
  226. return (((NSUInteger)self.internalValue) ^ (NSUInteger)(self.internalValue >> 32));
  227. }
  228. // NOTE: compare: is implemented in NumberValue.
  229. @end
  230. #pragma mark - FSTDoubleValue
  231. @interface FSTDoubleValue ()
  232. @property(nonatomic, assign, readonly) double internalValue;
  233. @end
  234. @implementation FSTDoubleValue
  235. + (instancetype)doubleValue:(double)value {
  236. // Normalize NaNs to match the behavior on the backend (which uses Double.doubletoLongBits()).
  237. if (isnan(value)) {
  238. return [FSTDoubleValue nanValue];
  239. }
  240. return [[FSTDoubleValue alloc] initWithValue:value];
  241. }
  242. + (instancetype)nanValue {
  243. static FSTDoubleValue *sharedInstance = nil;
  244. static dispatch_once_t onceToken;
  245. dispatch_once(&onceToken, ^{
  246. sharedInstance = [[FSTDoubleValue alloc] initWithValue:NAN];
  247. });
  248. return sharedInstance;
  249. }
  250. - (id)initWithValue:(double)value {
  251. self = [super init];
  252. if (self) {
  253. _internalValue = value;
  254. }
  255. return self;
  256. }
  257. - (id)value {
  258. return @(self.internalValue);
  259. }
  260. - (BOOL)isEqual:(id)other {
  261. // NOTE: DoubleValue and LongValue instances may compare: the same, but that doesn't make them
  262. // equal via isEqual:
  263. // NOTE: isEqual: should compare NaN equal to itself and -0.0 not equal to 0.0.
  264. return [other isKindOfClass:[FSTDoubleValue class]] &&
  265. DoubleBitwiseEquals(self.internalValue, ((FSTDoubleValue *)other).internalValue);
  266. }
  267. - (NSUInteger)hash {
  268. return DoubleBitwiseHash(self.internalValue);
  269. }
  270. // NOTE: compare: is implemented in NumberValue.
  271. @end
  272. #pragma mark - FSTStringValue
  273. /**
  274. * Specialization of Comparator for NSStrings.
  275. */
  276. template <>
  277. struct Comparator<NSString *> {
  278. bool operator()(NSString *left, NSString *right) const {
  279. Comparator<absl::string_view> lessThan;
  280. return lessThan(MakeStringView(left), MakeStringView(right));
  281. }
  282. };
  283. @interface FSTStringValue ()
  284. @property(nonatomic, copy, readonly) NSString *internalValue;
  285. @end
  286. // TODO(b/37267885): Add truncation support
  287. @implementation FSTStringValue
  288. + (instancetype)stringValue:(NSString *)value {
  289. return [[FSTStringValue alloc] initWithValue:value];
  290. }
  291. - (id)initWithValue:(NSString *)value {
  292. self = [super init];
  293. if (self) {
  294. _internalValue = [value copy];
  295. }
  296. return self;
  297. }
  298. - (FSTTypeOrder)typeOrder {
  299. return FSTTypeOrderString;
  300. }
  301. - (id)value {
  302. return self.internalValue;
  303. }
  304. - (BOOL)isEqual:(id)other {
  305. return [other isKindOfClass:[FSTStringValue class]] &&
  306. [self.internalValue isEqualToString:((FSTStringValue *)other).internalValue];
  307. }
  308. - (NSUInteger)hash {
  309. return self.internalValue ? 1 : 0;
  310. }
  311. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  312. if ([other isKindOfClass:[FSTStringValue class]]) {
  313. return WrapCompare(self.internalValue, ((FSTStringValue *)other).internalValue);
  314. } else {
  315. return [self defaultCompare:other];
  316. }
  317. }
  318. @end
  319. #pragma mark - FSTTimestampValue
  320. @interface FSTTimestampValue ()
  321. @property(nonatomic, strong, readonly) FIRTimestamp *internalValue;
  322. @end
  323. @implementation FSTTimestampValue
  324. + (instancetype)timestampValue:(FIRTimestamp *)value {
  325. return [[FSTTimestampValue alloc] initWithValue:value];
  326. }
  327. - (id)initWithValue:(FIRTimestamp *)value {
  328. self = [super init];
  329. if (self) {
  330. _internalValue = value; // FIRTimestamp is immutable.
  331. }
  332. return self;
  333. }
  334. - (FSTTypeOrder)typeOrder {
  335. return FSTTypeOrderTimestamp;
  336. }
  337. - (id)value {
  338. return self.internalValue;
  339. }
  340. - (id)valueWithOptions:(FSTFieldValueOptions *)options {
  341. if (options.timestampsInSnapshotsEnabled) {
  342. return self.value;
  343. } else {
  344. return [self.value dateValue];
  345. }
  346. }
  347. - (BOOL)isEqual:(id)other {
  348. return [other isKindOfClass:[FSTTimestampValue class]] &&
  349. [self.internalValue isEqual:((FSTTimestampValue *)other).internalValue];
  350. }
  351. - (NSUInteger)hash {
  352. return [self.internalValue hash];
  353. }
  354. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  355. if ([other isKindOfClass:[FSTTimestampValue class]]) {
  356. return [self.internalValue compare:((FSTTimestampValue *)other).internalValue];
  357. } else if ([other isKindOfClass:[FSTServerTimestampValue class]]) {
  358. // Concrete timestamps come before server timestamps.
  359. return NSOrderedAscending;
  360. } else {
  361. return [self defaultCompare:other];
  362. }
  363. }
  364. @end
  365. #pragma mark - FSTServerTimestampValue
  366. @implementation FSTServerTimestampValue
  367. + (instancetype)serverTimestampValueWithLocalWriteTime:(FIRTimestamp *)localWriteTime
  368. previousValue:(nullable FSTFieldValue *)previousValue {
  369. return [[FSTServerTimestampValue alloc] initWithLocalWriteTime:localWriteTime
  370. previousValue:previousValue];
  371. }
  372. - (id)initWithLocalWriteTime:(FIRTimestamp *)localWriteTime
  373. previousValue:(nullable FSTFieldValue *)previousValue {
  374. self = [super init];
  375. if (self) {
  376. _localWriteTime = localWriteTime;
  377. _previousValue = previousValue;
  378. }
  379. return self;
  380. }
  381. - (FSTTypeOrder)typeOrder {
  382. return FSTTypeOrderTimestamp;
  383. }
  384. - (id)value {
  385. return [NSNull null];
  386. }
  387. - (id)valueWithOptions:(FSTFieldValueOptions *)options {
  388. switch (options.serverTimestampBehavior) {
  389. case FSTServerTimestampBehaviorNone:
  390. return [NSNull null];
  391. case FSTServerTimestampBehaviorEstimate:
  392. return [[FSTTimestampValue timestampValue:self.localWriteTime] valueWithOptions:options];
  393. case FSTServerTimestampBehaviorPrevious:
  394. return self.previousValue ? [self.previousValue valueWithOptions:options] : [NSNull null];
  395. default:
  396. FSTFail(@"Unexpected server timestamp option: %ld", (long)options.serverTimestampBehavior);
  397. }
  398. }
  399. - (BOOL)isEqual:(id)other {
  400. return [other isKindOfClass:[FSTServerTimestampValue class]] &&
  401. [self.localWriteTime isEqual:((FSTServerTimestampValue *)other).localWriteTime];
  402. }
  403. - (NSUInteger)hash {
  404. return [self.localWriteTime hash];
  405. }
  406. - (NSString *)description {
  407. return [NSString stringWithFormat:@"<ServerTimestamp localTime=%@>", self.localWriteTime];
  408. }
  409. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  410. if ([other isKindOfClass:[FSTServerTimestampValue class]]) {
  411. return [self.localWriteTime compare:((FSTServerTimestampValue *)other).localWriteTime];
  412. } else if ([other isKindOfClass:[FSTTimestampValue class]]) {
  413. // Server timestamps come after all concrete timestamps.
  414. return NSOrderedDescending;
  415. } else {
  416. return [self defaultCompare:other];
  417. }
  418. }
  419. @end
  420. #pragma mark - FSTGeoPointValue
  421. @interface FSTGeoPointValue ()
  422. @property(nonatomic, strong, readonly) FIRGeoPoint *internalValue;
  423. @end
  424. @implementation FSTGeoPointValue
  425. + (instancetype)geoPointValue:(FIRGeoPoint *)value {
  426. return [[FSTGeoPointValue alloc] initWithValue:value];
  427. }
  428. - (id)initWithValue:(FIRGeoPoint *)value {
  429. self = [super init];
  430. if (self) {
  431. _internalValue = value; // FIRGeoPoint is immutable.
  432. }
  433. return self;
  434. }
  435. - (FSTTypeOrder)typeOrder {
  436. return FSTTypeOrderGeoPoint;
  437. }
  438. - (id)value {
  439. return self.internalValue;
  440. }
  441. - (BOOL)isEqual:(id)other {
  442. return [other isKindOfClass:[FSTGeoPointValue class]] &&
  443. [self.internalValue isEqual:((FSTGeoPointValue *)other).internalValue];
  444. }
  445. - (NSUInteger)hash {
  446. return [self.internalValue hash];
  447. }
  448. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  449. if ([other isKindOfClass:[FSTGeoPointValue class]]) {
  450. return [self.internalValue compare:((FSTGeoPointValue *)other).internalValue];
  451. } else {
  452. return [self defaultCompare:other];
  453. }
  454. }
  455. @end
  456. #pragma mark - FSTBlobValue
  457. static NSComparisonResult CompareBytes(NSData *left, NSData *right) {
  458. NSUInteger minLength = MIN(left.length, right.length);
  459. int result = memcmp(left.bytes, right.bytes, minLength);
  460. if (result < 0) {
  461. return NSOrderedAscending;
  462. } else if (result > 0) {
  463. return NSOrderedDescending;
  464. } else if (left.length < right.length) {
  465. return NSOrderedAscending;
  466. } else if (left.length > right.length) {
  467. return NSOrderedDescending;
  468. } else {
  469. return NSOrderedSame;
  470. }
  471. }
  472. @interface FSTBlobValue ()
  473. @property(nonatomic, copy, readonly) NSData *internalValue;
  474. @end
  475. // TODO(b/37267885): Add truncation support
  476. @implementation FSTBlobValue
  477. + (instancetype)blobValue:(NSData *)value {
  478. return [[FSTBlobValue alloc] initWithValue:value];
  479. }
  480. - (id)initWithValue:(NSData *)value {
  481. self = [super init];
  482. if (self) {
  483. _internalValue = [value copy];
  484. }
  485. return self;
  486. }
  487. - (FSTTypeOrder)typeOrder {
  488. return FSTTypeOrderBlob;
  489. }
  490. - (id)value {
  491. return self.internalValue;
  492. }
  493. - (BOOL)isEqual:(id)other {
  494. return [other isKindOfClass:[FSTBlobValue class]] &&
  495. [self.internalValue isEqual:((FSTBlobValue *)other).internalValue];
  496. }
  497. - (NSUInteger)hash {
  498. return [self.internalValue hash];
  499. }
  500. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  501. if ([other isKindOfClass:[FSTBlobValue class]]) {
  502. return CompareBytes(self.internalValue, ((FSTBlobValue *)other).internalValue);
  503. } else {
  504. return [self defaultCompare:other];
  505. }
  506. }
  507. @end
  508. #pragma mark - FSTReferenceValue
  509. @interface FSTReferenceValue ()
  510. @property(nonatomic, strong, readonly) FSTDocumentKey *key;
  511. @end
  512. @implementation FSTReferenceValue
  513. + (instancetype)referenceValue:(FSTDocumentKey *)value databaseID:(const DatabaseId *)databaseID {
  514. return [[FSTReferenceValue alloc] initWithValue:value databaseID:databaseID];
  515. }
  516. - (id)initWithValue:(FSTDocumentKey *)value databaseID:(const DatabaseId *)databaseID {
  517. self = [super init];
  518. if (self) {
  519. _key = value;
  520. _databaseID = databaseID;
  521. }
  522. return self;
  523. }
  524. - (id)value {
  525. return self.key;
  526. }
  527. - (FSTTypeOrder)typeOrder {
  528. return FSTTypeOrderReference;
  529. }
  530. - (BOOL)isEqual:(id)other {
  531. if (other == self) {
  532. return YES;
  533. }
  534. if (![other isKindOfClass:[FSTReferenceValue class]]) {
  535. return NO;
  536. }
  537. FSTReferenceValue *otherRef = (FSTReferenceValue *)other;
  538. return [self.key isEqualToKey:otherRef.key] && *self.databaseID == *otherRef.databaseID;
  539. }
  540. - (NSUInteger)hash {
  541. NSUInteger result = self.databaseID->Hash();
  542. result = 31 * result + [self.key hash];
  543. return result;
  544. }
  545. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  546. if ([other isKindOfClass:[FSTReferenceValue class]]) {
  547. FSTReferenceValue *ref = (FSTReferenceValue *)other;
  548. NSComparisonResult cmp = [util::WrapNSStringNoCopy(self.databaseID->project_id())
  549. compare:util::WrapNSStringNoCopy(ref.databaseID->project_id())];
  550. if (cmp != NSOrderedSame) {
  551. return cmp;
  552. }
  553. cmp = [util::WrapNSStringNoCopy(self.databaseID->database_id())
  554. compare:util::WrapNSStringNoCopy(ref.databaseID->database_id())];
  555. return cmp != NSOrderedSame ? cmp : [self.key compare:ref.key];
  556. } else {
  557. return [self defaultCompare:other];
  558. }
  559. }
  560. @end
  561. #pragma mark - FSTObjectValue
  562. static const NSComparator StringComparator = ^NSComparisonResult(NSString *left, NSString *right) {
  563. return WrapCompare(left, right);
  564. };
  565. @interface FSTObjectValue ()
  566. @property(nonatomic, strong, readonly)
  567. FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *internalValue;
  568. @end
  569. @implementation FSTObjectValue
  570. + (instancetype)objectValue {
  571. static FSTObjectValue *sharedEmptyInstance = nil;
  572. static dispatch_once_t onceToken;
  573. dispatch_once(&onceToken, ^{
  574. FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *empty =
  575. [FSTImmutableSortedDictionary dictionaryWithComparator:StringComparator];
  576. sharedEmptyInstance = [[FSTObjectValue alloc] initWithImmutableDictionary:empty];
  577. });
  578. return sharedEmptyInstance;
  579. }
  580. - (instancetype)initWithImmutableDictionary:
  581. (FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *)value {
  582. self = [super init];
  583. if (self) {
  584. _internalValue = value; // FSTImmutableSortedDictionary is immutable.
  585. }
  586. return self;
  587. }
  588. - (id)initWithDictionary:(NSDictionary<NSString *, FSTFieldValue *> *)value {
  589. FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *dictionary =
  590. [FSTImmutableSortedDictionary dictionaryWithDictionary:value comparator:StringComparator];
  591. return [self initWithImmutableDictionary:dictionary];
  592. }
  593. - (id)value {
  594. NSMutableDictionary *result = [NSMutableDictionary dictionary];
  595. [self.internalValue
  596. enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
  597. result[key] = [obj value];
  598. }];
  599. return result;
  600. }
  601. - (id)valueWithOptions:(FSTFieldValueOptions *)options {
  602. NSMutableDictionary *result = [NSMutableDictionary dictionary];
  603. [self.internalValue
  604. enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
  605. result[key] = [obj valueWithOptions:options];
  606. }];
  607. return result;
  608. }
  609. - (FSTTypeOrder)typeOrder {
  610. return FSTTypeOrderObject;
  611. }
  612. - (BOOL)isEqual:(id)other {
  613. if (other == self) {
  614. return YES;
  615. }
  616. if (![other isKindOfClass:[FSTObjectValue class]]) {
  617. return NO;
  618. }
  619. FSTObjectValue *otherObj = other;
  620. return [self.internalValue isEqual:otherObj.internalValue];
  621. }
  622. - (NSUInteger)hash {
  623. return [self.internalValue hash];
  624. }
  625. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  626. if ([other isKindOfClass:[FSTObjectValue class]]) {
  627. FSTImmutableSortedDictionary *selfDict = self.internalValue;
  628. FSTImmutableSortedDictionary *otherDict = ((FSTObjectValue *)other).internalValue;
  629. NSEnumerator *enumerator1 = [selfDict keyEnumerator];
  630. NSEnumerator *enumerator2 = [otherDict keyEnumerator];
  631. NSString *key1 = [enumerator1 nextObject];
  632. NSString *key2 = [enumerator2 nextObject];
  633. while (key1 && key2) {
  634. NSComparisonResult keyCompare = [key1 compare:key2];
  635. if (keyCompare != NSOrderedSame) {
  636. return keyCompare;
  637. }
  638. NSComparisonResult valueCompare = [selfDict[key1] compare:otherDict[key2]];
  639. if (valueCompare != NSOrderedSame) {
  640. return valueCompare;
  641. }
  642. key1 = [enumerator1 nextObject];
  643. key2 = [enumerator2 nextObject];
  644. }
  645. // Only equal if both enumerators are exhausted.
  646. return WrapCompare(key1 != nil, key2 != nil);
  647. } else {
  648. return [self defaultCompare:other];
  649. }
  650. }
  651. - (nullable FSTFieldValue *)valueForPath:(const FieldPath &)fieldPath {
  652. FSTFieldValue *value = self;
  653. for (size_t i = 0, max = fieldPath.size(); value && i < max; i++) {
  654. if (![value isMemberOfClass:[FSTObjectValue class]]) {
  655. return nil;
  656. }
  657. NSString *fieldName = util::WrapNSStringNoCopy(fieldPath[i]);
  658. value = ((FSTObjectValue *)value).internalValue[fieldName];
  659. }
  660. return value;
  661. }
  662. - (FSTObjectValue *)objectBySettingValue:(FSTFieldValue *)value
  663. forPath:(const FieldPath &)fieldPath {
  664. FSTAssert(fieldPath.size() > 0, @"Cannot set value with an empty path");
  665. NSString *childName = util::WrapNSString(fieldPath.first_segment());
  666. if (fieldPath.size() == 1) {
  667. // Recursive base case:
  668. return [self objectBySettingValue:value forField:childName];
  669. } else {
  670. // Nested path. Recursively generate a new sub-object and then wrap a new FSTObjectValue
  671. // around the result.
  672. FSTFieldValue *child = [_internalValue objectForKey:childName];
  673. FSTObjectValue *childObject;
  674. if ([child isKindOfClass:[FSTObjectValue class]]) {
  675. childObject = (FSTObjectValue *)child;
  676. } else {
  677. // If the child is not found or is a primitive type, pretend as if an empty object lived
  678. // there.
  679. childObject = [FSTObjectValue objectValue];
  680. }
  681. FSTFieldValue *newChild = [childObject objectBySettingValue:value forPath:fieldPath.PopFirst()];
  682. return [self objectBySettingValue:newChild forField:childName];
  683. }
  684. }
  685. - (FSTObjectValue *)objectByDeletingPath:(const FieldPath &)fieldPath {
  686. FSTAssert(fieldPath.size() > 0, @"Cannot delete an empty path");
  687. NSString *childName = util::WrapNSString(fieldPath.first_segment());
  688. if (fieldPath.size() == 1) {
  689. return [[FSTObjectValue alloc]
  690. initWithImmutableDictionary:[_internalValue dictionaryByRemovingObjectForKey:childName]];
  691. } else {
  692. FSTFieldValue *child = _internalValue[childName];
  693. if ([child isKindOfClass:[FSTObjectValue class]]) {
  694. FSTObjectValue *newChild =
  695. [((FSTObjectValue *)child) objectByDeletingPath:fieldPath.PopFirst()];
  696. return [self objectBySettingValue:newChild forField:childName];
  697. } else {
  698. // If the child is not found or is a primitive type, make no modifications
  699. return self;
  700. }
  701. }
  702. }
  703. - (FSTObjectValue *)objectBySettingValue:(FSTFieldValue *)value forField:(NSString *)field {
  704. return [[FSTObjectValue alloc]
  705. initWithImmutableDictionary:[_internalValue dictionaryBySettingObject:value forKey:field]];
  706. }
  707. @end
  708. @interface FSTArrayValue ()
  709. @property(nonatomic, strong, readonly) NSArray<FSTFieldValue *> *internalValue;
  710. @end
  711. #pragma mark - FSTArrayValue
  712. @implementation FSTArrayValue
  713. - (id)initWithValueNoCopy:(NSArray<FSTFieldValue *> *)value {
  714. self = [super init];
  715. if (self) {
  716. // Does not copy, assumes the caller has already copied.
  717. _internalValue = value;
  718. }
  719. return self;
  720. }
  721. - (BOOL)isEqual:(id)other {
  722. if (other == self) {
  723. return YES;
  724. }
  725. if (![other isKindOfClass:[self class]]) {
  726. return NO;
  727. }
  728. // NSArray's isEqual does the right thing for our purposes.
  729. FSTArrayValue *otherArray = other;
  730. return [self.internalValue isEqual:otherArray.internalValue];
  731. }
  732. - (NSUInteger)hash {
  733. return [self.internalValue hash];
  734. }
  735. - (id)value {
  736. NSMutableArray *result = [NSMutableArray arrayWithCapacity:_internalValue.count];
  737. [self.internalValue enumerateObjectsUsingBlock:^(FSTFieldValue *obj, NSUInteger idx, BOOL *stop) {
  738. [result addObject:[obj value]];
  739. }];
  740. return result;
  741. }
  742. - (id)valueWithOptions:(FSTFieldValueOptions *)options {
  743. NSMutableArray *result = [NSMutableArray arrayWithCapacity:_internalValue.count];
  744. [self.internalValue enumerateObjectsUsingBlock:^(FSTFieldValue *obj, NSUInteger idx, BOOL *stop) {
  745. [result addObject:[obj valueWithOptions:options]];
  746. }];
  747. return result;
  748. }
  749. - (FSTTypeOrder)typeOrder {
  750. return FSTTypeOrderArray;
  751. }
  752. - (NSComparisonResult)compare:(FSTFieldValue *)other {
  753. if ([other isKindOfClass:[FSTArrayValue class]]) {
  754. NSArray<FSTFieldValue *> *selfArray = self.internalValue;
  755. NSArray<FSTFieldValue *> *otherArray = ((FSTArrayValue *)other).internalValue;
  756. NSUInteger minLength = MIN(selfArray.count, otherArray.count);
  757. for (NSUInteger i = 0; i < minLength; i++) {
  758. NSComparisonResult cmp = [selfArray[i] compare:otherArray[i]];
  759. if (cmp != NSOrderedSame) {
  760. return cmp;
  761. }
  762. }
  763. return WrapCompare<int64_t>(selfArray.count, otherArray.count);
  764. } else {
  765. return [self defaultCompare:other];
  766. }
  767. }
  768. @end
  769. NS_ASSUME_NONNULL_END