FSTFieldValue.mm 26 KB

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