GPBCodedOuputStreamTests.m 16.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#import "GPBTestUtilities.h"

33
#import "GPBCodedOutputStream_PackagePrivate.h"
34 35 36 37
#import "GPBCodedInputStream.h"
#import "GPBUtilities_PackagePrivate.h"
#import "google/protobuf/Unittest.pbobjc.h"

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
@interface GPBCodedOutputStream (InternalMethods)
// Declared in the .m file, expose for testing.
- (instancetype)initWithOutputStream:(NSOutputStream *)output
                                data:(NSMutableData *)data;
@end

@interface GPBCodedOutputStream (Helper)
+ (instancetype)streamWithOutputStream:(NSOutputStream *)output
                            bufferSize:(size_t)bufferSize;
@end

@implementation GPBCodedOutputStream (Helper)
+ (instancetype)streamWithOutputStream:(NSOutputStream *)output
                            bufferSize:(size_t)bufferSize {
  NSMutableData *data = [NSMutableData dataWithLength:bufferSize];
  return [[[self alloc] initWithOutputStream:output data:data] autorelease];
}
@end

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
@interface CodedOutputStreamTests : GPBTestCase
@end

@implementation CodedOutputStreamTests

- (NSData*)bytes_with_sentinel:(int32_t)unused, ... {
  va_list list;
  va_start(list, unused);

  NSMutableData* values = [NSMutableData dataWithCapacity:0];
  int32_t i;

  while ((i = va_arg(list, int32_t)) != 256) {
    NSAssert(i >= 0 && i < 256, @"");
    uint8_t u = (uint8_t)i;
    [values appendBytes:&u length:1];
  }

  va_end(list);

  return values;
}

#define bytes(...) [self bytes_with_sentinel:0, __VA_ARGS__, 256]

- (void)assertWriteLittleEndian32:(NSData*)data value:(int32_t)value {
  NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  GPBCodedOutputStream* output =
      [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  [output writeRawLittleEndian32:(int32_t)value];
  [output flush];

  NSData* actual =
      [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  XCTAssertEqualObjects(data, actual);

  // Try different block sizes.
  for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
    rawOutput = [NSOutputStream outputStreamToMemory];
    output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
                                               bufferSize:blockSize];
    [output writeRawLittleEndian32:(int32_t)value];
    [output flush];

    actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    XCTAssertEqualObjects(data, actual);
  }
}

- (void)assertWriteLittleEndian64:(NSData*)data value:(int64_t)value {
  NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  GPBCodedOutputStream* output =
      [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  [output writeRawLittleEndian64:value];
  [output flush];

  NSData* actual =
      [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  XCTAssertEqualObjects(data, actual);

  // Try different block sizes.
  for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
    rawOutput = [NSOutputStream outputStreamToMemory];
    output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
                                               bufferSize:blockSize];
    [output writeRawLittleEndian64:value];
    [output flush];

    actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    XCTAssertEqualObjects(data, actual);
  }
}

- (void)assertWriteVarint:(NSData*)data value:(int64_t)value {
  // Only do 32-bit write if the value fits in 32 bits.
  if (GPBLogicalRightShift64(value, 32) == 0) {
    NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
    GPBCodedOutputStream* output =
        [GPBCodedOutputStream streamWithOutputStream:rawOutput];
    [output writeRawVarint32:(int32_t)value];
    [output flush];

    NSData* actual =
        [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    XCTAssertEqualObjects(data, actual);

    // Also try computing size.
    XCTAssertEqual(GPBComputeRawVarint32Size((int32_t)value),
                   (size_t)data.length);
  }

  {
    NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
    GPBCodedOutputStream* output =
        [GPBCodedOutputStream streamWithOutputStream:rawOutput];
    [output writeRawVarint64:value];
    [output flush];

    NSData* actual =
        [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    XCTAssertEqualObjects(data, actual);

    // Also try computing size.
    XCTAssertEqual(GPBComputeRawVarint64Size(value), (size_t)data.length);
  }

  // Try different block sizes.
  for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
    // Only do 32-bit write if the value fits in 32 bits.
    if (GPBLogicalRightShift64(value, 32) == 0) {
      NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
      GPBCodedOutputStream* output =
          [GPBCodedOutputStream streamWithOutputStream:rawOutput
                                            bufferSize:blockSize];

      [output writeRawVarint32:(int32_t)value];
      [output flush];

      NSData* actual =
          [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
      XCTAssertEqualObjects(data, actual);
    }

    {
      NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
      GPBCodedOutputStream* output =
          [GPBCodedOutputStream streamWithOutputStream:rawOutput
                                            bufferSize:blockSize];

      [output writeRawVarint64:value];
      [output flush];

      NSData* actual =
          [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
      XCTAssertEqualObjects(data, actual);
    }
  }
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
- (void)assertWriteStringNoTag:(NSData*)data
                         value:(NSString *)value
                       context:(NSString *)contextMessage {
  NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
  GPBCodedOutputStream* output =
      [GPBCodedOutputStream streamWithOutputStream:rawOutput];
  [output writeStringNoTag:value];
  [output flush];

  NSData* actual =
      [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  XCTAssertEqualObjects(data, actual, @"%@", contextMessage);

  // Try different block sizes.
  for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
    rawOutput = [NSOutputStream outputStreamToMemory];
    output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
                                               bufferSize:blockSize];
    [output writeStringNoTag:value];
    [output flush];

    actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    XCTAssertEqualObjects(data, actual, @"%@", contextMessage);
  }
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
- (void)testWriteVarint1 {
  [self assertWriteVarint:bytes(0x00) value:0];
}

- (void)testWriteVarint2 {
  [self assertWriteVarint:bytes(0x01) value:1];
}

- (void)testWriteVarint3 {
  [self assertWriteVarint:bytes(0x7f) value:127];
}

- (void)testWriteVarint4 {
  // 14882
  [self assertWriteVarint:bytes(0xa2, 0x74) value:(0x22 << 0) | (0x74 << 7)];
}

- (void)testWriteVarint5 {
  // 2961488830
  [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b)
                    value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
                          (0x04 << 21) | (0x0bLL << 28)];
}

- (void)testWriteVarint6 {
  // 64-bit
  // 7256456126
  [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b)
                    value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
                          (0x04 << 21) | (0x1bLL << 28)];
}

- (void)testWriteVarint7 {
  // 41256202580718336
  [self assertWriteVarint:bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49)
                    value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) |
                          (0x1c << 21) | (0x43LL << 28) | (0x49LL << 35) |
                          (0x24LL << 42) | (0x49LL << 49)];
}

