getBuffer: length:
Returns by reference a pointer to a read buffer and, by reference, the number of bytes available, and returns a Boolean value that indicates whether the buffer is available.
- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len
Parameters
- buffer
- Upon return, contains a pointer to a read buffer. The buffer is only valid until the next stream operation is performed.
- len
- Upon return, contains the number of bytes available.
Return Value( NSInputStream getBuffer length example )
YES
if the buffer is available, otherwise NO
.
Subclasses of
NSInputStream
may return NO
if this operation is not appropriate for the stream type.
( NSInputStream getBuffer length example )
uint8_t *buf1;
unsigned int numBytes1;
if ([((NSInputStream *) stream) getBuffer: &buf length: &numBytes]) {
NSLog(@"\t\tBytes are in the buffer before Op.");
}
uint8_t buffer[BUFFER_SIZE];
int len = [((NSInputStream *) stream) read: buffer
maxLength: BUFFER_SIZE];
uint8_t *buf2;
unsigned int numBytes2;
if ([((NSInputStream *) stream) getBuffer: &buf2 length: &numBytes2]) {
NSLog(@"\t\tBytes in the buffer after Op.");
}
( NSInputStream getBuffer length example )
- (void)stream:(NSInputStream *)iStream handleEvent:(NSStreamEvent)event {
BOOL shouldClose = NO;
switch(event) {
case NSStreamEventEndEncountered:
shouldClose = YES;
// If all data hasn't been read, fall through to the "has bytes" event
if(![iStream hasBytesAvailable]) break;
case NSStreamEventHasBytesAvailable: ; // We need a semicolon here before we can declare local variables
uint8_t *buffer;
NSUInteger length;
BOOL freeBuffer = NO;
// The stream has data. Try to get its internal buffer instead of creating one
if(![iStream getBuffer:&buffer length:&length]) {
// The stream couldn't provide its internal buffer. We have to make one ourselves
buffer = malloc(BUFFER_LEN * sizeof(uint8_t));
freeBuffer = YES;
NSInteger result = [iStream read:buffer maxLength:BUFFER_LEN];
if(result < 0) {
// error copying to buffer
break;
}
length = result;
}
// length bytes of data in buffer
if(freeBuffer) free(buffer);
break;
case NSStreamEventErrorOccurred:
// some other error
shouldClose = YES;
break;
}
if(shouldClose) [iStream close];
}