More work on ITAppleEventTools and also fix a compiler warning
[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 -delegate
65 {
66     return delegate;
67 }
68
69 -(int) availableDataLength
70 {
71     int len;
72     [lock lock];
73     len = [data length];
74     [lock unlock];
75     return len;
76 }
77
78 -(NSData*) readDataOfLength:(int)length
79 {
80     NSData *ret;
81     NSRange range = {0, length};
82     [lock lock];
83     ret = [data subdataWithRange:range];
84     [data replaceBytesInRange:range withBytes:nil length:0];
85     [lock unlock];
86     return ret;
87 }
88
89 -(NSData*) readAllData
90 {
91     NSData *ret;
92     [lock lock];
93     ret = [data autorelease];
94     data = [[NSMutableData alloc] init];
95     [lock unlock];
96     return ret;
97 }
98
99 -(void) writeData:(in NSData*)_data
100 {
101     [lock lock];
102     [data appendData:_data];
103     [lock unlock];
104     [delegate newDataAdded:self];
105 }
106
107 -(void) writeBytes:(in char *)b len:(long)length
108 {
109     [lock lock];
110     [data appendBytes:b length:length];
111     [lock unlock];
112     [delegate newDataAdded:self];
113 }
114
115 -(void) lockStream
116 {
117     [lock lock];
118 }
119
120 -(void) unlockStream
121 {
122     [lock unlock];
123 }
124
125 -(void) shortenData:(long)length
126 {
127     NSRange range = {0, length};
128     [data replaceBytesInRange:range withBytes:nil length:0];
129 }
130 @end