- (void)testWriteVarint8 {
  // 11964378330978735131
  [self assertWriteVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85,
                                0xa6, 0x01)
                    value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) |
                          (0x42 << 21) | (0x3bLL << 28) | (0x56LL << 35) |
                          (0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) |
                          (0x01LL << 63)];
}

- (void)testWriteLittleEndian {
  [self assertWriteLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12)
                            value:0x12345678];
  [self assertWriteLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a)
                            value:0x9abcdef0];

  [self assertWriteLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56,
                                        0x34, 0x12)
                            value:0x123456789abcdef0LL];
  [self assertWriteLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde,
                                        0xbc, 0x9a)
                            value:0x9abcdef012345678LL];
}

- (void)testEncodeZigZag {
  XCTAssertEqual(0U, GPBEncodeZigZag32(0));
  XCTAssertEqual(1U, GPBEncodeZigZag32(-1));
  XCTAssertEqual(2U, GPBEncodeZigZag32(1));
  XCTAssertEqual(3U, GPBEncodeZigZag32(-2));
  XCTAssertEqual(0x7FFFFFFEU, GPBEncodeZigZag32(0x3FFFFFFF));
  XCTAssertEqual(0x7FFFFFFFU, GPBEncodeZigZag32(0xC0000000));
  XCTAssertEqual(0xFFFFFFFEU, GPBEncodeZigZag32(0x7FFFFFFF));
  XCTAssertEqual(0xFFFFFFFFU, GPBEncodeZigZag32(0x80000000));

  XCTAssertEqual(0ULL, GPBEncodeZigZag64(0));
  XCTAssertEqual(1ULL, GPBEncodeZigZag64(-1));
  XCTAssertEqual(2ULL, GPBEncodeZigZag64(1));
  XCTAssertEqual(3ULL, GPBEncodeZigZag64(-2));
  XCTAssertEqual(0x000000007FFFFFFEULL,
                 GPBEncodeZigZag64(0x000000003FFFFFFFLL));
  XCTAssertEqual(0x000000007FFFFFFFULL,
                 GPBEncodeZigZag64(0xFFFFFFFFC0000000LL));
  XCTAssertEqual(0x00000000FFFFFFFEULL,
                 GPBEncodeZigZag64(0x000000007FFFFFFFLL));
  XCTAssertEqual(0x00000000FFFFFFFFULL,
                 GPBEncodeZigZag64(0xFFFFFFFF80000000LL));
  XCTAssertEqual(0xFFFFFFFFFFFFFFFEULL,
                 GPBEncodeZigZag64(0x7FFFFFFFFFFFFFFFLL));
  XCTAssertEqual(0xFFFFFFFFFFFFFFFFULL,
                 GPBEncodeZigZag64(0x8000000000000000LL));

  // Some easier-to-verify round-trip tests.  The inputs (other than 0, 1, -1)
  // were chosen semi-randomly via keyboard bashing.
  XCTAssertEqual(0U, GPBEncodeZigZag32(GPBDecodeZigZag32(0)));
  XCTAssertEqual(1U, GPBEncodeZigZag32(GPBDecodeZigZag32(1)));
  XCTAssertEqual(-1U, GPBEncodeZigZag32(GPBDecodeZigZag32(-1)));
  XCTAssertEqual(14927U, GPBEncodeZigZag32(GPBDecodeZigZag32(14927)));
  XCTAssertEqual(-3612U, GPBEncodeZigZag32(GPBDecodeZigZag32(-3612)));

  XCTAssertEqual(0ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(0)));
  XCTAssertEqual(1ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(1)));
  XCTAssertEqual(-1ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-1)));
  XCTAssertEqual(14927ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(14927)));
  XCTAssertEqual(-3612ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-3612)));

  XCTAssertEqual(856912304801416ULL,
                 GPBEncodeZigZag64(GPBDecodeZigZag64(856912304801416LL)));
  XCTAssertEqual(-75123905439571256ULL,
                 GPBEncodeZigZag64(GPBDecodeZigZag64(-75123905439571256LL)));
}

