FSTFieldValue.mm 25 KB

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