FSTUserDataConverter.mm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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/API/FSTUserDataConverter.h"
  17. #include <memory>
  18. #include <utility>
  19. #include <vector>
  20. #import "FIRTimestamp.h"
  21. #import "FIRGeoPoint.h"
  22. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  23. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  24. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  25. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  26. #import "Firestore/Source/API/FIRSetOptions+Internal.h"
  27. #import "Firestore/Source/Model/FSTFieldValue.h"
  28. #import "Firestore/Source/Model/FSTMutation.h"
  29. #import "Firestore/Source/Util/FSTAssert.h"
  30. #import "Firestore/Source/Util/FSTUsageValidation.h"
  31. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  32. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  33. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  34. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  35. #include "absl/memory/memory.h"
  36. namespace util = firebase::firestore::util;
  37. using firebase::firestore::model::DatabaseId;
  38. using firebase::firestore::model::DocumentKey;
  39. using firebase::firestore::model::FieldPath;
  40. NS_ASSUME_NONNULL_BEGIN
  41. static NSString *const RESERVED_FIELD_DESIGNATOR = @"__";
  42. #pragma mark - FSTParsedSetData
  43. @implementation FSTParsedSetData
  44. - (instancetype)initWithData:(FSTObjectValue *)data
  45. fieldMask:(nullable FSTFieldMask *)fieldMask
  46. fieldTransforms:(NSArray<FSTFieldTransform *> *)fieldTransforms {
  47. self = [super init];
  48. if (self) {
  49. _data = data;
  50. _fieldMask = fieldMask;
  51. _fieldTransforms = fieldTransforms;
  52. }
  53. return self;
  54. }
  55. - (NSArray<FSTMutation *> *)mutationsWithKey:(const DocumentKey &)key
  56. precondition:(FSTPrecondition *)precondition {
  57. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  58. if (self.fieldMask) {
  59. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  60. fieldMask:self.fieldMask
  61. value:self.data
  62. precondition:precondition]];
  63. } else {
  64. [mutations addObject:[[FSTSetMutation alloc] initWithKey:key
  65. value:self.data
  66. precondition:precondition]];
  67. }
  68. if (self.fieldTransforms.count > 0) {
  69. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  70. fieldTransforms:self.fieldTransforms]];
  71. }
  72. return mutations;
  73. }
  74. @end
  75. #pragma mark - FSTParsedUpdateData
  76. @implementation FSTParsedUpdateData
  77. - (instancetype)initWithData:(FSTObjectValue *)data
  78. fieldMask:(FSTFieldMask *)fieldMask
  79. fieldTransforms:(NSArray<FSTFieldTransform *> *)fieldTransforms {
  80. self = [super init];
  81. if (self) {
  82. _data = data;
  83. _fieldMask = fieldMask;
  84. _fieldTransforms = fieldTransforms;
  85. }
  86. return self;
  87. }
  88. - (NSArray<FSTMutation *> *)mutationsWithKey:(const DocumentKey &)key
  89. precondition:(FSTPrecondition *)precondition {
  90. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  91. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  92. fieldMask:self.fieldMask
  93. value:self.data
  94. precondition:precondition]];
  95. if (self.fieldTransforms.count > 0) {
  96. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  97. fieldTransforms:self.fieldTransforms]];
  98. }
  99. return mutations;
  100. }
  101. @end
  102. /**
  103. * Represents what type of API method provided the data being parsed; useful for determining which
  104. * error conditions apply during parsing and providing better error messages.
  105. */
  106. typedef NS_ENUM(NSInteger, FSTUserDataSource) {
  107. FSTUserDataSourceSet,
  108. FSTUserDataSourceMergeSet,
  109. FSTUserDataSourceUpdate,
  110. FSTUserDataSourceQueryValue, // from a where clause or cursor bound.
  111. };
  112. #pragma mark - FSTParseContext
  113. /**
  114. * A "context" object passed around while parsing user data.
  115. */
  116. @interface FSTParseContext : NSObject
  117. /** Whether or not this context corresponds to an element of an array. */
  118. @property(nonatomic, assign, readonly, getter=isArrayElement) BOOL arrayElement;
  119. /**
  120. * What type of API method provided the data being parsed; useful for determining which error
  121. * conditions apply during parsing and providing better error messages.
  122. */
  123. @property(nonatomic, assign) FSTUserDataSource dataSource;
  124. @property(nonatomic, strong, readonly) NSMutableArray<FSTFieldTransform *> *fieldTransforms;
  125. - (instancetype)init NS_UNAVAILABLE;
  126. /**
  127. * Initializes a FSTParseContext with the given source and path.
  128. *
  129. * @param dataSource Indicates what kind of API method this data came from.
  130. * @param path A path within the object being parsed. This could be an empty path (in which case
  131. * the context represents the root of the data being parsed), or a nonempty path (indicating the
  132. * context represents a nested location within the data).
  133. *
  134. * TODO(b/34871131): We don't support array paths right now, so path can be nullptr to indicate
  135. * the context represents any location within an array (in which case certain features will not work
  136. * and errors will be somewhat compromised).
  137. */
  138. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  139. path:(std::unique_ptr<FieldPath>)path
  140. arrayElement:(BOOL)arrayElement
  141. fieldTransforms:(NSMutableArray<FSTFieldTransform *> *)fieldTransforms
  142. fieldMask:(std::shared_ptr<std::vector<FieldPath>>)fieldMask
  143. NS_DESIGNATED_INITIALIZER;
  144. // Helpers to get a FSTParseContext for a child field.
  145. - (instancetype)contextForField:(NSString *)fieldName;
  146. - (instancetype)contextForFieldPath:(const FieldPath &)fieldPath;
  147. - (instancetype)contextForArrayIndex:(NSUInteger)index;
  148. /** Returns true for the non-query parse contexts (Set, MergeSet and Update) */
  149. - (BOOL)isWrite;
  150. - (const FieldPath *)path;
  151. - (const std::vector<FieldPath> *)fieldMask;
  152. - (void)appendToFieldMaskWithFieldPath:(FieldPath)fieldPath;
  153. @end
  154. @implementation FSTParseContext {
  155. /** The current path being parsed. */
  156. // TODO(b/34871131): path should never be nullptr, but we don't support array paths right now.
  157. std::unique_ptr<FieldPath> _path;
  158. // _fieldMask is shared across all active context objects to accumulate the result. For example,
  159. // the result of calling any of contextForField, contextForFieldPath and contextForArrayIndex
  160. // shares the ownership of _fieldMask.
  161. std::shared_ptr<std::vector<FieldPath>> _fieldMask;
  162. }
  163. + (instancetype)contextWithSource:(FSTUserDataSource)dataSource
  164. path:(std::unique_ptr<FieldPath>)path {
  165. FSTParseContext *context =
  166. [[FSTParseContext alloc] initWithSource:dataSource
  167. path:std::move(path)
  168. arrayElement:NO
  169. fieldTransforms:[NSMutableArray array]
  170. fieldMask:std::make_shared<std::vector<FieldPath>>()];
  171. [context validatePath];
  172. return context;
  173. }
  174. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  175. path:(std::unique_ptr<FieldPath>)path
  176. arrayElement:(BOOL)arrayElement
  177. fieldTransforms:(NSMutableArray<FSTFieldTransform *> *)fieldTransforms
  178. fieldMask:(std::shared_ptr<std::vector<FieldPath>>)fieldMask {
  179. if (self = [super init]) {
  180. _dataSource = dataSource;
  181. _path = std::move(path);
  182. _arrayElement = arrayElement;
  183. _fieldTransforms = fieldTransforms;
  184. _fieldMask = std::move(fieldMask);
  185. }
  186. return self;
  187. }
  188. - (instancetype)contextForField:(NSString *)fieldName {
  189. std::unique_ptr<FieldPath> path{};
  190. if (_path) {
  191. path = absl::make_unique<FieldPath>(_path->Append(util::MakeString(fieldName)));
  192. }
  193. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:self.dataSource
  194. path:std::move(path)
  195. arrayElement:NO
  196. fieldTransforms:self.fieldTransforms
  197. fieldMask:_fieldMask];
  198. [context validatePathSegment:fieldName];
  199. return context;
  200. }
  201. - (instancetype)contextForFieldPath:(const FieldPath &)fieldPath {
  202. std::unique_ptr<FieldPath> path{};
  203. if (_path) {
  204. path = absl::make_unique<FieldPath>(_path->Append(fieldPath));
  205. }
  206. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:self.dataSource
  207. path:std::move(path)
  208. arrayElement:NO
  209. fieldTransforms:self.fieldTransforms
  210. fieldMask:_fieldMask];
  211. [context validatePath];
  212. return context;
  213. }
  214. - (instancetype)contextForArrayIndex:(NSUInteger)index {
  215. // TODO(b/34871131): We don't support array paths right now; so make path nil.
  216. return [[FSTParseContext alloc] initWithSource:self.dataSource
  217. path:nil
  218. arrayElement:YES
  219. fieldTransforms:self.fieldTransforms
  220. fieldMask:_fieldMask];
  221. }
  222. /**
  223. * Returns a string that can be appended to error messages indicating what field caused the error.
  224. */
  225. - (NSString *)fieldDescription {
  226. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  227. if (!_path || _path->empty()) {
  228. return @"";
  229. } else {
  230. return [NSString stringWithFormat:@" (found in field %s)", _path->CanonicalString().c_str()];
  231. }
  232. }
  233. - (BOOL)isWrite {
  234. switch (self.dataSource) {
  235. case FSTUserDataSourceSet: // Falls through.
  236. case FSTUserDataSourceMergeSet: // Falls through.
  237. case FSTUserDataSourceUpdate:
  238. return YES;
  239. case FSTUserDataSourceQueryValue:
  240. return NO;
  241. default:
  242. FSTThrowInvalidArgument(@"Unexpected case for FSTUserDataSource: %d", self.dataSource);
  243. }
  244. }
  245. - (void)validatePath {
  246. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  247. if (_path == nullptr) {
  248. return;
  249. }
  250. for (const auto &segment : *_path) {
  251. [self validatePathSegment:util::WrapNSStringNoCopy(segment)];
  252. }
  253. }
  254. - (void)validatePathSegment:(NSString *)segment {
  255. if ([self isWrite] && [segment hasPrefix:RESERVED_FIELD_DESIGNATOR] &&
  256. [segment hasSuffix:RESERVED_FIELD_DESIGNATOR]) {
  257. FSTThrowInvalidArgument(@"Document fields cannot begin and end with %@%@",
  258. RESERVED_FIELD_DESIGNATOR, [self fieldDescription]);
  259. }
  260. }
  261. - (const FieldPath *)path {
  262. return _path.get();
  263. }
  264. - (const std::vector<FieldPath> *)fieldMask {
  265. return _fieldMask.get();
  266. }
  267. - (void)appendToFieldMaskWithFieldPath:(FieldPath)fieldPath {
  268. _fieldMask->push_back(std::move(fieldPath));
  269. }
  270. @end
  271. #pragma mark - FSTDocumentKeyReference
  272. @implementation FSTDocumentKeyReference {
  273. DocumentKey _key;
  274. }
  275. - (instancetype)initWithKey:(DocumentKey)key databaseID:(const DatabaseId *)databaseID {
  276. self = [super init];
  277. if (self) {
  278. _key = std::move(key);
  279. _databaseID = databaseID;
  280. }
  281. return self;
  282. }
  283. - (const firebase::firestore::model::DocumentKey &)key {
  284. return _key;
  285. }
  286. @end
  287. #pragma mark - FSTUserDataConverter
  288. @interface FSTUserDataConverter ()
  289. // Does not own the DatabaseId instance.
  290. @property(assign, nonatomic, readonly) const DatabaseId *databaseID;
  291. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  292. @end
  293. @implementation FSTUserDataConverter
  294. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID
  295. preConverter:(FSTPreConverterBlock)preConverter {
  296. self = [super init];
  297. if (self) {
  298. _databaseID = databaseID;
  299. _preConverter = preConverter;
  300. }
  301. return self;
  302. }
  303. - (FSTParsedSetData *)parsedMergeData:(id)input {
  304. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  305. // Obj-C to verify the type for us.
  306. if (![input isKindOfClass:[NSDictionary class]]) {
  307. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  308. }
  309. FSTParseContext *context =
  310. [FSTParseContext contextWithSource:FSTUserDataSourceMergeSet
  311. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  312. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  313. return [[FSTParsedSetData alloc]
  314. initWithData:updateData
  315. fieldMask:[[FSTFieldMask alloc] initWithFields:*context.fieldMask]
  316. fieldTransforms:context.fieldTransforms];
  317. }
  318. - (FSTParsedSetData *)parsedSetData:(id)input {
  319. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  320. // Obj-C to verify the type for us.
  321. if (![input isKindOfClass:[NSDictionary class]]) {
  322. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  323. }
  324. FSTParseContext *context =
  325. [FSTParseContext contextWithSource:FSTUserDataSourceSet
  326. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  327. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  328. return [[FSTParsedSetData alloc] initWithData:updateData
  329. fieldMask:nil
  330. fieldTransforms:context.fieldTransforms];
  331. }
  332. - (FSTParsedUpdateData *)parsedUpdateData:(id)input {
  333. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  334. // Obj-C to verify the type for us.
  335. if (![input isKindOfClass:[NSDictionary class]]) {
  336. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  337. }
  338. NSDictionary *dict = input;
  339. __block std::vector<FieldPath> fieldMaskPaths{};
  340. __block FSTObjectValue *updateData = [FSTObjectValue objectValue];
  341. FSTParseContext *context =
  342. [FSTParseContext contextWithSource:FSTUserDataSourceUpdate
  343. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  344. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  345. FieldPath path{};
  346. if ([key isKindOfClass:[NSString class]]) {
  347. path = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  348. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  349. path = ((FIRFieldPath *)key).internalValue;
  350. } else {
  351. FSTThrowInvalidArgument(
  352. @"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  353. }
  354. value = self.preConverter(value);
  355. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  356. // Add it to the field mask, but don't add anything to updateData.
  357. fieldMaskPaths.push_back(path);
  358. } else {
  359. FSTFieldValue *_Nullable parsedValue =
  360. [self parseData:value context:[context contextForFieldPath:path]];
  361. if (parsedValue) {
  362. fieldMaskPaths.push_back(path);
  363. updateData = [updateData objectBySettingValue:parsedValue forPath:path];
  364. }
  365. }
  366. }];
  367. FSTFieldMask *mask = [[FSTFieldMask alloc] initWithFields:fieldMaskPaths];
  368. return [[FSTParsedUpdateData alloc] initWithData:updateData
  369. fieldMask:mask
  370. fieldTransforms:context.fieldTransforms];
  371. }
  372. - (FSTFieldValue *)parsedQueryValue:(id)input {
  373. FSTParseContext *context =
  374. [FSTParseContext contextWithSource:FSTUserDataSourceQueryValue
  375. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  376. FSTFieldValue *_Nullable parsed = [self parseData:input context:context];
  377. FSTAssert(parsed, @"Parsed data should not be nil.");
  378. FSTAssert(context.fieldTransforms.count == 0, @"Field transforms should have been disallowed.");
  379. return parsed;
  380. }
  381. /**
  382. * Internal helper for parsing user data.
  383. *
  384. * @param input Data to be parsed.
  385. * @param context A context object representing the current path being parsed, the source of the
  386. * data being parsed, etc.
  387. *
  388. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  389. * included in the resulting parsed data.
  390. */
  391. - (nullable FSTFieldValue *)parseData:(id)input context:(FSTParseContext *)context {
  392. input = self.preConverter(input);
  393. if ([input isKindOfClass:[NSArray class]]) {
  394. // TODO(b/34871131): Include the path containing the array in the error message.
  395. if (context.isArrayElement) {
  396. FSTThrowInvalidArgument(@"Nested arrays are not supported");
  397. }
  398. NSArray *array = input;
  399. NSMutableArray<FSTFieldValue *> *result = [NSMutableArray arrayWithCapacity:array.count];
  400. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *stop) {
  401. FSTFieldValue *_Nullable parsedEntry =
  402. [self parseData:entry context:[context contextForArrayIndex:idx]];
  403. if (!parsedEntry) {
  404. // Just include nulls in the array for fields being replaced with a sentinel.
  405. parsedEntry = [FSTNullValue nullValue];
  406. }
  407. [result addObject:parsedEntry];
  408. }];
  409. // If context.path is nil we are already inside an array and we don't support field mask paths
  410. // more granular than the top-level array.
  411. if (context.path) {
  412. [context appendToFieldMaskWithFieldPath:*context.path];
  413. }
  414. return [[FSTArrayValue alloc] initWithValueNoCopy:result];
  415. } else if ([input isKindOfClass:[NSDictionary class]]) {
  416. NSDictionary *dict = input;
  417. NSMutableDictionary<NSString *, FSTFieldValue *> *result =
  418. [NSMutableDictionary dictionaryWithCapacity:dict.count];
  419. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  420. FSTFieldValue *_Nullable parsedValue =
  421. [self parseData:value context:[context contextForField:key]];
  422. if (parsedValue) {
  423. result[key] = parsedValue;
  424. }
  425. }];
  426. return [[FSTObjectValue alloc] initWithDictionary:result];
  427. } else {
  428. // If context.path is null, we are inside an array and we should have already added the root of
  429. // the array to the field mask.
  430. if (context.path) {
  431. [context appendToFieldMaskWithFieldPath:*context.path];
  432. }
  433. return [self parseScalarValue:input context:context];
  434. }
  435. }
  436. /**
  437. * Helper to parse a scalar value (i.e. not an NSDictionary or NSArray).
  438. *
  439. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  440. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  441. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  442. * exception.
  443. *
  444. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  445. * included in the resulting parsed data.
  446. */
  447. - (nullable FSTFieldValue *)parseScalarValue:(nullable id)input context:(FSTParseContext *)context {
  448. if (!input || [input isMemberOfClass:[NSNull class]]) {
  449. return [FSTNullValue nullValue];
  450. } else if ([input isKindOfClass:[NSNumber class]]) {
  451. // Recover the underlying type of the number, using the method described here:
  452. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  453. const char *cType = [input objCType];
  454. // Type Encoding values taken from
  455. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  456. // Articles/ocrtTypeEncodings.html
  457. switch (cType[0]) {
  458. case 'q':
  459. return [FSTIntegerValue integerValue:[input longLongValue]];
  460. case 'i': // Falls through.
  461. case 's': // Falls through.
  462. case 'l': // Falls through.
  463. case 'I': // Falls through.
  464. case 'S':
  465. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  466. // guaranteed small enough to skip a length check.
  467. return [FSTIntegerValue integerValue:[input longLongValue]];
  468. case 'L': // Falls through.
  469. case 'Q':
  470. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  471. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  472. {
  473. unsigned long long extended = [input unsignedLongLongValue];
  474. if (extended > LLONG_MAX) {
  475. FSTThrowInvalidArgument(@"NSNumber (%llu) is too large%@",
  476. [input unsignedLongLongValue], [context fieldDescription]);
  477. } else {
  478. return [FSTIntegerValue integerValue:(int64_t)extended];
  479. }
  480. }
  481. case 'f':
  482. return [FSTDoubleValue doubleValue:[input doubleValue]];
  483. case 'd':
  484. // Double values are already the right type, so just reuse the existing boxed double.
  485. //
  486. // Note that NSNumber already performs NaN normalization to a single shared instance
  487. // so there's no need to treat NaN specially here.
  488. return [FSTDoubleValue doubleValue:[input doubleValue]];
  489. case 'B': // Falls through.
  490. case 'c': // Falls through.
  491. case 'C':
  492. // Boolean values are weird.
  493. //
  494. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  495. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  496. // legitimate usage of signed chars is impossible, but this should be rare.
  497. //
  498. // Additionally, for consistency, map unsigned chars to bools in the same way.
  499. return [FSTBooleanValue booleanValue:[input boolValue]];
  500. default:
  501. // All documented codes should be handled above, so this shouldn't happen.
  502. FSTCFail(@"Unknown NSNumber objCType %s on %@", cType, input);
  503. }
  504. } else if ([input isKindOfClass:[NSString class]]) {
  505. return [FSTStringValue stringValue:input];
  506. } else if ([input isKindOfClass:[NSDate class]]) {
  507. return [FSTTimestampValue timestampValue:[FIRTimestamp timestampWithDate:input]];
  508. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  509. FIRTimestamp *originalTimestamp = (FIRTimestamp *)input;
  510. FIRTimestamp *truncatedTimestamp =
  511. [FIRTimestamp timestampWithSeconds:originalTimestamp.seconds
  512. nanoseconds:originalTimestamp.nanoseconds / 1000 * 1000];
  513. return [FSTTimestampValue timestampValue:truncatedTimestamp];
  514. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  515. return [FSTGeoPointValue geoPointValue:input];
  516. } else if ([input isKindOfClass:[NSData class]]) {
  517. return [FSTBlobValue blobValue:input];
  518. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  519. FSTDocumentKeyReference *reference = input;
  520. if (*reference.databaseID != *self.databaseID) {
  521. const DatabaseId *other = reference.databaseID;
  522. FSTThrowInvalidArgument(
  523. @"Document Reference is for database %s/%s but should be for database %s/%s%@",
  524. other->project_id().c_str(), other->database_id().c_str(),
  525. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  526. [context fieldDescription]);
  527. }
  528. return [FSTReferenceValue referenceValue:reference.key databaseID:self.databaseID];
  529. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  530. if ([input isKindOfClass:[FSTDeleteFieldValue class]]) {
  531. if (context.dataSource == FSTUserDataSourceMergeSet) {
  532. return nil;
  533. } else if (context.dataSource == FSTUserDataSourceUpdate) {
  534. FSTAssert(context.path->size() > 0,
  535. @"FieldValue.delete() at the top level should have already been handled.");
  536. FSTThrowInvalidArgument(
  537. @"FieldValue.delete() can only appear at the top level of your "
  538. "update data%@",
  539. [context fieldDescription]);
  540. } else {
  541. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  542. FSTThrowInvalidArgument(
  543. @"FieldValue.delete() can only be used with updateData() and setData() with "
  544. @"SetOptions.merge().");
  545. }
  546. } else if ([input isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  547. if (![context isWrite]) {
  548. FSTThrowInvalidArgument(
  549. @"FieldValue.serverTimestamp() can only be used with setData() and updateData().");
  550. }
  551. if (!context.path) {
  552. FSTThrowInvalidArgument(
  553. @"FieldValue.serverTimestamp() is not currently supported inside arrays%@",
  554. [context fieldDescription]);
  555. }
  556. [context.fieldTransforms
  557. addObject:[[FSTFieldTransform alloc]
  558. initWithPath:*context.path
  559. transform:[FSTServerTimestampTransform serverTimestampTransform]]];
  560. // Return nil so this value is omitted from the parsed result.
  561. return nil;
  562. } else {
  563. FSTFail(@"Unknown FIRFieldValue type: %@", NSStringFromClass([input class]));
  564. }
  565. } else {
  566. FSTThrowInvalidArgument(@"Unsupported type: %@%@", NSStringFromClass([input class]),
  567. [context fieldDescription]);
  568. }
  569. }
  570. @end
  571. NS_ASSUME_NONNULL_END