GPBCodedOuputStreamTests.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #import "GPBTestUtilities.h"
  31. #import "GPBCodedOutputStream_PackagePrivate.h"
  32. #import "GPBCodedInputStream.h"
  33. #import "GPBUtilities_PackagePrivate.h"
  34. #import "google/protobuf/Unittest.pbobjc.h"
  35. @interface GPBCodedOutputStream (InternalMethods)
  36. // Declared in the .m file, expose for testing.
  37. - (instancetype)initWithOutputStream:(NSOutputStream *)output
  38. data:(NSMutableData *)data;
  39. @end
  40. @interface GPBCodedOutputStream (Helper)
  41. + (instancetype)streamWithOutputStream:(NSOutputStream *)output
  42. bufferSize:(size_t)bufferSize;
  43. @end
  44. @implementation GPBCodedOutputStream (Helper)
  45. + (instancetype)streamWithOutputStream:(NSOutputStream *)output
  46. bufferSize:(size_t)bufferSize {
  47. NSMutableData *data = [NSMutableData dataWithLength:bufferSize];
  48. return [[[self alloc] initWithOutputStream:output data:data] autorelease];
  49. }
  50. @end
  51. @interface CodedOutputStreamTests : GPBTestCase
  52. @end
  53. @implementation CodedOutputStreamTests
  54. - (NSData*)bytes_with_sentinel:(int32_t)unused, ... {
  55. va_list list;
  56. va_start(list, unused);
  57. NSMutableData* values = [NSMutableData dataWithCapacity:0];
  58. int32_t i;
  59. while ((i = va_arg(list, int32_t)) != 256) {
  60. NSAssert(i >= 0 && i < 256, @"");
  61. uint8_t u = (uint8_t)i;
  62. [values appendBytes:&u length:1];
  63. }
  64. va_end(list);
  65. return values;
  66. }
  67. #define bytes(...) [self bytes_with_sentinel:0, __VA_ARGS__, 256]
  68. - (void)assertWriteLittleEndian32:(NSData*)data value:(int32_t)value {
  69. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  70. GPBCodedOutputStream* output =
  71. [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  72. [output writeRawLittleEndian32:(int32_t)value];
  73. [output flush];
  74. NSData* actual =
  75. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  76. XCTAssertEqualObjects(data, actual);
  77. // Try different block sizes.
  78. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  79. rawOutput = [NSOutputStream outputStreamToMemory];
  80. output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
  81. bufferSize:blockSize];
  82. [output writeRawLittleEndian32:(int32_t)value];
  83. [output flush];
  84. actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  85. XCTAssertEqualObjects(data, actual);
  86. }
  87. }
  88. - (void)assertWriteLittleEndian64:(NSData*)data value:(int64_t)value {
  89. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  90. GPBCodedOutputStream* output =
  91. [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  92. [output writeRawLittleEndian64:value];
  93. [output flush];
  94. NSData* actual =
  95. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  96. XCTAssertEqualObjects(data, actual);
  97. // Try different block sizes.
  98. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  99. rawOutput = [NSOutputStream outputStreamToMemory];
  100. output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
  101. bufferSize:blockSize];
  102. [output writeRawLittleEndian64:value];
  103. [output flush];
  104. actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  105. XCTAssertEqualObjects(data, actual);
  106. }
  107. }
  108. - (void)assertWriteVarint:(NSData*)data value:(int64_t)value {
  109. // Only do 32-bit write if the value fits in 32 bits.
  110. if (GPBLogicalRightShift64(value, 32) == 0) {
  111. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  112. GPBCodedOutputStream* output =
  113. [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  114. [output writeRawVarint32:(int32_t)value];
  115. [output flush];
  116. NSData* actual =
  117. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  118. XCTAssertEqualObjects(data, actual);
  119. // Also try computing size.
  120. XCTAssertEqual(GPBComputeRawVarint32Size((int32_t)value),
  121. (size_t)data.length);
  122. }
  123. {
  124. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  125. GPBCodedOutputStream* output =
  126. [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  127. [output writeRawVarint64:value];
  128. [output flush];
  129. NSData* actual =
  130. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  131. XCTAssertEqualObjects(data, actual);
  132. // Also try computing size.
  133. XCTAssertEqual(GPBComputeRawVarint64Size(value), (size_t)data.length);
  134. }
  135. // Try different block sizes.
  136. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  137. // Only do 32-bit write if the value fits in 32 bits.
  138. if (GPBLogicalRightShift64(value, 32) == 0) {
  139. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  140. GPBCodedOutputStream* output =
  141. [GPBCodedOutputStream streamWithOutputStream:rawOutput
  142. bufferSize:blockSize];
  143. [output writeRawVarint32:(int32_t)value];
  144. [output flush];
  145. NSData* actual =
  146. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  147. XCTAssertEqualObjects(data, actual);
  148. }
  149. {
  150. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  151. GPBCodedOutputStream* output =
  152. [GPBCodedOutputStream streamWithOutputStream:rawOutput
  153. bufferSize:blockSize];
  154. [output writeRawVarint64:value];
  155. [output flush];
  156. NSData* actual =
  157. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  158. XCTAssertEqualObjects(data, actual);
  159. }
  160. }
  161. }
  162. - (void)assertWriteStringNoTag:(NSData*)data
  163. value:(NSString *)value
  164. context:(NSString *)contextMessage {
  165. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  166. GPBCodedOutputStream* output =
  167. [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  168. [output writeStringNoTag:value];
  169. [output flush];
  170. NSData* actual =
  171. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  172. XCTAssertEqualObjects(data, actual, @"%@", contextMessage);
  173. // Try different block sizes.
  174. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  175. rawOutput = [NSOutputStream outputStreamToMemory];
  176. output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
  177. bufferSize:blockSize];
  178. [output writeStringNoTag:value];
  179. [output flush];
  180. actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  181. XCTAssertEqualObjects(data, actual, @"%@", contextMessage);
  182. }
  183. }
  184. - (void)testWriteVarint1 {
  185. [self assertWriteVarint:bytes(0x00) value:0];
  186. }
  187. - (void)testWriteVarint2 {
  188. [self assertWriteVarint:bytes(0x01) value:1];
  189. }
  190. - (void)testWriteVarint3 {
  191. [self assertWriteVarint:bytes(0x7f) value:127];
  192. }
  193. - (void)testWriteVarint4 {
  194. // 14882
  195. [self assertWriteVarint:bytes(0xa2, 0x74) value:(0x22 << 0) | (0x74 << 7)];
  196. }
  197. - (void)testWriteVarint5 {
  198. // 2961488830
  199. [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b)
  200. value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
  201. (0x04 << 21) | (0x0bLL << 28)];
  202. }
  203. - (void)testWriteVarint6 {
  204. // 64-bit
  205. // 7256456126
  206. [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b)
  207. value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
  208. (0x04 << 21) | (0x1bLL << 28)];
  209. }
  210. - (void)testWriteVarint7 {
  211. // 41256202580718336
  212. [self assertWriteVarint:bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49)
  213. value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) |
  214. (0x1c << 21) | (0x43LL << 28) | (0x49LL << 35) |
  215. (0x24LL << 42) | (0x49LL << 49)];
  216. }
  217. - (void)testWriteVarint8 {
  218. // 11964378330978735131
  219. [self assertWriteVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85,
  220. 0xa6, 0x01)
  221. value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) |
  222. (0x42 << 21) | (0x3bLL << 28) | (0x56LL << 35) |
  223. (0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) |
  224. (0x01ULL << 63)];
  225. }
  226. - (void)testWriteLittleEndian {
  227. [self assertWriteLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12)
  228. value:0x12345678];
  229. [self assertWriteLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a)
  230. value:0x9abcdef0];
  231. [self assertWriteLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56,
  232. 0x34, 0x12)
  233. value:0x123456789abcdef0LL];
  234. [self assertWriteLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde,
  235. 0xbc, 0x9a)
  236. value:0x9abcdef012345678LL];
  237. }
  238. - (void)testEncodeZigZag {
  239. XCTAssertEqual(0U, GPBEncodeZigZag32(0));
  240. XCTAssertEqual(1U, GPBEncodeZigZag32(-1));
  241. XCTAssertEqual(2U, GPBEncodeZigZag32(1));
  242. XCTAssertEqual(3U, GPBEncodeZigZag32(-2));
  243. XCTAssertEqual(0x7FFFFFFEU, GPBEncodeZigZag32(0x3FFFFFFF));
  244. XCTAssertEqual(0x7FFFFFFFU, GPBEncodeZigZag32(0xC0000000));
  245. XCTAssertEqual(0xFFFFFFFEU, GPBEncodeZigZag32(0x7FFFFFFF));
  246. XCTAssertEqual(0xFFFFFFFFU, GPBEncodeZigZag32(0x80000000));
  247. XCTAssertEqual(0ULL, GPBEncodeZigZag64(0));
  248. XCTAssertEqual(1ULL, GPBEncodeZigZag64(-1));
  249. XCTAssertEqual(2ULL, GPBEncodeZigZag64(1));
  250. XCTAssertEqual(3ULL, GPBEncodeZigZag64(-2));
  251. XCTAssertEqual(0x000000007FFFFFFEULL,
  252. GPBEncodeZigZag64(0x000000003FFFFFFFLL));
  253. XCTAssertEqual(0x000000007FFFFFFFULL,
  254. GPBEncodeZigZag64(0xFFFFFFFFC0000000LL));
  255. XCTAssertEqual(0x00000000FFFFFFFEULL,
  256. GPBEncodeZigZag64(0x000000007FFFFFFFLL));
  257. XCTAssertEqual(0x00000000FFFFFFFFULL,
  258. GPBEncodeZigZag64(0xFFFFFFFF80000000LL));
  259. XCTAssertEqual(0xFFFFFFFFFFFFFFFEULL,
  260. GPBEncodeZigZag64(0x7FFFFFFFFFFFFFFFLL));
  261. XCTAssertEqual(0xFFFFFFFFFFFFFFFFULL,
  262. GPBEncodeZigZag64(0x8000000000000000LL));
  263. // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
  264. // were chosen semi-randomly via keyboard bashing.
  265. XCTAssertEqual(0U, GPBEncodeZigZag32(GPBDecodeZigZag32(0)));
  266. XCTAssertEqual(1U, GPBEncodeZigZag32(GPBDecodeZigZag32(1)));
  267. XCTAssertEqual(-1U, GPBEncodeZigZag32(GPBDecodeZigZag32(-1)));
  268. XCTAssertEqual(14927U, GPBEncodeZigZag32(GPBDecodeZigZag32(14927)));
  269. XCTAssertEqual(-3612U, GPBEncodeZigZag32(GPBDecodeZigZag32(-3612)));
  270. XCTAssertEqual(0ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(0)));
  271. XCTAssertEqual(1ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(1)));
  272. XCTAssertEqual(-1ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-1)));
  273. XCTAssertEqual(14927ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(14927)));
  274. XCTAssertEqual(-3612ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-3612)));
  275. XCTAssertEqual(856912304801416ULL,
  276. GPBEncodeZigZag64(GPBDecodeZigZag64(856912304801416LL)));
  277. XCTAssertEqual(-75123905439571256ULL,
  278. GPBEncodeZigZag64(GPBDecodeZigZag64(-75123905439571256LL)));
  279. }
  280. - (void)testWriteWholeMessage {
  281. // Not kGPBDefaultRepeatCount because we are comparing to a golden master file
  282. // that was generated with 2.
  283. TestAllTypes* message = [self allSetRepeatedCount:2];
  284. NSData* rawBytes = message.data;
  285. NSData* goldenData =
  286. [self getDataFileNamed:@"golden_message" dataToWrite:rawBytes];
  287. XCTAssertEqualObjects(rawBytes, goldenData);
  288. // Try different block sizes.
  289. for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
  290. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  291. GPBCodedOutputStream* output =
  292. [GPBCodedOutputStream streamWithOutputStream:rawOutput
  293. bufferSize:blockSize];
  294. [message writeToCodedOutputStream:output];
  295. [output flush];
  296. NSData* actual =
  297. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  298. XCTAssertEqualObjects(rawBytes, actual);
  299. }
  300. // Not kGPBDefaultRepeatCount because we are comparing to a golden master file
  301. // that was generated with 2.
  302. TestAllExtensions* extensions = [self allExtensionsSetRepeatedCount:2];
  303. rawBytes = extensions.data;
  304. goldenData = [self getDataFileNamed:@"golden_packed_fields_message"
  305. dataToWrite:rawBytes];
  306. XCTAssertEqualObjects(rawBytes, goldenData);
  307. }
  308. - (void)testCFStringGetCStringPtrAndStringsWithNullChars {
  309. // This test exists to verify that CFStrings with embedded NULLs still expose
  310. // their raw buffer if they are backed by UTF8 storage. If this fails, the
  311. // quick/direct access paths in GPBCodedOutputStream that depend on
  312. // CFStringGetCStringPtr need to be re-evalutated (maybe just removed).
  313. // And yes, we do get NULLs in strings from some servers.
  314. char zeroTest[] = "\0Test\0String";
  315. // Note: there is a \0 at the end of this since it is a c-string.
  316. NSString *asNSString = [[NSString alloc] initWithBytes:zeroTest
  317. length:sizeof(zeroTest)
  318. encoding:NSUTF8StringEncoding];
  319. const char *cString =
  320. CFStringGetCStringPtr((CFStringRef)asNSString, kCFStringEncodingUTF8);
  321. XCTAssertTrue(cString != NULL);
  322. // Again, if the above assert fails, then it means NSString no longer exposes
  323. // the raw utf8 storage of a string created from utf8 input, so the code using
  324. // CFStringGetCStringPtr in GPBCodedOutputStream will still work (it will take
  325. // a different code path); but the optimizations for when
  326. // CFStringGetCStringPtr does work could possibly go away.
  327. XCTAssertEqual(sizeof(zeroTest),
  328. [asNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
  329. XCTAssertTrue(0 == memcmp(cString, zeroTest, sizeof(zeroTest)));
  330. [asNSString release];
  331. }
  332. - (void)testWriteStringsWithZeroChar {
  333. // Unicode allows `\0` as a character, and NSString is a class cluster, so
  334. // there are a few different classes that could end up beind a given string.
  335. // Historically, we've seen differences based on constant strings in code and
  336. // strings built via the NSString apis. So this round trips them to ensure
  337. // they are acting as expected.
  338. NSArray<NSString *> *strs = @[
  339. @"\0at start",
  340. @"in\0middle",
  341. @"at end\0",
  342. ];
  343. int i = 0;
  344. for (NSString *str in strs) {
  345. NSData *asUTF8 = [str dataUsingEncoding:NSUTF8StringEncoding];
  346. NSMutableData *expected = [NSMutableData data];
  347. uint8_t lengthByte = (uint8_t)asUTF8.length;
  348. [expected appendBytes:&lengthByte length:1];
  349. [expected appendData:asUTF8];
  350. NSString *context = [NSString stringWithFormat:@"Loop %d - Literal", i];
  351. [self assertWriteStringNoTag:expected value:str context:context];
  352. // Force a new string to be built which gets a different class from the
  353. // NSString class cluster than the literal did.
  354. NSString *str2 = [NSString stringWithFormat:@"%@", str];
  355. context = [NSString stringWithFormat:@"Loop %d - Built", i];
  356. [self assertWriteStringNoTag:expected value:str2 context:context];
  357. ++i;
  358. }
  359. }
  360. - (void)testThatItThrowsWhenWriteRawPtrFails {
  361. NSOutputStream *output = [NSOutputStream outputStreamToMemory];
  362. GPBCodedOutputStream *codedOutput =
  363. [GPBCodedOutputStream streamWithOutputStream:output bufferSize:0]; // Skip buffering.
  364. [output close]; // Close the output stream to force failure on write.
  365. const char *cString = "raw";
  366. XCTAssertThrowsSpecificNamed([codedOutput writeRawPtr:cString offset:0 length:strlen(cString)],
  367. NSException, GPBCodedOutputStreamException_WriteFailed);
  368. }
  369. @end