- (void)testWriteWholeMessage {
  // Not kGPBDefaultRepeatCount because we are comparing to a golden master file
  // that was generated with 2.
  TestAllTypes* message = [self allSetRepeatedCount:2];

  NSData* rawBytes = message.data;
  NSData* goldenData =
      [self getDataFileNamed:@"golden_message" dataToWrite:rawBytes];
  XCTAssertEqualObjects(rawBytes, goldenData);

  // Try different block sizes.
  for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
    NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
    GPBCodedOutputStream* output =
        [GPBCodedOutputStream streamWithOutputStream:rawOutput
                                          bufferSize:blockSize];
    [message writeToCodedOutputStream:output];
    [output flush];

    NSData* actual =
        [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    XCTAssertEqualObjects(rawBytes, actual);
  }

  // Not kGPBDefaultRepeatCount because we are comparing to a golden master file
  // that was generated with 2.
  TestAllExtensions* extensions = [self allExtensionsSetRepeatedCount:2];
  rawBytes = extensions.data;
  goldenData = [self getDataFileNamed:@"golden_packed_fields_message"
                          dataToWrite:rawBytes];
  XCTAssertEqualObjects(rawBytes, goldenData);
}

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
- (void)testCFStringGetCStringPtrAndStringsWithNullChars {
  // This test exists to verify that CFStrings with embedded NULLs still expose
  // their raw buffer if they are backed by UTF8 storage. If this fails, the
  // quick/direct access paths in GPBCodedOutputStream that depend on
  // CFStringGetCStringPtr need to be re-evalutated (maybe just removed).
  // And yes, we do get NULLs in strings from some servers.

  char zeroTest[] = "\0Test\0String";
  // Note: there is a \0 at the end of this since it is a c-string.
  NSString *asNSString = [[NSString alloc] initWithBytes:zeroTest
                                                  length:sizeof(zeroTest)
                                                encoding:NSUTF8StringEncoding];
  const char *cString =
      CFStringGetCStringPtr((CFStringRef)asNSString, kCFStringEncodingUTF8);
  XCTAssertTrue(cString != NULL);
  // Again, if the above assert fails, then it means NSString no longer exposes
  // the raw utf8 storage of a string created from utf8 input, so the code using
  // CFStringGetCStringPtr in GPBCodedOutputStream will still work (it will take
  // a different code path); but the optimizations for when
  // CFStringGetCStringPtr does work could possibly go away.

  XCTAssertEqual(sizeof(zeroTest),
                 [asNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
  XCTAssertTrue(0 == memcmp(cString, zeroTest, sizeof(zeroTest)));
  [asNSString release];
}

- (void)testWriteStringsWithZeroChar {
  // Unicode allows `\0` as a character, and NSString is a class cluster, so
  // there are a few different classes that could end up beind a given string.
  // Historically, we've seen differences based on constant strings in code and
  // strings built via the NSString apis. So this round trips them to ensure
  // they are acting as expected.

  NSArray<NSString *> *strs = @[
    @"\0at start",
    @"in\0middle",
    @"at end\0",
  ];
  int i = 0;
  for (NSString *str in strs) {
    NSData *asUTF8 = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *expected = [NSMutableData data];
    uint8_t lengthByte = (uint8_t)asUTF8.length;
    [expected appendBytes:&lengthByte length:1];
    [expected appendData:asUTF8];

    NSString *context = [NSString stringWithFormat:@"Loop %d - Literal", i];
    [self assertWriteStringNoTag:expected value:str context:context];

    // Force a new string to be built which gets a different class from the
    // NSString class cluster than the literal did.
    NSString *str2 = [NSString stringWithFormat:@"%@", str];
    context = [NSString stringWithFormat:@"Loop %d - Built", i];
    [self assertWriteStringNoTag:expected value:str2 context:context];

    ++i;
  }
}

426
@end