Skip to content

Commit

Permalink
Operate directly on NSMutableData for incoming socket data, do not wo…
Browse files Browse the repository at this point in the history
…rk with raw buffers

Signed-off-by: Claudio Cambra <[email protected]>
  • Loading branch information
claucambra committed Jul 24, 2023
1 parent 120218a commit b35e3d6
Showing 1 changed file with 5 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,8 @@ - (void)processInBuffer
{
NSLog(@"Processing in buffer. In buffer length %li", _inBuffer.length);

UInt8 separator[] = {0xa}; // Byte value for "\n"
static const UInt8 separator[] = {0xa}; // Byte value for "\n"
static const char terminator[] = {0};
NSData * const separatorData = [NSData dataWithBytes:separator length:1];

while(_inBuffer.length > 0) {
Expand All @@ -338,24 +339,21 @@ - (void)processInBuffer
options:0
range:inBufferLengthRange];

unsigned char *buffer = _inBuffer.mutableBytes;
NSUInteger nullTerminatorIndex = NSUIntegerMax;

// Add NULL terminator, so we can use C string methods
if (firstSeparatorIndex.location == NSNotFound) {
NSLog(@"No separator found. Creating new buffer qith space for null terminator.");

unsigned char *newBuffer = malloc(sizeof(unsigned char) * (inBufferLength + 1));
memcpy(newBuffer, buffer, inBufferLength);
buffer = newBuffer;
[_inBuffer appendBytes:terminator length:1];
nullTerminatorIndex = inBufferLength;
} else {
nullTerminatorIndex = firstSeparatorIndex.location;
[_inBuffer replaceBytesInRange:NSMakeRange(nullTerminatorIndex, 1) withBytes:terminator];
}

NSAssert(nullTerminatorIndex != NSUIntegerMax, @"Null terminator index should be valid.");

buffer[nullTerminatorIndex] = 0; // Add NULL terminator, so we can use C string methods

NSString * const newLine = [NSString stringWithUTF8String:_inBuffer.bytes];
const NSRange nullTerminatorRange = NSMakeRange(0, nullTerminatorIndex + 1);

Expand Down

0 comments on commit b35e3d6

Please sign in to comment.