FSTUserDataReader.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 <FirebaseCore/FIRTimestamp.h>
  17. #include <memory>
  18. #include <set>
  19. #include <string>
  20. #include <utility>
  21. #include <vector>
  22. #import "Firestore/Source/API/FSTUserDataReader.h"
  23. #import "FIRGeoPoint.h"
  24. #import "FIRVectorValue.h"
  25. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  26. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  27. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  28. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  29. #import "Firestore/Source/API/FIRGeoPoint+Internal.h"
  30. #import "Firestore/Source/API/converters.h"
  31. #import "Firestore/core/include/firebase/firestore/geo_point.h"
  32. #include "Firestore/core/src/core/user_data.h"
  33. #include "Firestore/core/src/model/database_id.h"
  34. #include "Firestore/core/src/model/document_key.h"
  35. #include "Firestore/core/src/model/field_mask.h"
  36. #include "Firestore/core/src/model/field_path.h"
  37. #include "Firestore/core/src/model/field_transform.h"
  38. #include "Firestore/core/src/model/object_value.h"
  39. #include "Firestore/core/src/model/precondition.h"
  40. #include "Firestore/core/src/model/resource_path.h"
  41. #include "Firestore/core/src/model/transform_operation.h"
  42. #include "Firestore/core/src/model/value_util.h"
  43. #include "Firestore/core/src/nanopb/nanopb_util.h"
  44. #include "Firestore/core/src/nanopb/reader.h"
  45. #include "Firestore/core/src/remote/serializer.h"
  46. #include "Firestore/core/src/timestamp_internal.h"
  47. #include "Firestore/core/src/util/exception.h"
  48. #include "Firestore/core/src/util/hard_assert.h"
  49. #include "Firestore/core/src/util/read_context.h"
  50. #include "Firestore/core/src/util/string_apple.h"
  51. #include "absl/memory/memory.h"
  52. #include "absl/strings/match.h"
  53. #include "absl/types/optional.h"
  54. namespace nanopb = firebase::firestore::nanopb;
  55. using firebase::Timestamp;
  56. using firebase::TimestampInternal;
  57. using firebase::firestore::GeoPoint;
  58. using firebase::firestore::google_firestore_v1_ArrayValue;
  59. using firebase::firestore::google_firestore_v1_MapValue;
  60. using firebase::firestore::google_firestore_v1_MapValue_FieldsEntry;
  61. using firebase::firestore::google_firestore_v1_Value;
  62. using firebase::firestore::google_protobuf_NullValue_NULL_VALUE;
  63. using firebase::firestore::google_protobuf_Timestamp;
  64. using firebase::firestore::google_type_LatLng;
  65. using firebase::firestore::core::ParseAccumulator;
  66. using firebase::firestore::core::ParseContext;
  67. using firebase::firestore::core::ParsedSetData;
  68. using firebase::firestore::core::ParsedUpdateData;
  69. using firebase::firestore::core::UserDataSource;
  70. using firebase::firestore::model::ArrayTransform;
  71. using firebase::firestore::model::DatabaseId;
  72. using firebase::firestore::model::DeepClone;
  73. using firebase::firestore::model::DocumentKey;
  74. using firebase::firestore::model::FieldMask;
  75. using firebase::firestore::model::FieldPath;
  76. using firebase::firestore::model::FieldTransform;
  77. using firebase::firestore::model::NullValue;
  78. using firebase::firestore::model::NumericIncrementTransform;
  79. using firebase::firestore::model::ObjectValue;
  80. using firebase::firestore::model::ResourcePath;
  81. using firebase::firestore::model::ServerTimestampTransform;
  82. using firebase::firestore::model::TransformOperation;
  83. using firebase::firestore::nanopb::CheckedSize;
  84. using firebase::firestore::nanopb::Message;
  85. using firebase::firestore::remote::Serializer;
  86. using firebase::firestore::util::MakeString;
  87. using firebase::firestore::util::ReadContext;
  88. using firebase::firestore::util::ThrowInvalidArgument;
  89. using nanopb::StringReader;
  90. NS_ASSUME_NONNULL_BEGIN
  91. #pragma mark - FSTDocumentKeyReference
  92. @implementation FSTDocumentKeyReference {
  93. DocumentKey _key;
  94. DatabaseId _databaseID;
  95. }
  96. - (instancetype)initWithKey:(DocumentKey)key databaseID:(DatabaseId)databaseID {
  97. self = [super init];
  98. if (self) {
  99. _key = std::move(key);
  100. _databaseID = std::move(databaseID);
  101. }
  102. return self;
  103. }
  104. - (const model::DocumentKey &)key {
  105. return _key;
  106. }
  107. - (const model::DatabaseId &)databaseID {
  108. return _databaseID;
  109. }
  110. @end
  111. #pragma mark - FSTUserDataReader
  112. @interface FSTUserDataReader ()
  113. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  114. @end
  115. @implementation FSTUserDataReader {
  116. DatabaseId _databaseID;
  117. }
  118. - (instancetype)initWithDatabaseID:(DatabaseId)databaseID
  119. preConverter:(FSTPreConverterBlock)preConverter {
  120. self = [super init];
  121. if (self) {
  122. _databaseID = std::move(databaseID);
  123. _preConverter = preConverter;
  124. }
  125. return self;
  126. }
  127. - (ParsedSetData)parsedSetData:(id)input {
  128. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  129. // Obj-C to verify the type for us.
  130. if (![input isKindOfClass:[NSDictionary class]]) {
  131. ThrowInvalidArgument("Data to be written must be an NSDictionary.");
  132. }
  133. ParseAccumulator accumulator{UserDataSource::Set};
  134. auto updateData = [self parseData:input context:accumulator.RootContext()];
  135. HARD_ASSERT(updateData.has_value(), "Parsed data should not be nil.");
  136. return std::move(accumulator).SetData(ObjectValue{std::move(*updateData)});
  137. }
  138. - (ParsedSetData)parsedMergeData:(id)input fieldMask:(nullable NSArray<id> *)fieldMask {
  139. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  140. // Obj-C to verify the type for us.
  141. if (![input isKindOfClass:[NSDictionary class]]) {
  142. ThrowInvalidArgument("Data to be written must be an NSDictionary.");
  143. }
  144. ParseAccumulator accumulator{UserDataSource::MergeSet};
  145. auto updateData = [self parseData:input context:accumulator.RootContext()];
  146. HARD_ASSERT(updateData.has_value(), "Parsed data should not be nil.");
  147. ObjectValue updateObject{std::move(*updateData)};
  148. if (fieldMask) {
  149. std::set<FieldPath> validatedFieldPaths;
  150. for (id fieldPath in fieldMask) {
  151. FieldPath path;
  152. if ([fieldPath isKindOfClass:[NSString class]]) {
  153. path = FieldPath::FromDotSeparatedString(MakeString(fieldPath));
  154. } else if ([fieldPath isKindOfClass:[FIRFieldPath class]]) {
  155. path = static_cast<FIRFieldPath *>(fieldPath).internalValue;
  156. } else {
  157. ThrowInvalidArgument("All elements in mergeFields: must be NSStrings or FIRFieldPaths.");
  158. }
  159. // Verify that all elements specified in the field mask are part of the parsed context.
  160. if (!accumulator.Contains(path)) {
  161. ThrowInvalidArgument(
  162. "Field '%s' is specified in your field mask but missing from your input data.",
  163. path.CanonicalString());
  164. }
  165. validatedFieldPaths.insert(path);
  166. }
  167. return std::move(accumulator)
  168. .MergeData(std::move(updateObject), FieldMask{std::move(validatedFieldPaths)});
  169. } else {
  170. return std::move(accumulator).MergeData(std::move(updateObject));
  171. }
  172. }
  173. - (ParsedUpdateData)parsedUpdateData:(id)input {
  174. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  175. // Obj-C to verify the type for us.
  176. if (![input isKindOfClass:[NSDictionary class]]) {
  177. ThrowInvalidArgument("Data to be written must be an NSDictionary.");
  178. }
  179. NSDictionary *dict = input;
  180. ParseAccumulator accumulator{UserDataSource::Update};
  181. __block ParseContext context = accumulator.RootContext();
  182. __block ObjectValue updateData;
  183. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *) {
  184. FieldPath path;
  185. if ([key isKindOfClass:[NSString class]]) {
  186. path = FieldPath::FromDotSeparatedString(MakeString(key));
  187. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  188. path = ((FIRFieldPath *)key).internalValue;
  189. } else {
  190. ThrowInvalidArgument("Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  191. }
  192. value = self.preConverter(value);
  193. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  194. // Add it to the field mask, but don't add anything to updateData.
  195. context.AddToFieldMask(std::move(path));
  196. } else {
  197. auto parsedValue = [self parseData:value context:context.ChildContext(path)];
  198. if (parsedValue) {
  199. context.AddToFieldMask(path);
  200. updateData.Set(path, std::move(*parsedValue));
  201. }
  202. }
  203. }];
  204. return std::move(accumulator).UpdateData(std::move(updateData));
  205. }
  206. - (Message<google_firestore_v1_Value>)parsedQueryValue:(id)input {
  207. return [self parsedQueryValue:input allowArrays:false];
  208. }
  209. - (Message<google_firestore_v1_Value>)parsedQueryValue:(id)input allowArrays:(bool)allowArrays {
  210. ParseAccumulator accumulator{allowArrays ? UserDataSource::ArrayArgument
  211. : UserDataSource::Argument};
  212. auto parsed = [self parseData:input context:accumulator.RootContext()];
  213. HARD_ASSERT(parsed, "Parsed data should not be nil.");
  214. HARD_ASSERT(accumulator.field_transforms().empty(),
  215. "Field transforms should have been disallowed.");
  216. return std::move(*parsed);
  217. }
  218. /**
  219. * Internal helper for parsing user data.
  220. *
  221. * @param input Data to be parsed.
  222. * @param context A context object representing the current path being parsed, the source of the
  223. * data being parsed, etc.
  224. *
  225. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  226. * included in the resulting parsed data.
  227. */
  228. - (absl::optional<Message<google_firestore_v1_Value>>)parseData:(id)input
  229. context:(ParseContext &&)context {
  230. input = self.preConverter(input);
  231. if ([input isKindOfClass:[NSDictionary class]]) {
  232. return [self parseDictionary:(NSDictionary *)input context:std::move(context)];
  233. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  234. // FieldValues usually parse into transforms (except FieldValue.delete()) in which case we
  235. // do not want to include this field in our parsed data (as doing so will overwrite the field
  236. // directly prior to the transform trying to transform it). So we don't call appendToFieldMask
  237. // and we return nil as our parsing result.
  238. [self parseSentinelFieldValue:(FIRFieldValue *)input context:std::move(context)];
  239. return absl::nullopt;
  240. } else {
  241. // If context path is unset we are already inside an array and we don't support field mask paths
  242. // more granular than the top-level array.
  243. if (context.path()) {
  244. context.AddToFieldMask(*context.path());
  245. }
  246. if ([input isKindOfClass:[NSArray class]]) {
  247. // TODO(b/34871131): Include the path containing the array in the error message.
  248. // In the case of IN queries, the parsed data is an array (representing the set of values to
  249. // be included for the IN query) that may directly contain additional arrays (each
  250. // representing an individual field value), so we disable this validation.
  251. if (context.array_element() && context.data_source() != UserDataSource::ArrayArgument) {
  252. ThrowInvalidArgument("Nested arrays are not supported");
  253. }
  254. return [self parseArray:(NSArray *)input context:std::move(context)];
  255. } else {
  256. return [self parseScalarValue:input context:std::move(context)];
  257. }
  258. }
  259. }
  260. - (Message<google_firestore_v1_Value>)parseDictionary:(NSDictionary<NSString *, id> *)dict
  261. context:(ParseContext &&)context {
  262. __block Message<google_firestore_v1_Value> result;
  263. result->which_value_type = google_firestore_v1_Value_map_value_tag;
  264. result->map_value = {};
  265. if (dict.count == 0) {
  266. const FieldPath *path = context.path();
  267. if (path && !path->empty()) {
  268. context.AddToFieldMask(*path);
  269. }
  270. } else {
  271. // Compute the final size of the fields array, which contains an entry for
  272. // all fields that are not FieldValue sentinels
  273. __block pb_size_t count = 0;
  274. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *, id value, BOOL *) {
  275. if (![value isKindOfClass:[FIRFieldValue class]]) {
  276. ++count;
  277. }
  278. }];
  279. result->map_value.fields_count = count;
  280. result->map_value.fields = nanopb::MakeArray<google_firestore_v1_MapValue_FieldsEntry>(count);
  281. __block pb_size_t index = 0;
  282. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *) {
  283. auto parsedValue = [self parseData:value context:context.ChildContext(MakeString(key))];
  284. if (parsedValue) {
  285. result->map_value.fields[index].key = nanopb::MakeBytesArray(MakeString(key));
  286. result->map_value.fields[index].value = *parsedValue->release();
  287. ++index;
  288. }
  289. }];
  290. }
  291. return std::move(result);
  292. }
  293. - (Message<google_firestore_v1_Value>)parseVectorValue:(FIRVectorValue *)vectorValue
  294. context:(ParseContext &&)context {
  295. __block Message<google_firestore_v1_Value> result;
  296. result->which_value_type = google_firestore_v1_Value_map_value_tag;
  297. result->map_value = {};
  298. result->map_value.fields_count = 2;
  299. result->map_value.fields = nanopb::MakeArray<google_firestore_v1_MapValue_FieldsEntry>(2);
  300. result->map_value.fields[0].key = nanopb::CopyBytesArray(model::kTypeValueFieldKey);
  301. result->map_value.fields[0].value = *[self encodeStringValue:MakeString(@"__vector__")].release();
  302. NSArray<NSNumber *> *vectorArray = vectorValue.array;
  303. __block Message<google_firestore_v1_Value> arrayMessage;
  304. arrayMessage->which_value_type = google_firestore_v1_Value_array_value_tag;
  305. arrayMessage->array_value.values_count = CheckedSize([vectorArray count]);
  306. arrayMessage->array_value.values =
  307. nanopb::MakeArray<google_firestore_v1_Value>(arrayMessage->array_value.values_count);
  308. [vectorArray enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *) {
  309. if (![entry isKindOfClass:[NSNumber class]]) {
  310. ThrowInvalidArgument("VectorValues must only contain numeric values.",
  311. context.FieldDescription());
  312. }
  313. // Vector values must always use Double encoding
  314. arrayMessage->array_value.values[idx] = *[self encodeDouble:[entry doubleValue]].release();
  315. }];
  316. result->map_value.fields[1].key = nanopb::CopyBytesArray(model::kVectorValueFieldKey);
  317. result->map_value.fields[1].value = *arrayMessage.release();
  318. return std::move(result);
  319. }
  320. - (Message<google_firestore_v1_Value>)parseArray:(NSArray<id> *)array
  321. context:(ParseContext &&)context {
  322. __block Message<google_firestore_v1_Value> result;
  323. result->which_value_type = google_firestore_v1_Value_array_value_tag;
  324. result->array_value.values_count = CheckedSize([array count]);
  325. result->array_value.values =
  326. nanopb::MakeArray<google_firestore_v1_Value>(result->array_value.values_count);
  327. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *) {
  328. auto parsedEntry = [self parseData:entry context:context.ChildContext(idx)];
  329. if (!parsedEntry) {
  330. // Just include nulls in the array for fields being replaced with a sentinel.
  331. parsedEntry.emplace(DeepClone(NullValue()));
  332. }
  333. result->array_value.values[idx] = *parsedEntry->release();
  334. }];
  335. return std::move(result);
  336. }
  337. /**
  338. * "Parses" the provided FIRFieldValue, adding any necessary transforms to
  339. * context.fieldTransforms.
  340. */
  341. - (void)parseSentinelFieldValue:(FIRFieldValue *)fieldValue context:(ParseContext &&)context {
  342. // Sentinels are only supported with writes, and not within arrays.
  343. if (!context.write()) {
  344. ThrowInvalidArgument("%s can only be used with updateData() and setData()%s",
  345. fieldValue.methodName, context.FieldDescription());
  346. }
  347. if (!context.path()) {
  348. ThrowInvalidArgument("%s is not currently supported inside arrays", fieldValue.methodName);
  349. }
  350. if ([fieldValue isKindOfClass:[FSTDeleteFieldValue class]]) {
  351. if (context.data_source() == UserDataSource::MergeSet) {
  352. // No transform to add for a delete, but we need to add it to our fieldMask so it gets
  353. // deleted.
  354. context.AddToFieldMask(*context.path());
  355. } else if (context.data_source() == UserDataSource::Update) {
  356. HARD_ASSERT(!context.path()->empty(),
  357. "FieldValue.delete() at the top level should have already been handled.");
  358. ThrowInvalidArgument("FieldValue.delete() can only appear at the top level of your "
  359. "update data%s",
  360. context.FieldDescription());
  361. } else {
  362. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  363. ThrowInvalidArgument(
  364. "FieldValue.delete() can only be used with updateData() and setData() with merge:true%s",
  365. context.FieldDescription());
  366. }
  367. } else if ([fieldValue isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  368. context.AddToFieldTransforms(*context.path(), ServerTimestampTransform());
  369. } else if ([fieldValue isKindOfClass:[FSTArrayUnionFieldValue class]]) {
  370. auto parsedElements =
  371. [self parseArrayTransformElements:((FSTArrayUnionFieldValue *)fieldValue).elements];
  372. ArrayTransform arrayUnion(TransformOperation::Type::ArrayUnion, std::move(parsedElements));
  373. context.AddToFieldTransforms(*context.path(), std::move(arrayUnion));
  374. } else if ([fieldValue isKindOfClass:[FSTArrayRemoveFieldValue class]]) {
  375. auto parsedElements =
  376. [self parseArrayTransformElements:((FSTArrayRemoveFieldValue *)fieldValue).elements];
  377. ArrayTransform arrayRemove(TransformOperation::Type::ArrayRemove, std::move(parsedElements));
  378. context.AddToFieldTransforms(*context.path(), std::move(arrayRemove));
  379. } else if ([fieldValue isKindOfClass:[FSTNumericIncrementFieldValue class]]) {
  380. auto *numericIncrementFieldValue = (FSTNumericIncrementFieldValue *)fieldValue;
  381. auto operand = [self parsedQueryValue:numericIncrementFieldValue.operand];
  382. NumericIncrementTransform numeric_increment(std::move(operand));
  383. context.AddToFieldTransforms(*context.path(), std::move(numeric_increment));
  384. } else {
  385. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([fieldValue class]));
  386. }
  387. }
  388. /**
  389. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  390. *
  391. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  392. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  393. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  394. * exception.
  395. *
  396. * @return The parsed value.
  397. */
  398. - (Message<google_firestore_v1_Value>)parseScalarValue:(nullable id)input
  399. context:(ParseContext &&)context {
  400. if (!input || [input isMemberOfClass:[NSNull class]]) {
  401. return DeepClone(NullValue());
  402. } else if ([input isKindOfClass:[NSNumber class]]) {
  403. // Recover the underlying type of the number, using the method described here:
  404. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  405. const char *cType = [input objCType];
  406. // Type Encoding values taken from
  407. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  408. // Articles/ocrtTypeEncodings.html
  409. switch (cType[0]) {
  410. case 'q':
  411. return [self encodeInteger:[input longLongValue]];
  412. case 'i': // Falls through.
  413. case 's': // Falls through.
  414. case 'l': // Falls through.
  415. case 'I': // Falls through.
  416. case 'S':
  417. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  418. // guaranteed small enough to skip a length check.
  419. return [self encodeInteger:[input longLongValue]];
  420. case 'L': // Falls through.
  421. case 'Q':
  422. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  423. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  424. {
  425. unsigned long long extended = [input unsignedLongLongValue];
  426. if (extended > LLONG_MAX) {
  427. ThrowInvalidArgument("NSNumber (%s) is too large%s", [input unsignedLongLongValue],
  428. context.FieldDescription());
  429. } else {
  430. return [self encodeInteger:static_cast<int64_t>(extended)];
  431. }
  432. }
  433. case 'f':
  434. return [self encodeDouble:[input doubleValue]];
  435. case 'd':
  436. // Double values are already the right type, so just reuse the existing boxed double.
  437. //
  438. // Note that NSNumber already performs NaN normalization to a single shared instance
  439. // so there's no need to treat NaN specially here.
  440. return [self encodeDouble:[input doubleValue]];
  441. case 'B': // Falls through.
  442. case 'c': // Falls through.
  443. case 'C':
  444. // Boolean values are weird.
  445. //
  446. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  447. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  448. // legitimate usage of signed chars is impossible, but this should be rare.
  449. //
  450. // Additionally, for consistency, map unsigned chars to bools in the same way.
  451. return [self encodeBoolean:[input boolValue]];
  452. default:
  453. // All documented codes should be handled above, so this shouldn't happen.
  454. HARD_FAIL("Unknown NSNumber objCType %s on %s", cType, input);
  455. }
  456. } else if ([input isKindOfClass:[NSString class]]) {
  457. std::string inputString = MakeString(input);
  458. return [self encodeStringValue:inputString];
  459. } else if ([input isKindOfClass:[NSDate class]]) {
  460. NSDate *inputDate = input;
  461. return [self encodeTimestampValue:api::MakeTimestamp(inputDate)];
  462. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  463. FIRTimestamp *inputTimestamp = input;
  464. Timestamp timestamp = TimestampInternal::Truncate(api::MakeTimestamp(inputTimestamp));
  465. return [self encodeTimestampValue:timestamp];
  466. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  467. return [self encodeGeoPoint:api::MakeGeoPoint(input)];
  468. } else if ([input isKindOfClass:[NSData class]]) {
  469. NSData *inputData = input;
  470. return [self encodeBlob:(nanopb::MakeByteString(inputData))];
  471. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  472. FSTDocumentKeyReference *reference = input;
  473. if (reference.databaseID != _databaseID) {
  474. const DatabaseId &other = reference.databaseID;
  475. ThrowInvalidArgument(
  476. "Document Reference is for database %s/%s but should be for database %s/%s%s",
  477. other.project_id(), other.database_id(), _databaseID.project_id(),
  478. _databaseID.database_id(), context.FieldDescription());
  479. }
  480. return [self encodeReference:_databaseID key:reference.key];
  481. } else if ([input isKindOfClass:[FIRVectorValue class]]) {
  482. FIRVectorValue *vector = input;
  483. return [self parseVectorValue:vector context:std::move(context)];
  484. } else {
  485. ThrowInvalidArgument("Unsupported type: %s%s", NSStringFromClass([input class]),
  486. context.FieldDescription());
  487. }
  488. }
  489. - (Message<google_firestore_v1_Value>)encodeBoolean:(bool)value {
  490. Message<google_firestore_v1_Value> result;
  491. result->which_value_type = google_firestore_v1_Value_boolean_value_tag;
  492. result->boolean_value = value;
  493. return result;
  494. }
  495. - (Message<google_firestore_v1_Value>)encodeInteger:(int64_t)value {
  496. Message<google_firestore_v1_Value> result;
  497. result->which_value_type = google_firestore_v1_Value_integer_value_tag;
  498. result->integer_value = value;
  499. return result;
  500. }
  501. - (Message<google_firestore_v1_Value>)encodeDouble:(double)value {
  502. Message<google_firestore_v1_Value> result;
  503. result->which_value_type = google_firestore_v1_Value_double_value_tag;
  504. result->double_value = value;
  505. return result;
  506. }
  507. - (Message<google_firestore_v1_Value>)encodeTimestampValue:(Timestamp)value {
  508. Message<google_firestore_v1_Value> result;
  509. result->which_value_type = google_firestore_v1_Value_timestamp_value_tag;
  510. result->timestamp_value.seconds = value.seconds();
  511. result->timestamp_value.nanos = value.nanoseconds();
  512. return result;
  513. }
  514. - (Message<google_firestore_v1_Value>)encodeStringValue:(const std::string &)value {
  515. Message<google_firestore_v1_Value> result;
  516. result->which_value_type = google_firestore_v1_Value_string_value_tag;
  517. result->string_value = nanopb::MakeBytesArray(value);
  518. return result;
  519. }
  520. - (Message<google_firestore_v1_Value>)encodeBlob:(const nanopb::ByteString &)value {
  521. Message<google_firestore_v1_Value> result;
  522. result->which_value_type = google_firestore_v1_Value_bytes_value_tag;
  523. // Copy the blob so that pb_release can do the right thing.
  524. result->bytes_value = nanopb::CopyBytesArray(value.get());
  525. return result;
  526. }
  527. - (Message<google_firestore_v1_Value>)encodeReference:(const DatabaseId &)databaseId
  528. key:(const DocumentKey &)key {
  529. HARD_ASSERT(_databaseID == databaseId, "Database %s cannot encode reference from %s",
  530. _databaseID.ToString(), databaseId.ToString());
  531. std::string referenceName = ResourcePath({"projects", databaseId.project_id(), "databases",
  532. databaseId.database_id(), "documents", key.ToString()})
  533. .CanonicalString();
  534. Message<google_firestore_v1_Value> result;
  535. result->which_value_type = google_firestore_v1_Value_reference_value_tag;
  536. result->reference_value = nanopb::MakeBytesArray(referenceName);
  537. return result;
  538. }
  539. - (Message<google_firestore_v1_Value>)encodeGeoPoint:(const GeoPoint &)value {
  540. Message<google_firestore_v1_Value> result;
  541. result->which_value_type = google_firestore_v1_Value_geo_point_value_tag;
  542. result->geo_point_value.latitude = value.latitude();
  543. result->geo_point_value.longitude = value.longitude();
  544. return result;
  545. }
  546. - (Message<google_firestore_v1_ArrayValue>)parseArrayTransformElements:(NSArray<id> *)elements {
  547. ParseAccumulator accumulator{UserDataSource::Argument};
  548. Message<google_firestore_v1_ArrayValue> array_value;
  549. array_value->values_count = CheckedSize(elements.count);
  550. array_value->values = nanopb::MakeArray<google_firestore_v1_Value>(array_value->values_count);
  551. for (NSUInteger i = 0; i < elements.count; i++) {
  552. id element = elements[i];
  553. // Although array transforms are used with writes, the actual elements being unioned or removed
  554. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  555. ParseContext context = accumulator.RootContext();
  556. auto parsedElement = [self parseData:element context:context.ChildContext(i)];
  557. HARD_ASSERT(parsedElement && accumulator.field_transforms().empty(),
  558. "Failed to properly parse array transform element: %s", element);
  559. array_value->values[i] = *parsedElement->release();
  560. }
  561. return array_value;
  562. }
  563. @end
  564. NS_ASSUME_NONNULL_END