QNCrc32.m 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // QNCrc.m
  3. // QiniuSDK
  4. //
  5. // Created by bailong on 14-9-29.
  6. // Copyright (c) 2014年 Qiniu. All rights reserved.
  7. //
  8. #import <zlib.h>
  9. #import "QNConfiguration.h"
  10. #import "QNCrc32.h"
  11. @implementation QNCrc32
  12. + (UInt32)data:(NSData *)data {
  13. uLong crc = crc32(0L, Z_NULL, 0);
  14. crc = crc32(crc, [data bytes], (uInt)[data length]);
  15. return (UInt32)crc;
  16. }
  17. + (UInt32)file:(NSString *)filePath
  18. error:(NSError **)error {
  19. @autoreleasepool {
  20. NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:error];
  21. if (*error != nil) {
  22. return 0;
  23. }
  24. int len = (int)[data length];
  25. int count = (len + kQNBlockSize - 1) / kQNBlockSize;
  26. uLong crc = crc32(0L, Z_NULL, 0);
  27. for (int i = 0; i < count; i++) {
  28. int offset = i * kQNBlockSize;
  29. int size = (len - offset) > kQNBlockSize ? kQNBlockSize : (len - offset);
  30. NSData *d = [data subdataWithRange:NSMakeRange(offset, (unsigned int)size)];
  31. crc = crc32(crc, [d bytes], (uInt)[d length]);
  32. }
  33. return (UInt32)crc;
  34. }
  35. }
  36. @end