FSTFieldValue.mm 26 KB

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