-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSData+CopyToBuffer.m
61 lines (41 loc) · 1.33 KB
/
NSData+CopyToBuffer.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
// NSData+CopyToBuffer.m
// This file is part of the "SWApplicationSupport" project, and is distributed under the MIT License.
//
// Created by Samuel Williams on 20/02/06.
// Copyright 2006 Samuel Williams. All rights reserved.
//
#import "NSData+CopyToBuffer.h"
#include <string.h>
@interface NSData (PopLinePrivate)
- (NSUInteger) findLineEnding;
@end
@implementation NSData (CopyToBuffer)
- (void) copyToBuffer: (char*)buffer maxLength: (size_t)length {
memcpy(buffer, [self bytes], MIN(length, [self length]));
}
- (NSUInteger) findLineEnding {
const char * buf = [self bytes];
NSUInteger i = 0, sz = [self length];
while (i < sz && buf[i] != '\r' && buf[i] != '\n') {
i++;
}
return i;
}
@end
@implementation NSMutableData (PopLine)
- (NSString*) popLine {
NSUInteger offset = [self findLineEnding];
if (offset >= [self length]) return nil;
NSRange lineRange = NSMakeRange(0, offset);
NSData * lineData = [self subdataWithRange:lineRange];
const char * buf = [self bytes];
while ((buf[offset] == '\r' || buf[offset] == '\n') && offset < [self length]) {
offset += 1;
}
[self replaceBytesInRange:NSMakeRange(0, offset) withBytes:NULL length:0];
NSString * line = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
//NSLog (@"Popping line: %@", line);
return [line autorelease];
}
@end