2 Copyright (C) 2000-2008 SKYRIX Software AG
3 Copyright (C) 2008 Helge Hess
5 This file is part of SOPE.
7 SOPE is free software; you can redistribute it and/or modify it under
8 the terms of the GNU Lesser General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
12 SOPE is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with SOPE; see the file COPYING. If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
23 #include <NGExtensions/NSString+Escaping.h>
26 @implementation NSString(Escaping)
28 - (NSString *)stringByApplyingCEscaping {
35 if ((len = [self length]) == 0)
38 src = malloc(sizeof(unichar) * (len + 2));
39 [self getCharacters:src];
40 src[len] = 0; // zero-terminate
42 buffer = malloc(sizeof(unichar) * ((len * 2) + 1));
44 for (pos = 0, srcIdx = 0; srcIdx < len; pos++, srcIdx++) {
45 switch (src[srcIdx]) {
47 buffer[pos] = '\\'; pos++;
51 buffer[pos] = '\\'; pos++;
55 buffer[pos] = '\\'; pos++;
60 buffer[pos] = src[srcIdx];
66 s = [NSString stringWithCharacters:buffer length:pos];
68 if (buffer != NULL) { free(buffer); buffer = NULL; }
69 if (src != NULL) { free(src); src = NULL; }
73 - (NSString *)stringByEscapingCharactersFromSet:(NSCharacterSet *)_escSet
74 usingStringEscaping:(<NGStringEscaping>)_esc
76 NSMutableString *safeString;
78 NSRange prevRange, escRange;
82 length = [self length];
83 prevRange = NSMakeRange(0, length);
84 escRange = [self rangeOfCharacterFromSet:_escSet options:0 range:prevRange];
86 needsEscaping = escRange.length > 0 ? YES : NO;
88 return self; /* cheap */
90 safeString = [NSMutableString stringWithCapacity:length];
95 prevRange.length = escRange.location - prevRange.location;
96 if (prevRange.length > 0)
97 [safeString appendString:[self substringWithRange:prevRange]];
99 s = [_esc stringByEscapingString:[self substringWithRange:escRange]];
101 [safeString appendString:s];
103 prevRange.location = NSMaxRange(escRange);
104 todoRange.location = prevRange.location;
105 todoRange.length = length - prevRange.location;
106 escRange = [self rangeOfCharacterFromSet:_escSet
110 while(escRange.length > 0);
112 if (todoRange.length > 0)
113 [safeString appendString:[self substringWithRange:todoRange]];
118 @end /* NSString(Escaping) */