This whole thing could use a rewrite but whatever
[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 -setDelegate:(id <DataReciever>)d
57 {
58     id old = delegate;
59     [delegate release];
60     delegate = [d retain];
61     return old;
62 }
63
64 -(int) availableDataLength
65 {
66     int len;
67     [lock lock];
68     len = [data length];
69     [lock unlock];
70     return len;
71 }
72
73 -(NSData*) readDataOfLength:(int)length
74 {
75     NSData *ret;
76     NSRange range = {0, length};
77     [lock lock];
78     ret = [data subdataWithRange:range];
79     [data replaceBytesInRange:range withBytes:nil length:0];
80     [lock unlock];
81     return ret;
82 }
83
84 -(NSData*) readAllData
85 {
86     NSData *ret;
87     [lock lock];
88     ret = [data autorelease];
89     data = [[NSMutableData alloc] init];
90     [lock unlock];
91     return ret;
92 }
93
94 -(void) writeData:(in NSData*)_data
95 {
96     [lock lock];
97     [data appendData:_data];
98     [lock unlock];
99     [delegate newDataAdded:self];
100 }
101
102 -(void) writeBytes:(in char *)b len:(long)length
103 {
104     [lock lock];
105     [data appendBytes:b length:length];
106     [lock unlock];
107     [delegate newDataAdded:self];
108 }
109
110 -(void) lockStream
111 {
112     [lock lock];
113 }
114
115 -(void) unlockStream
116 {
117     [lock unlock];
118 }
119
120 -(void) shortenData:(long)length
121 {
122     NSRange range = {0, length};
123     [data replaceBytesInRange:range withBytes:nil length:0];
124 }
125 @end