Huge update to ITFoundation. I've gone through every file (except queue.h
[ITFoundation.git] / ITByteStream.m
1 #import "ITByteStream.h"
2
3 // TODO: Add NSCopying/NSCoding support. Blocking reads (how would this work? NSConditionLock?)
4
5 @implementation ITByteStream
6
7 - (id)init {
8         if (self == [super init]) {
9                 data = [[NSMutableData alloc] init];
10                 lock = [[NSLock alloc] init];
11                 delegate = nil;
12         }
13         return self;
14 }
15
16 - (id)initWithDelegate:(id <ITDataReceiver>)d {
17         if (self == [super init]) {
18                 data = [[NSMutableData alloc] init];
19                 lock = [[NSLock alloc] init];
20                 delegate = [d retain];
21         }
22         return self;
23 }
24
25 - (id)initWithStream:(ITByteStream*)stream delegate:(id <ITDataReceiver>)d {
26         if (self == [super init]) {
27                 data = [stream->data copy];
28                 lock = [[NSLock alloc] init];
29                 delegate = [d retain];
30         }
31         return 0;
32 }
33
34 - (oneway void)dealloc {
35         [lock lock];
36         [data release];
37         [lock unlock];
38         [lock release];
39         [super dealloc];
40 }
41
42 - (id <ITDataReceiver>)setDelegate:(id <ITDataReceiver>)d {
43         id old = delegate;
44         [delegate release];
45         delegate = [d retain];
46         return old;
47 }
48
49 - (id <ITDataReceiver>)delegate {
50         return delegate;
51 }
52
53 - (int)availableDataLength {
54         int len;
55         [lock lock];
56         len = [data length];
57         [lock unlock];
58         return len;
59 }
60
61 - (NSData*)readDataOfLength:(int)length {
62         NSData *ret;
63         NSRange range = {0, length};
64         [lock lock];
65         ret = [data subdataWithRange:range];
66         [data replaceBytesInRange:range withBytes:nil length:0];
67         [lock unlock];
68         return ret;
69 }
70
71 - (NSData*)readAllData {
72         NSData *ret;
73         [lock lock];
74         ret = [data autorelease];
75         data = [[NSMutableData alloc] init];
76         [lock unlock];
77         return ret;
78 }
79
80 - (void)writeData:(in NSData*)_data {
81         [lock lock];
82         [data appendData:_data];
83         [lock unlock];
84         [delegate newDataAdded:self];
85 }
86
87 - (void)writeBytes:(in char *)b len:(long)length {
88         [lock lock];
89         [data appendBytes:b length:length];
90         [lock unlock];
91         [delegate newDataAdded:self];
92 }
93
94 - (void)lockStream {
95         [lock lock];
96 }
97
98 - (void)unlockStream {
99         [lock unlock];
100 }
101
102 - (void)shortenData:(long)length {
103         NSRange range = {0, length};
104         [data replaceBytesInRange:range withBytes:nil length:0];
105 }
106
107 @end