Doesn't crash now. Of course, there's still lots of problems.
[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, *tmp;
74     NSRange range = {0, length};
75     [lock lock];
76     ret = [data subdataWithRange:range];
77 #if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED
78     [data replaceBytesInRange:range withBytes:nil length:0];
79 #else
80     range = {length, [data length]};
81     tmp = [data subdataWithRange:range];
82     [data setData:tmp];
83 #endif
84     [lock unlock];
85     return ret;
86 }
87
88 -(NSData*) readAllData
89 {
90     NSData *ret;
91     [lock lock];
92     ret = [data autorelease];
93     data = [[NSMutableData alloc] init];
94     [lock unlock];
95     return ret;
96 }
97
98 -(void) writeData:(in NSData*)_data
99 {
100     [lock lock];
101     [data appendData:_data];
102     [lock unlock];
103     [delegate newDataAdded:self];
104 }
105
106 -(void) writeBytes:(char *)b len:(long)length
107 {
108     [lock lock];
109     [data appendBytes:b length:length];
110     [lock unlock];
111     [delegate newDataAdded:self];
112 }
113 @end