Created
November 26, 2010 15:05
-
-
Save rsms/716819 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <string> | |
@interface NSString (cpp) | |
- (NSUInteger)populateStdString:(std::string&)str | |
usingEncoding:(NSStringEncoding)encoding | |
range:(NSRange)range; | |
@end | |
@implementation NSString (cpp) | |
// Populate a std::string avoiding a double-copy | |
- (NSUInteger)populateStdString:(std::string&)str | |
usingEncoding:(NSStringEncoding)encoding | |
range:(NSRange)range { | |
NSUInteger estimatedSize = [self maximumLengthOfBytesUsingEncoding:encoding]; | |
str.resize(estimatedSize); | |
char *pch = (char*)str.data(); | |
NSUInteger usedBufferCount = 0; | |
[self getBytes:pch | |
maxLength:estimatedSize | |
usedLength:&usedBufferCount | |
encoding:encoding | |
options:0 | |
range:range | |
remainingRange:NULL]; | |
str.resize(usedBufferCount); | |
return usedBufferCount; | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
std::string u8substr; | |
NSUInteger size = [nsstr populateStdString:u8substr | |
usingEncoding:NSUTF8StringEncoding | |
range:highlightRange]; | |
BOOL u8substrIsMutlibyte = size != str.length; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment