NSData+NSInputStream.m 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // NSData+NSInputStream.m
  3. // Tidbits
  4. //
  5. // Created by Ewan Mellor on 6/16/13.
  6. // Copyright (c) 2013 Tipbit, Inc. All rights reserved.
  7. //
  8. #import "NSData+NSInputStream.h"
  9. #define BUFSIZE 65536U
  10. @implementation NSData (NSInputStream)
  11. +(NSData *)dataWithContentsOfStream:(NSInputStream *)input initialCapacity:(NSUInteger)capacity error:(NSError **)error {
  12. size_t bufsize = MIN(BUFSIZE, capacity);
  13. uint8_t * buf = malloc(bufsize);
  14. if (buf == NULL) {
  15. if (error) {
  16. *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
  17. }
  18. return nil;
  19. }
  20. NSMutableData* result = capacity == NSUIntegerMax ? [NSMutableData data] : [NSMutableData dataWithCapacity:capacity];
  21. @try {
  22. while (true) {
  23. NSInteger n = [input read:buf maxLength:bufsize];
  24. if (n < 0) {
  25. result = nil;
  26. if (error) {
  27. *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil];
  28. }
  29. break;
  30. }
  31. else if (n == 0) {
  32. break;
  33. }
  34. else {
  35. [result appendBytes:buf length:n];
  36. }
  37. }
  38. }
  39. @catch (NSException * exn) {
  40. SVGKitLogWarn(@"[%@] WARNING: caught exception writing to file: %@", [self class], exn);
  41. result = nil;
  42. if (error) {
  43. *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:EIO userInfo:nil];
  44. }
  45. }
  46. free(buf);
  47. return result;
  48. }
  49. @end