Rename some methods; remove extraneous others
[SA_NSDataExtensions.git] / NSData+SA_NSDataExtensions.m
blob8cfa8598dc5e80d6be895231f812090530dbcbf4
1 //
2 //  NSData+SA_NSDataExtensions.m
3 //
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 {
12         if (self.length == 0)
13                 return NO;
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" 
25                                                           length:1];
26         } else if (self.isNullTerminated) {
27                 return self;
28         } else {
29                 char* terminated_string_buffer = malloc(self.length + 1);
30                 [self getBytes:terminated_string_buffer 
31                                 length:self.length];
32                 terminated_string_buffer[self.length] = '\0';
33                 
34                 return [NSData dataWithBytesNoCopy:terminated_string_buffer 
35                                                                         length:(self.length + 1) 
36                                                           freeWhenDone:YES];
37         }
40 +(NSData *) dataWithBlankCString {
41         return [NSData dataWithBytes:"\0" 
42                                                   length:1];
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)];
55 @end