FSTUserDataConverter.mm 25 KB

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