Skip to content

Instantly share code, notes, and snippets.

@rsms
Created November 26, 2010 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsms/716819 to your computer and use it in GitHub Desktop.
Save rsms/716819 to your computer and use it in GitHub Desktop.
#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
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