2 // NSData+SA_NSDataExtensions.m
4 // Copyright 2015-2021 Said Achmiz.
5 // See LICENSE and README.md for more info.
7 #import "NSData+SA_NSDataExtensions.h"
9 @implementation NSData (SA_NSDataExtensions)
11 -(BOOL) isNullTerminated {
15 return (((char*) self.bytes)[self.length - 1] == '\0');
18 -(const char *) terminatedCString {
19 return self.dataWithTerminatedCString.bytes;
22 -(NSData *) dataWithTerminatedCString {
23 if (self.length == 0) {
24 return [NSData dataWithBytes:"\0"
26 } else if (self.isNullTerminated) {
29 char* terminated_string_buffer = malloc(self.length + 1);
30 [self getBytes:terminated_string_buffer
32 terminated_string_buffer[self.length] = '\0';
34 return [NSData dataWithBytesNoCopy:terminated_string_buffer
35 length:(self.length + 1)
40 +(NSData *) dataWithBlankCString {
41 return [NSData dataWithBytes:"\0"
45 +(NSData *) dataFromCString:(const char *)cString {
46 return [NSData dataWithBytes:cString
47 length:strlen(cString)];
50 +(NSData *) dataWithCString:(char *)cString {
51 return [NSData dataWithBytesNoCopy:cString
52 length:strlen(cString)];