-
Notifications
You must be signed in to change notification settings - Fork 0
/
ITByteStream.m
107 lines (90 loc) · 1.94 KB
/
ITByteStream.m
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
#import "ITByteStream.h"
// TODO: Add NSCopying/NSCoding support. Blocking reads (how would this work? NSConditionLock?)
@implementation ITByteStream
- (id)init {
if (self == [super init]) {
data = [[NSMutableData alloc] init];
lock = [[NSLock alloc] init];
delegate = nil;
}
return self;
}
- (id)initWithDelegate:(id <ITDataReceiver>)d {
if (self == [super init]) {
data = [[NSMutableData alloc] init];
lock = [[NSLock alloc] init];
delegate = [d retain];
}
return self;
}
- (id)initWithStream:(ITByteStream*)stream delegate:(id <ITDataReceiver>)d {
if (self == [super init]) {
data = [stream->data copy];
lock = [[NSLock alloc] init];
delegate = [d retain];
}
return 0;
}
- (oneway void)dealloc {
[lock lock];
[data release];
[lock unlock];
[lock release];
[super dealloc];
}
- (id <ITDataReceiver>)setDelegate:(id <ITDataReceiver>)d {
id old = delegate;
[delegate release];
delegate = [d retain];
return old;
}
- (id <ITDataReceiver>)delegate {
return delegate;
}
- (int)availableDataLength {
int len;
[lock lock];
len = [data length];
[lock unlock];
return len;
}
- (NSData*)readDataOfLength:(int)length {
NSData *ret;
NSRange range = {0, length};
[lock lock];
ret = [data subdataWithRange:range];
[data replaceBytesInRange:range withBytes:nil length:0];
[lock unlock];
return ret;
}
- (NSData*)readAllData {
NSData *ret;
[lock lock];
ret = [data autorelease];
data = [[NSMutableData alloc] init];
[lock unlock];
return ret;
}
- (void)writeData:(in NSData*)_data {
[lock lock];
[data appendData:_data];
[lock unlock];
[delegate newDataAdded:self];
}
- (void)writeBytes:(in char *)b len:(long)length {
[lock lock];
[data appendBytes:b length:length];
[lock unlock];
[delegate newDataAdded:self];
}
- (void)lockStream {
[lock lock];
}
- (void)unlockStream {
[lock unlock];
}
- (void)shortenData:(long)length {
NSRange range = {0, length};
[data replaceBytesInRange:range withBytes:nil length:0];
}
@end