Give me a B! Give me a U! Give me a G!
[ITFoundation.git] / ITByteStream.m
1 //
2 //  ITByteStream.h
3 //  ITFoundation
4 //
5 //  Created by Alexander Strange on Thu Feb 27 2003.
6 //  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
7 //
8
9 #import "ITByteStream.h"
10
11 // TODO: Add NSCopying/NSCoding support. Blocking reads (how would this work? NSConditionLock?)
12
13 @implementation ITByteStream
14 -(id) init
15 {
16     if (self == [super init])
17            {
18            data = [[NSMutableData alloc] init];
19            lock = [[NSLock alloc] init];
20            delegate = nil;
21            }
22     return self;
23 }
24
25 -(id) initWithDelegate:(id)d
26 {
27     if (self == [super init])
28            {
29            data = [[NSMutableData alloc] init];
30            lock = [[NSLock alloc] init];
31            delegate = [d retain];
32            }
33     return self;
34 }
35
36 -(id) initWithStream:(ITByteStream*)stream delegate:(id)d
37 {
38     if (self == [super init])
39            {
40            data = [stream->data copy];
41            lock = [[NSLock alloc] init];
42            delegate = [d retain];
43            }
44     return 0;
45 }
46
47 -(oneway void) dealloc
48 {
49     [lock lock];
50     [data release];
51     [lock unlock];
52     [lock release];
53     [super dealloc];
54 }
55
56 -(void) setDelegate:(id <ITByteStreamDelegate>)d
57 {
58     [delegate release];
59     delegate = [d retain];
60 }
61
62 -(int) availableDataLength
63 {
64     int len;
65     [lock lock];
66     len = [data length];
67     [lock unlock];
68     return len;
69 }
70
71 -(NSData*) readDataOfLength:(int)length
72 {
73     NSData *ret;
74     NSRange range = {0, length};
75     [lock lock];
76     ret = [data subdataWithRange:range];
77     [data replaceBytesInRange:range withBytes:nil length:0];
78     [lock unlock];
79     return ret;
80 }
81
82 -(NSData*) readAllData
83 {
84     NSData *ret;
85     [lock lock];
86     ret = [data autorelease];
87     data = [[NSMutableData alloc] init];
88     [lock unlock];
89     return ret;
90 }
91
92 -(void) writeData:(in NSData*)_data
93 {
94     [lock lock];
95     [data appendData:_data];
96     [lock unlock];
97     [delegate newDataAdded:self];
98 }
99
100 -(void) writeBytes:(char *)b len:(long)length
101 {
102     [lock lock];
103     [data appendBytes:b length:length];
104     [lock unlock];
105     [delegate newDataAdded:self];
106 }
107
108 -(void) lockStream
109 {
110     [lock lock];
111 }
112
113 -(void) unlockStream
114 {
115     [lock unlock];
116 }
117
118 -(void) shortenData:(long)length
119 {
120     NSRange range = {0, length};
121     [data replaceBytesInRange:range withBytes:nil length:0];
122 }
123 @end