OSSInputStreamHelper.m 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // OSSInputStreamHelper.m
  3. // AliyunOSSSDK
  4. //
  5. // Created by 怀叙 on 2017/12/7.
  6. // Copyright © 2017年 阿里云. All rights reserved.
  7. //
  8. #import "OSSInputStreamHelper.h"
  9. #import "OSSLog.h"
  10. #import "aos_crc64.h"
  11. @interface OSSInputStreamHelper ()
  12. {
  13. NSInputStream *_inputStream;
  14. CFAbsoluteTime _startTime;
  15. dispatch_semaphore_t _semaphore;
  16. }
  17. @end
  18. @implementation OSSInputStreamHelper
  19. - (instancetype)initWithFileAtPath:(nonnull NSString *)path
  20. {
  21. self = [super init];
  22. if (self) {
  23. _crc64 = 0;
  24. _inputStream = [NSInputStream inputStreamWithFileAtPath:path];
  25. _semaphore = dispatch_semaphore_create(1);
  26. }
  27. return self;
  28. }
  29. - (instancetype)initWithURL:(nonnull NSURL *)URL
  30. {
  31. self = [super init];
  32. if (self) {
  33. _crc64 = 0;
  34. _inputStream = [NSInputStream inputStreamWithURL:URL];
  35. _semaphore = dispatch_semaphore_create(1);
  36. }
  37. return self;
  38. }
  39. - (void)syncReadBuffers
  40. {
  41. dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
  42. _startTime = CFAbsoluteTimeGetCurrent();
  43. [_inputStream open];
  44. NSInteger length = 1;
  45. while (length > 0)
  46. {
  47. @autoreleasepool{
  48. uint8_t streamData[1024 * 4];
  49. length = [_inputStream read:streamData maxLength:1024 * 4];
  50. if (length > 0) {
  51. _crc64 = aos_crc64(_crc64, streamData, length);
  52. }
  53. }
  54. }
  55. if (length < 0) {
  56. OSSLogError(@"there is an error when reading buffer from file!");
  57. }
  58. [_inputStream close];
  59. CFAbsoluteTime duration = CFAbsoluteTimeGetCurrent() - _startTime;
  60. OSSLogDebug(@"read file cost time is :%f",duration);
  61. dispatch_semaphore_signal(_semaphore);
  62. }
  63. - (uint64_t)crc64
  64. {
  65. return _crc64;
  66. }
  67. @end