Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Cassette/CASQueueFile.m
Original file line number Diff line number Diff line change
Expand Up @@ -504,14 +504,24 @@ - (NSUInteger)usedBytes {
* Stores a 32-bit integer @c value in the @c buffer at the given @c offset.
*/
void writeInt(NSMutableData *buffer, NSUInteger offset, uint32_t value) {
BOOL hasValidRange = buffer.length >= offset + 4;
if (!hasValidRange) {
[NSException raise:NSRangeException
format:@"writeInt buffer out of range"];
}
[buffer replaceBytesInRange:NSMakeRange(offset, 4) withBytes:&value];
}

/**
* Reads a 32-bit integer value from the @c buffer at @c offset.
*/
NSUInteger readUnsignedInt(NSData *buffer, NSUInteger offset) {
uint32_t value;
uint32_t value = 0;
BOOL hasValidRange = buffer.length >= offset + 4;
if (!hasValidRange) {
[NSException raise:NSRangeException
format:@"readUnsignedInt buffer out of range"];
}
[buffer getBytes:&value range:NSMakeRange(offset, 4)];
return value;
}
Expand Down
28 changes: 28 additions & 0 deletions CassetteTests/CASQueueFileTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@

#import "CASQueueFile.h"

@interface CASQueueFile (ExposeMethods)

void writeInt(NSMutableData *buffer, NSUInteger offset, uint32_t value);

NSUInteger readUnsignedInt(NSData *buffer, NSUInteger offset);

@end

@interface CASQueueFileTests : XCTestCase

@property (nonatomic, nullable, strong) CASQueueFile *queueFile;
Expand Down Expand Up @@ -221,4 +229,24 @@ - (void)testRingReadingElementsMaintainsCorrectness {
return dataArray;
}

- (void)testReadInt {
XCTAssertThrows(readUnsignedInt([[NSData alloc] init], 12));
const unsigned char bytes[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
NSData *validBuffer = [NSData dataWithBytes:bytes length:sizeof(bytes)];
NSUInteger value = readUnsignedInt(validBuffer, 12);
XCTAssert(value == 269422093, "Should be valid value in range");
}

- (void)testWriteInt {
const unsigned char bytes[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
NSMutableData *buffer = [NSMutableData dataWithBytes:bytes length:sizeof(bytes)];
NSUInteger value;
XCTAssertThrows(readUnsignedInt([[NSMutableData alloc] init], 1));
value = readUnsignedInt(buffer, 1);
XCTAssert(value == 0);
writeInt(buffer, 1, 84148994);
value = readUnsignedInt(buffer, 1);
XCTAssert(value == 84148994);
}

@end