GPBCodedOuputStreamTests.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. // The sign/nosign distinction is done here because normally varints are
  199. // around 64bit values, but for some cases a 32bit value is forced with
  200. // with the sign bit (tags, uint32, etc.)
  201. // 1887747006 (no sign bit)
  202. [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x07)
  203. value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
  204. (0x04 << 21) | (0x07LL << 28)];
  205. // 2961488830 (sign bit)
  206. [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b)
  207. value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
  208. (0x04 << 21) | (0x0bLL << 28)];
  209. }
  210. - (void)testWriteVarint6 {
  211. // 64-bit
  212. // 7256456126
  213. [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b)
  214. value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
  215. (0x04 << 21) | (0x1bLL << 28)];
  216. }
  217. - (void)testWriteVarint7 {
  218. // 41256202580718336
  219. [self assertWriteVarint:bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49)
  220. value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) |
  221. (0x1c << 21) | (0x43LL << 28) | (0x49LL << 35) |
  222. (0x24LL << 42) | (0x49LL << 49)];
  223. }
  224. - (void)testWriteVarint8 {
  225. // 11964378330978735131
  226. [self assertWriteVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85,
  227. 0xa6, 0x01)
  228. value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) |
  229. (0x42 << 21) | (0x3bLL << 28) | (0x56LL << 35) |
  230. (0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) |
  231. (0x01ULL << 63)];
  232. }
  233. - (void)testWriteLittleEndian {
  234. [self assertWriteLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12)
  235. value:0x12345678];
  236. [self assertWriteLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a)
  237. value:0x9abcdef0];
  238. [self assertWriteLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56,
  239. 0x34, 0x12)
  240. value:0x123456789abcdef0LL];
  241. [self assertWriteLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde,
  242. 0xbc, 0x9a)
  243. value:0x9abcdef012345678LL];
  244. }
  245. - (void)testEncodeZigZag {
  246. XCTAssertEqual(0U, GPBEncodeZigZag32(0));
  247. XCTAssertEqual(1U, GPBEncodeZigZag32(-1));
  248. XCTAssertEqual(2U, GPBEncodeZigZag32(1));
  249. XCTAssertEqual(3U, GPBEncodeZigZag32(-2));
  250. XCTAssertEqual(0x7FFFFFFEU, GPBEncodeZigZag32(0x3FFFFFFF));
  251. XCTAssertEqual(0x7FFFFFFFU, GPBEncodeZigZag32(0xC0000000));
  252. XCTAssertEqual(0xFFFFFFFEU, GPBEncodeZigZag32(0x7FFFFFFF));
  253. XCTAssertEqual(0xFFFFFFFFU, GPBEncodeZigZag32(0x80000000));
  254. XCTAssertEqual(0ULL, GPBEncodeZigZag64(0));
  255. XCTAssertEqual(1ULL, GPBEncodeZigZag64(-1));
  256. XCTAssertEqual(2ULL, GPBEncodeZigZag64(1));
  257. XCTAssertEqual(3ULL, GPBEncodeZigZag64(-2));
  258. XCTAssertEqual(0x000000007FFFFFFEULL,
  259. GPBEncodeZigZag64(0x000000003FFFFFFFLL));
  260. XCTAssertEqual(0x000000007FFFFFFFULL,
  261. GPBEncodeZigZag64(0xFFFFFFFFC0000000LL));
  262. XCTAssertEqual(0x00000000FFFFFFFEULL,
  263. GPBEncodeZigZag64(0x000000007FFFFFFFLL));
  264. XCTAssertEqual(0x00000000FFFFFFFFULL,
  265. GPBEncodeZigZag64(0xFFFFFFFF80000000LL));
  266. XCTAssertEqual(0xFFFFFFFFFFFFFFFEULL,
  267. GPBEncodeZigZag64(0x7FFFFFFFFFFFFFFFLL));
  268. XCTAssertEqual(0xFFFFFFFFFFFFFFFFULL,
  269. GPBEncodeZigZag64(0x8000000000000000LL));
  270. // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
  271. // were chosen semi-randomly via keyboard bashing.
  272. XCTAssertEqual(0U, GPBEncodeZigZag32(GPBDecodeZigZag32(0)));
  273. XCTAssertEqual(1U, GPBEncodeZigZag32(GPBDecodeZigZag32(1)));
  274. XCTAssertEqual(-1U, GPBEncodeZigZag32(GPBDecodeZigZag32(-1)));
  275. XCTAssertEqual(14927U, GPBEncodeZigZag32(GPBDecodeZigZag32(14927)));
  276. XCTAssertEqual(-3612U, GPBEncodeZigZag32(GPBDecodeZigZag32(-3612)));
  277. XCTAssertEqual(0ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(0)));
  278. XCTAssertEqual(1ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(1)));
  279. XCTAssertEqual(-1ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-1)));
  280. XCTAssertEqual(14927ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(14927)));
  281. XCTAssertEqual(-3612ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-3612)));
  282. XCTAssertEqual(856912304801416ULL,
  283. GPBEncodeZigZag64(GPBDecodeZigZag64(856912304801416LL)));
  284. XCTAssertEqual(-75123905439571256ULL,
  285. GPBEncodeZigZag64(GPBDecodeZigZag64(-75123905439571256LL)));
  286. }
  287. - (void)testWriteWholeMessage {
  288. // Not kGPBDefaultRepeatCount because we are comparing to a golden master file
  289. // that was generated with 2.
  290. TestAllTypes* message = [self allSetRepeatedCount:2];
  291. NSData* rawBytes = message.data;
  292. NSData* goldenData =
  293. [self getDataFileNamed:@"golden_message" dataToWrite:rawBytes];
  294. XCTAssertEqualObjects(rawBytes, goldenData);
  295. // Try different block sizes.
  296. for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
  297. NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  298. GPBCodedOutputStream* output =
  299. [GPBCodedOutputStream streamWithOutputStream:rawOutput
  300. bufferSize:blockSize];
  301. [message writeToCodedOutputStream:output];
  302. [output flush];
  303. NSData* actual =
  304. [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  305. XCTAssertEqualObjects(rawBytes, actual);
  306. }
  307. // Not kGPBDefaultRepeatCount because we are comparing to a golden master file
  308. // that was generated with 2.
  309. TestAllExtensions* extensions = [self allExtensionsSetRepeatedCount:2];
  310. rawBytes = extensions.data;
  311. goldenData = [self getDataFileNamed:@"golden_packed_fields_message"
  312. dataToWrite:rawBytes];
  313. XCTAssertEqualObjects(rawBytes, goldenData);
  314. }
  315. - (void)testCFStringGetCStringPtrAndStringsWithNullChars {
  316. // This test exists to verify that CFStrings with embedded NULLs still expose
  317. // their raw buffer if they are backed by UTF8 storage. If this fails, the
  318. // quick/direct access paths in GPBCodedOutputStream that depend on
  319. // CFStringGetCStringPtr need to be re-evalutated (maybe just removed).
  320. // And yes, we do get NULLs in strings from some servers.
  321. char zeroTest[] = "\0Test\0String";
  322. // Note: there is a \0 at the end of this since it is a c-string.
  323. NSString *asNSString = [[NSString alloc] initWithBytes:zeroTest
  324. length:sizeof(zeroTest)
  325. encoding:NSUTF8StringEncoding];
  326. const char *cString =
  327. CFStringGetCStringPtr((CFStringRef)asNSString, kCFStringEncodingUTF8);
  328. XCTAssertTrue(cString != NULL);
  329. // Again, if the above assert fails, then it means NSString no longer exposes
  330. // the raw utf8 storage of a string created from utf8 input, so the code using
  331. // CFStringGetCStringPtr in GPBCodedOutputStream will still work (it will take
  332. // a different code path); but the optimizations for when
  333. // CFStringGetCStringPtr does work could possibly go away.
  334. XCTAssertEqual(sizeof(zeroTest),
  335. [asNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
  336. XCTAssertTrue(0 == memcmp(cString, zeroTest, sizeof(zeroTest)));
  337. [asNSString release];
  338. }
  339. - (void)testWriteStringsWithZeroChar {
  340. // Unicode allows `\0` as a character, and NSString is a class cluster, so
  341. // there are a few different classes that could end up behind a given string.
  342. // Historically, we've seen differences based on constant strings in code and
  343. // strings built via the NSString apis. So this round trips them to ensure
  344. // they are acting as expected.
  345. NSArray<NSString *> *strs = @[
  346. @"\0at start",
  347. @"in\0middle",
  348. @"at end\0",
  349. ];
  350. int i = 0;
  351. for (NSString *str in strs) {
  352. NSData *asUTF8 = [str dataUsingEncoding:NSUTF8StringEncoding];
  353. NSMutableData *expected = [NSMutableData data];
  354. uint8_t lengthByte = (uint8_t)asUTF8.length;
  355. [expected appendBytes:&lengthByte length:1];
  356. [expected appendData:asUTF8];
  357. NSString *context = [NSString stringWithFormat:@"Loop %d - Literal", i];
  358. [self assertWriteStringNoTag:expected value:str context:context];
  359. // Force a new string to be built which gets a different class from the
  360. // NSString class cluster than the literal did.
  361. NSString *str2 = [NSString stringWithFormat:@"%@", str];
  362. context = [NSString stringWithFormat:@"Loop %d - Built", i];
  363. [self assertWriteStringNoTag:expected value:str2 context:context];
  364. ++i;
  365. }
  366. }
  367. - (void)testThatItThrowsWhenWriteRawPtrFails {
  368. NSOutputStream *output = [NSOutputStream outputStreamToMemory];
  369. GPBCodedOutputStream *codedOutput =
  370. [GPBCodedOutputStream streamWithOutputStream:output bufferSize:0]; // Skip buffering.
  371. [output close]; // Close the output stream to force failure on write.
  372. const char *cString = "raw";
  373. XCTAssertThrowsSpecificNamed([codedOutput writeRawPtr:cString offset:0 length:strlen(cString)],
  374. NSException, GPBCodedOutputStreamException_WriteFailed);
  375. }
  376. @end