Permalink
Browse files

Contribution by bwalkin: Added +NSData*[NSData dataWithContentsOfDisp…

…atchData:(dispatch_data_t)data] to easily wrap (not neccesarily copy) a dispatch_data_t object and make it sequential in an NSData object. The returned NSData object will own a reference to the dispatch_data_t object and thus can manage its lifetime
  • Loading branch information...
rsms committed Apr 21, 2012
1 parent fd469e8 commit 351e6c9538c366ca62203acade4b5d2d78d5620c
View
0 peertalk/PTChannel.h 100644 → 100755
No changes.
View
1 peertalk/PTProtocol.h 100644 → 100755
@@ -103,6 +103,7 @@ NSString *PTProtocolErrorDomain;
// holds a reference to the recevier. It's the callers responsibility to call
// dispatch_release on the returned object when done.
- (dispatch_data_t)createReferencingDispatchData;
++ (NSData *)dataWithContentsOfDispatchData:(dispatch_data_t)data;
@end
@interface NSDictionary (PTProtocol)
View
38 peertalk/PTProtocol.m 100644 → 100755
@@ -1,4 +1,5 @@
#import "PTProtocol.h"
+#import <objc/runtime.h>
static const uint32_t PTProtocolVersion1 = 1;
@@ -256,6 +257,7 @@ - (void)readPayloadOfSize:(size_t)payloadSize overChannel:(dispatch_io_t)channel
return;
}
}
+
callback(nil, contiguousData, buffer, bufferSize);
if (contiguousData) dispatch_release(contiguousData);
}
@@ -287,6 +289,22 @@ - (void)readFramesOverChannel:(dispatch_io_t)channel onFrame:(void(^)(NSError*,
@end
+@interface _PTDispatchData : NSObject {
+ dispatch_data_t dispatchData_;
+}
+@end
+@implementation _PTDispatchData
+- (id)initWithDispatchData:(dispatch_data_t)dispatchData {
+ if (!(self = [super init])) return nil;
+ dispatchData_ = dispatchData;
+ dispatch_retain(dispatchData_);
+ return self;
+}
+- (void)dealloc {
+ if (dispatchData_) dispatch_release(dispatchData_);
+}
+@end
+
@implementation NSData (PTProtocol)
- (dispatch_data_t)createReferencingDispatchData {
@@ -299,6 +317,26 @@ - (dispatch_data_t)createReferencingDispatchData {
});
}
++ (NSData *)dataWithContentsOfDispatchData:(dispatch_data_t)data {
+ if (!data) {
+ return nil;
+ }
+ uint8_t *buffer = NULL;
+ size_t bufferSize = 0;
+ dispatch_data_t contiguousData = dispatch_data_create_map(data, (const void **)&buffer, &bufferSize);
+ if (!contiguousData) {
+ return nil;
+ }
+
+ _PTDispatchData *dispatchDataRef = [[_PTDispatchData alloc] initWithDispatchData:contiguousData];
+ NSData *newData = [NSData dataWithBytesNoCopy:(void*)buffer length:bufferSize freeWhenDone:NO];
+ dispatch_release(contiguousData);
+ static const bool kDispatchDataRefKey;
+ objc_setAssociatedObject(newData, (const void*)kDispatchDataRefKey, dispatchDataRef, OBJC_ASSOCIATION_RETAIN);
+
+ return newData;
+}
+
@end
View
0 peertalk/PTUSBHub.h 100644 → 100755
No changes.
View
0 peertalk/PTUSBHub.m 100644 → 100755
No changes.

0 comments on commit 351e6c9

Please sign in to comment.