char* ConvertStringToEncoding(CFStringRef string, CFStringEncoding encoding, int identifier) { char* output = NULL; if (_pbxgdb_plugin_functions) { // we want to convert the whole string CFRange range; range.location = 0; range.length = CFStringGetLength(string); // find out how big our utf-8 buffer needs to be CFIndex length_needed; CFStringGetBytes(string, range, encoding, '?', false, NULL, 0, &length_needed); // make the output buffer // just in case the convert call fails completely, we zero terminate it output = (char*)(_pbxgdb_plugin_functions->allocate(identifier, length_needed + 1)); if (output) { output[0] = 0; // try to get the actual string - we terminate it for safety CFStringGetBytes(string, range, encoding, '?', false, (UInt8*) output, length_needed, &length_needed); output[length_needed] = 0; } } if (output) DEBUG_PRINT("converted: %s\n", output); return output ? output : kNullPluginError; }
char * _SC_cfstring_to_cstring(CFStringRef cfstr, char *buf, CFIndex bufLen, CFStringEncoding encoding) { CFIndex converted; CFIndex last = 0; CFIndex len; if (cfstr == NULL) { cfstr = CFSTR(""); } len = CFStringGetLength(cfstr); /* how much buffer space will we really need? */ converted = CFStringGetBytes(cfstr, CFRangeMake(0, len), encoding, 0, FALSE, NULL, 0, &last); if (converted < len) { /* if full string could not be converted */ if (buf != NULL) { buf[0] = '\0'; } return NULL; } if (buf != NULL) { if (bufLen < (last + 1)) { /* if the size of the provided buffer is too small */ buf[0] = '\0'; return NULL; } } else { /* allocate a buffer */ bufLen = last + 1; buf = CFAllocatorAllocate(NULL, bufLen, 0); if (buf == NULL) { return NULL; } } (void)CFStringGetBytes(cfstr, CFRangeMake(0, len), encoding, 0, FALSE, (UInt8 *)buf, bufLen, &last); buf[last] = '\0'; return buf; }
const char *Tcl_UniCharToUtfDString(Tcl_UniChar *characters, size_t length, Tcl_DString *ds) { CFStringRef str = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,characters, length, kCFAllocatorNull); CFRange range = {0,length}; // all the characters CFIndex bufLen = 0; CFStringGetBytes(str, range, kCFStringEncodingUTF8, true, false, NULL, 0, &bufLen); *ds = (malloc(bufLen)); CFStringGetBytes(str, range, kCFStringEncodingUTF8, true, false, *ds, bufLen, &bufLen); CFRelease(str); return (const char *)*ds; }
extern pascal OSStatus CFQStringCopyCString(CFStringRef str, CFStringEncoding encoding, char **cStrPtr) // See comment in header. { OSStatus err; CFIndex cStrLen; CFRange range; assert( str != NULL); assert( cStrPtr != NULL); assert(*cStrPtr == NULL); err = noErr; range = CFRangeMake(0, CFStringGetLength(str)); (void) CFStringGetBytes(str, range, encoding, 0, false, NULL, 0, &cStrLen); // Can't convert to CFQAllocate because the caller is required // to free the string using "free", and there's no guarantee that // CFQAllocate and "free" are compatible (for example, if you're // compiling CFM and running on Mac OS X, "free" is from an MSL pool // while CFQAllocate allocates from System framework). // // Anyway, this isn't a problem because the size is always at // least one byte, so malloc won't misbehave. *cStrPtr = (char *) malloc( ((size_t) cStrLen) + 1); if (*cStrPtr == NULL) { err = memFullErr; } if (err == noErr) { #if MORE_DEBUG (*cStrPtr)[cStrLen] = '¥'; #endif if ( CFStringGetBytes(str, range, encoding, 0, false, (UInt8 *) *cStrPtr, cStrLen, &cStrLen) != range.length ) { err = kCFQDataErr; } } if (err == noErr) { assert((*cStrPtr)[cStrLen] == '¥'); (*cStrPtr)[cStrLen] = 0; } else { free(*cStrPtr); *cStrPtr = NULL; } assert( (err == noErr) == (*cStrPtr != NULL) ); return err; }
std::string Path::toUTF8() const { #ifdef OSX CFRange myRange = CFRangeMake(0, CFStringGetLength(_myString)); CFIndex myBufferSize = 0; std::string myResult; CFIndex myCharCount = CFStringGetBytes(_myString, myRange, kCFStringEncodingUTF8, '?', FALSE, 0, 0, &myBufferSize); if (myCharCount) { myResult.resize(myBufferSize); CFIndex myExCharCount = CFStringGetBytes(_myString, myRange, kCFStringEncodingUTF8, '?', FALSE, (UInt8*)&(*(myResult.begin())), myBufferSize, &myBufferSize); ASSURE_WITH(AssurePolicy::Throw, myExCharCount == myCharCount); } return myResult; #elif _WIN32 if (_myLocaleChars == 0) { return std::string(); } // convert from active codepage to WideChars AC_SIZE_TYPE myWCharSize = MultiByteToWideChar(CP_ACP, getMultibyteToWideCharFlags(), _myLocaleChars, -1, 0, 0); if (myWCharSize == 0) { throw UnicodeException(errorDescription(lastError()), PLUS_FILE_LINE); } LPWSTR myWChars = new WCHAR[myWCharSize]; MultiByteToWideChar(CP_ACP, getMultibyteToWideCharFlags(), _myLocaleChars, -1, myWChars, myWCharSize); // convert from WideChars to UTF8 AC_SIZE_TYPE myUTF8Size = WideCharToMultiByte(CP_UTF8, 0, myWChars, -1, 0, 0, 0, 0); if (myUTF8Size == 0) { throw UnicodeException(errorDescription(lastError()), PLUS_FILE_LINE); } char * myUTF8Chars = new char[myUTF8Size]; WideCharToMultiByte(CP_UTF8, 0, myWChars, -1, myUTF8Chars, myUTF8Size, 0, 0); std::string myUTF8String(myUTF8Chars); delete [] myWChars; delete [] myUTF8Chars; return myUTF8String; #else if (_myLocaleChars == 0) { return std::string(); } gchar * myUTF = g_filename_to_utf8(_myLocaleChars, -1, 0, 0, 0); if ( ! myUTF) { throw UnicodeException(std::string("Failed to convert filename '") + _myLocaleChars + "' to UTF8.", PLUS_FILE_LINE); } std::string myUTF8String(myUTF); g_free(myUTF); return myUTF8String; #endif }
CString TextCodecMac::encode(const UChar* characters, size_t length, UnencodableHandling handling) { // FIXME: We should really use TEC here instead of CFString for consistency with the other direction. // FIXME: Since there's no "force ASCII range" mode in CFString, we change the backslash into a yen sign. // Encoding will change the yen sign back into a backslash. String copy(characters, length); copy.replace('\\', m_backslashAsCurrencySymbol); CFStringRef cfs = copy.createCFString(); CFIndex startPos = 0; CFIndex charactersLeft = CFStringGetLength(cfs); Vector<char> result; size_t size = 0; UInt8 lossByte = handling == QuestionMarksForUnencodables ? '?' : 0; while (charactersLeft > 0) { CFRange range = CFRangeMake(startPos, charactersLeft); CFIndex bufferLength; CFStringGetBytes(cfs, range, m_encoding, lossByte, false, NULL, 0x7FFFFFFF, &bufferLength); result.grow(size + bufferLength); unsigned char* buffer = reinterpret_cast<unsigned char*>(result.data() + size); CFIndex charactersConverted = CFStringGetBytes(cfs, range, m_encoding, lossByte, false, buffer, bufferLength, &bufferLength); size += bufferLength; if (charactersConverted != charactersLeft) { unsigned badChar = CFStringGetCharacterAtIndex(cfs, startPos + charactersConverted); ++charactersConverted; if ((badChar & 0xFC00) == 0xD800 && charactersConverted != charactersLeft) { // is high surrogate UniChar low = CFStringGetCharacterAtIndex(cfs, startPos + charactersConverted); if ((low & 0xFC00) == 0xDC00) { // is low surrogate badChar <<= 10; badChar += low; badChar += 0x10000 - (0xD800 << 10) - 0xDC00; ++charactersConverted; } } UnencodableReplacementArray entity; int entityLength = getUnencodableReplacement(badChar, handling, entity); result.grow(size + entityLength); memcpy(result.data() + size, entity, entityLength); size += entityLength; } startPos += charactersConverted; charactersLeft -= charactersConverted; } CFRelease(cfs); return CString(result.data(), size); }
bool HIDDeviceManager::getStringProperty(IOHIDDeviceRef device, CFStringRef propertyName, String* pResult) { CFStringRef str = (CFStringRef) IOHIDDeviceGetProperty(device, propertyName); if (!str) { return false; } CFIndex length = CFStringGetLength(str); CFRange range = CFRangeMake(0, length); // Test the conversion first to get required buffer size. CFIndex bufferLength; CFIndex numberOfChars = CFStringGetBytes(str, range, kCFStringEncodingUTF8, (char) '?', FALSE, NULL, 0, &bufferLength); if (numberOfChars == 0) { return false; } // Now allocate buffer. char* buffer = new char[bufferLength+1]; numberOfChars = CFStringGetBytes(str, range, kCFStringEncodingUTF8, (char) '?', FALSE, (UInt8*) buffer, bufferLength, NULL); OVR_ASSERT_LOG(numberOfChars != 0, ("CFStringGetBytes failed.")); buffer[bufferLength] = '\0'; *pResult = String(buffer); return true; }
void HP_Object::Show() const { // the default implementation is to print the object's ID, class ID and name (if it has one) // make a string for the class ID char theClassID[] = CA4CCToCString(mClassID); // get the object's name CAPropertyAddress theAddress(kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster); CFStringRef theCFName = NULL; UInt32 theSize = sizeof(CFStringRef); try { GetPropertyData(theAddress, 0, NULL, theSize, &theCFName); } catch(...) { theCFName = NULL; } // make a C string out of the name char theName[256]; theName[0] = 0; if(theCFName != NULL) { CFIndex theLength = 0; CFRange theRange = { 0, CFStringGetLength(theCFName) }; CFStringGetBytes(theCFName, theRange, kCFStringEncodingUTF8, 0, false, (UInt8*)theName, 255, &theLength); theName[theLength] = 0; CFRelease(theCFName); } // print the information to the standard output printf("AudioObjectID:\t\t0x%lX\n\tAudioClassID:\t'%s'\n\tName:\t\t\t%s\n", (long unsigned int)mObjectID, theClassID, theName); }
static char * cfstring_to_cstring(CFStringRef cfstr, char *buf, int bufLen) { CFIndex len = CFStringGetLength(cfstr); if (!buf) { bufLen = len + 1; buf = CFAllocatorAllocate(NULL, bufLen, 0); } if (len >= bufLen) { len = bufLen - 1; } (void)CFStringGetBytes(cfstr, CFRangeMake(0, len), kCFStringEncodingASCII, 0, FALSE, buf, bufLen, NULL); buf[len] = '\0'; return buf; }
PA_Unichar* charToPA_Unichar(char* src){ CFStringRef cfstr = CFStringCreateWithCString(kCFAllocatorDefault, src, kCFStringEncodingUTF8); PA_Unichar *dst = malloc(CFStringGetLength(cfstr)); CFIndex index; CFStringGetBytes(cfstr, CFRangeMake(0, CFStringGetLength(cfstr)), kCFStringEncodingUTF16, 0, false, dst, CFStringGetLength(cfstr), &index); return dst; }
bool UTF8toUTF16(const std::string &str, utf16_char *buf, unsigned int max_len) { bool result = false; CFStringRef input = CFStringCreateWithCString(kCFAllocatorDefault, str.c_str(), kCFStringEncodingUTF8); if(input) { CFIndex len = CFStringGetLength(input); if(len < max_len) { CFRange range = {0, len}; CFIndex chars = CFStringGetBytes(input, range, kCFStringEncodingUTF16, '?', FALSE, (UInt8 *)buf, max_len * sizeof(utf16_char), NULL); result = (chars == len); buf[len] = '\0'; } CFRelease(input); } return result; }
static ST_Error set_str(ST_UserTextFrame *f, CFStringRef s, uint8_t **ptr, uint32_t *sz) { CFIndex slen; CFIndex l; uint8_t *buf; void *tmp; /* Make space for it */ slen = CFStringGetLength(s); l = CFStringGetMaximumSizeForEncoding(slen, encs[f->encoding]); if(!(buf = (uint8_t *)malloc(l))) return ST_Error_errno; CFStringGetBytes(s, CFRangeMake(0, slen), encs[f->encoding], 0, f->encoding == ST_TextEncoding_UTF16, buf, l, &slen); /* Attempt to make it smaller */ if(slen != l) { if((tmp = realloc(buf, slen))) buf = (uint8_t *)tmp; } free(*ptr); *sz = slen; *ptr = buf; return ST_Error_None; }
void Caching_Stream::streamEndEncountered() { if (m_fileOutput) { delete m_fileOutput, m_fileOutput = 0; } if (m_cacheable) { if (m_writable) { CS_TRACE("Successfully cached the stream\n"); CS_TRACE_CFURL(m_fileUrl); // We only write the meta data if the stream was successfully streamed. // In that way we can use the meta data as an indicator that there is a file to stream. if (!m_cacheMetaDataWritten) { CFWriteStreamRef writeStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault, m_metaDataUrl); if (writeStream) { if (CFWriteStreamOpen(writeStream)) { CFStringRef contentType = m_target->contentType(); UInt8 buf[1024]; CFIndex usedBytes = 0; if (contentType) { // It is possible that some streams don't provide a content type CFStringGetBytes(contentType, CFRangeMake(0, CFStringGetLength(contentType)), kCFStringEncodingUTF8, '?', false, buf, 1024, &usedBytes); } if (usedBytes > 0) { CS_TRACE("Writing the meta data\n"); CS_TRACE_CFSTRING(contentType); CFWriteStreamWrite(writeStream, buf, usedBytes); } CFWriteStreamClose(writeStream); } CFRelease(writeStream); } m_cacheable = false; m_writable = false; m_useCache = true; m_cacheMetaDataWritten = true; } } } if (m_delegate) { m_delegate->streamEndEncountered(); } }
// Function to convert and copy string literals to the format expected by the exporter API. // On Win: Pass the input directly to the output // On Mac: All conversion happens through the CFString format void copyConvertStringLiteralIntoUTF16(const wchar_t* inputString, prUTF16Char* destination) { #ifdef PRMAC_ENV int length = wcslen(inputString); CFRange range = {0, kPrMaxPath}; range.length = length; CFStringRef inputStringCFSR = CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(inputString), length * sizeof(wchar_t), kCFStringEncodingUTF32LE, kPrFalse); CFStringGetBytes( inputStringCFSR, range, kCFStringEncodingUTF16, 0, kPrFalse, reinterpret_cast<UInt8 *>(destination), length * (sizeof (prUTF16Char)), NULL); destination[length] = 0; // Set NULL-terminator, since CFString calls don't set it, and MediaCore hosts expect it CFRelease(inputStringCFSR); #elif defined PRWIN_ENV size_t length = wcslen(inputString); wcscpy_s(destination, length + 1, inputString); #endif }
int convertChars(char *from, int fromLen, void *fromCode, char *to, int toLen, void *toCode, int norm, int term) { CFStringRef cfs= CFStringCreateWithBytes(NULL, (UInt8 *) from, fromLen, (CFStringEncoding)fromCode, 0); if (cfs == NULL) { toLen = 0; to[toLen]= '\0'; return toLen; } CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, cfs); CFRelease(cfs); if (norm) // HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements CFStringNormalize(str, kCFStringNormalizationFormD); // canonical decomposition else CFStringNormalize(str, kCFStringNormalizationFormC); // pre-combined { CFRange rng= CFRangeMake(0, CFStringGetLength(str)); CFIndex len= 0; CFIndex num= CFStringGetBytes(str, rng, (CFStringEncoding)toCode, '?', 0, (UInt8 *)to, toLen - term, &len); CFRelease(str); if (!num) return convertCopy(from, fromLen, to, toLen, term); if (term) to[len]= '\0'; return len; } }
void ARRAY_TEXT::convertToUTF8(const CUTF16String* fromString, CUTF8String* toString) { #ifdef _WIN32 int len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)fromString->c_str(), fromString->length(), NULL, 0, NULL, NULL); if(len){ std::vector<uint8_t> buf(len + 1); if(WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)fromString->c_str(), fromString->length(), (LPSTR)&buf[0], len, NULL, NULL)){ *toString = CUTF8String((const uint8_t *)&buf[0]); } }else{ *toString = CUTF8String((const uint8_t *)""); } #else CFStringRef str = CFStringCreateWithCharacters(kCFAllocatorDefault, (const UniChar *)fromString->c_str(), fromString->length()); if(str){ size_t size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8) + sizeof(uint8_t); std::vector<uint8_t> buf(size); CFIndex len = 0; CFStringGetBytes(str, CFRangeMake(0, CFStringGetLength(str)), kCFStringEncodingUTF8, 0, true, (UInt8 *)&buf[0], size, &len); *toString = CUTF8String((const uint8_t *)&buf[0], len); CFRelease(str); } #endif }
ST_FUNC ST_Error ST_ID3v2_TextFrame_setTextStr(ST_TextFrame *f, CFStringRef s) { CFIndex slen; CFIndex l; uint8_t *buf; void *tmp; if(!f || !s) return ST_Error_InvalidArgument; /* Make space for it */ slen = CFStringGetLength(s); l = CFStringGetMaximumSizeForEncoding(slen, encs[f->encoding]); if(!(buf = (uint8_t *)malloc(l))) return ST_Error_errno; CFStringGetBytes(s, CFRangeMake(0, slen), encs[f->encoding], 0, f->encoding == ST_TextEncoding_UTF16, buf, l, &slen); /* Attempt to make it smaller */ if(slen != l) { if((tmp = realloc(buf, slen))) buf = (uint8_t *)tmp; } free(f->string); f->size = slen; f->string = buf; return ST_Error_None; }
static int get_string_property_utf8(IOHIDDeviceRef device, CFStringRef prop, char *buf, size_t len) { CFStringRef str = IOHIDDeviceGetProperty(device, prop); buf[0] = 0x0000; if (str) { CFRange range; range.location = 0; range.length = len; CFIndex used_buf_len; CFStringGetBytes(str, range, kCFStringEncodingUTF8, (char)'?', FALSE, (UInt8*)buf, len, &used_buf_len); buf[len-1] = 0x00000000; return used_buf_len; } else return 0; }
void HP_Stream::Show() const { // get the object's name CAPropertyAddress theAddress(kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster); CFStringRef theCFName = NULL; UInt32 theSize = sizeof(CFStringRef); try { GetPropertyData(theAddress, 0, NULL, theSize, &theCFName); } catch(...) { theCFName = NULL; } // make a C string out of the name char theName[256]; theName[0] = 0; if(theCFName != NULL) { CFIndex theLength = 0; CFRange theRange = { 0, CFStringGetLength(theCFName) }; CFStringGetBytes(theCFName, theRange, kCFStringEncodingUTF8, 0, false, (UInt8*)theName, 255, &theLength); theName[theLength] = 0; CFRelease(theCFName); } // print the information to the standard output //printf("AudioObjectID:\t0x%lX\n\tClass:\t\t%s\n\tName:\t\t%s\n\tDirection:\t%s\n\tChannels:\t%lu\n", (long unsigned int)mObjectID, "Audio Stream", theName, (IsInput() ? "Input" : "Output"), (long unsigned int)GetCurrentNumberChannels()); }
static int get_string_property_utf8(IOHIDDeviceRef device, CFStringRef prop, char *buf, size_t len) { CFStringRef str; if (!len) return 0; str = IOHIDDeviceGetProperty(device, prop); buf[0] = 0; if (str) { len--; CFIndex str_len = CFStringGetLength(str); CFRange range; range.location = 0; range.length = (str_len > len)? len: str_len; CFIndex used_buf_len; CFIndex chars_copied; chars_copied = CFStringGetBytes(str, range, kCFStringEncodingUTF8, (char)'?', FALSE, (UInt8*)buf, len, &used_buf_len); buf[chars_copied] = 0; return used_buf_len; } else return 0; }
/* dru_getlongdevicedescription Fills a character buffer with a device's long description: VENDOR PRODUCT (FIRMWARE) via BUS. The incoming buffer is returned as a convenience. */ char * druGetDeviceLongDescription(DRDeviceRef device, char *buffer, size_t bufSize) { CFDictionaryRef deviceInfo = DRDeviceCopyInfo(device); CFStringRef bus = CFDictionaryGetValue(deviceInfo,kDRDevicePhysicalInterconnectKey); CFStringRef desc; CFIndex len = 0; #if 1 /* for now, until the bus starts getting returned in ASCII */ if (CFEqual(bus,kDRDevicePhysicalInterconnectFireWire)) bus = CFSTR("FireWire"); else if (CFEqual(bus,kDRDevicePhysicalInterconnectUSB)) bus = CFSTR("USB"); else if (CFEqual(bus,kDRDevicePhysicalInterconnectATAPI)) bus = CFSTR("ATAPI"); else if (CFEqual(bus,kDRDevicePhysicalInterconnectSCSI)) bus = CFSTR("SCSI"); else bus = CFSTR("unknown interface"); #endif desc = CFStringCreateWithFormat(NULL,NULL,CFSTR("%@ %@ (%@) via %@"), CFDictionaryGetValue(deviceInfo,kDRDeviceVendorNameKey), CFDictionaryGetValue(deviceInfo,kDRDeviceProductNameKey), CFDictionaryGetValue(deviceInfo,kDRDeviceFirmwareRevisionKey), bus); CFStringGetBytes(desc, CFRangeMake(0,CFStringGetLength(desc)), kCFStringEncodingASCII, '.', false, (UInt8*)buffer, bufSize-1, &len); buffer[len] = 0; CFRelease(deviceInfo); CFRelease(desc); return buffer; }
// char to utf16_t conversion void CharConvUS(charconv* Conv, utf16_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { // assume wchar_t is 16 bits even if it's not true charconv_osx *CC = (charconv_osx *)Conv; if (CC) { CFStringRef TmpIn = CFStringCreateWithCString(NULL, In, CC->EncFrom); assert(TmpIn); if (TmpIn) { CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, CC->EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); memset((UInt8*)Out+Read,0,sizeof(uint16_t)); } else { Out[0]=0; } } else { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } } }
// char to char conversion void CharConvSS(charconv* Conv, char* Out, size_t OutLen, const char* In) { if (OutLen>0) { charconv_osx *CC = (charconv_osx *)Conv; if (CC) { CFStringRef TmpIn = CFStringCreateWithCString(NULL, In, CC->EncFrom); CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, CC->EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); Out[Read]=0; } else { size_t n = min(In?strlen(In):0,OutLen-1); memcpy(Out,In,n*sizeof(char)); Out[n] = 0; } } }
// utf16_t to char conversion void CharConvSU(charconv* Conv, char* Out, size_t OutLen, const utf16_t* In) { if (OutLen>0) { // assume wchar_t is 16 bits even if it's not true CFStringEncoding EncFrom,EncTo; if (Conv) { EncFrom = ((charconv_osx *)Conv)->EncFrom; EncTo = ((charconv_osx *)Conv)->EncTo; } else { EncFrom = kCFStringEncodingUTF16; EncTo = kCFStringEncodingUTF8; } CFStringRef TmpIn = CFStringCreateWithBytes(NULL, (const UInt8*)In, (utf16len(In)+1)*sizeof(utf16_t), EncFrom, false); CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); Out[Read]=0; } }
void stringGettingContentsAsCStringExample(void) { CFStringRef str; CFDataRef data; CFRange rangeToProcess; const char *bytes; show(CFSTR("------------------C String Manipulations---------------")); // Create some test CFString // Note that in general the string might contain Unicode characters which cannot // be converted to a 8-bit character encoding str = CFStringCreateWithCString(NULL, "Hello World", kCFStringEncodingASCII); show(CFSTR("Original String : %@"), str); // First, the fast but unpredictable way to get at the C String contents... // This is O(1), meaning it takes constant time. // This might return NULL! bytes = CFStringGetCStringPtr(str, kCFStringEncodingASCII); // If that fails, you can try to get the contents by copying it out if (bytes == NULL) { char localBuffer[10]; Boolean success; // This might also fail, either if you provide a buffer that is too small, // or the string cannot be converted into the specified encoding success = CFStringGetCString(str, localBuffer, 10, kCFStringEncodingASCII); } else show(CFSTR("From CStringPtr : %@"), bytes); // A pretty simple solution is to use a CFData; this frees you from guessing at the buffer size // But it does allocate a CFData... data = CFStringCreateExternalRepresentation(NULL, str, kCFStringEncodingASCII, 0); if (data) { show(CFSTR("External Rep: %@"), data); bytes = (const char *)CFDataGetBytePtr(data); } // More complicated but efficient solution is to use a fixed size buffer, and put a loop in rangeToProcess = CFRangeMake(0, CFStringGetLength(str)); while (rangeToProcess.length > 0) { UInt8 localBuffer[100]; CFIndex usedBufferLength; CFIndex numChars = CFStringGetBytes(str, rangeToProcess, kCFStringEncodingASCII, 0, FALSE, (UInt8 *)localBuffer, 100, &usedBufferLength); if (numChars == 0) break; // Means we failed to convert anything... // Otherwise we converted some stuff; process localBuffer containing usedBufferLength bytes // Note that the bytes in localBuffer are not NULL terminated // Update the remaining range to continue looping rangeToProcess.location += numChars; rangeToProcess.length -= numChars; } }
/* Given a CFStringRef, copy its contents into a Ruby string */ static VALUE convertStringRef(CFStringRef str) { CFRange range; CFStringEncoding encoding; CFIndex byteCount; UInt8 *buffer; VALUE retval; range = CFRangeMake(0, CFStringGetLength(str)); encoding = kCFStringEncodingUTF8; CFStringGetBytes(str, range, encoding, 0, false, NULL, 0, &byteCount); buffer = ALLOC_N(UInt8, byteCount); CFStringGetBytes(str, range, encoding, 0, false, buffer, byteCount, NULL); retval = rb_str_new((char *)buffer, (long)byteCount); free(buffer); return retval; }
Boolean diff_regExMatch(CFStringRef text, const regex_t *re) { //TODO(jan): Using regex.h is far from optimal. Find an alternative. Boolean isMatch; const char *bytes; char *localBuffer = NULL; char *textCString = NULL; // We are only interested in line endings anyway so ASCII is fine. CFStringEncoding encoding = kCFStringEncodingASCII; bytes = CFStringGetCStringPtr(text, encoding); if (bytes == NULL) { Boolean success; CFIndex length; CFIndex usedBufferLength; CFIndex textLength = CFStringGetLength(text); CFRange rangeToProcess = CFRangeMake(0, textLength); success = (CFStringGetBytes(text, rangeToProcess, encoding, '?', false, NULL, LONG_MAX, &usedBufferLength) > 0); if (success) { length = usedBufferLength + 1; localBuffer = calloc(length, sizeof(char)); success = (CFStringGetBytes(text, rangeToProcess, encoding, '?', false, (UInt8 *)localBuffer, length, NULL) > 0); if (success) { textCString = localBuffer; } } } else { textCString = (char *)bytes; } if (textCString != NULL) { isMatch = (regexec(re, textCString, 0, NULL, 0) == 0); } else { isMatch = false; //check(0); } if (localBuffer != NULL) { free(localBuffer); } return isMatch; }
wxString wxCFStringRef::AsString(wxFontEncoding WXUNUSED_IN_UNICODE(encoding)) { if ( !get() ) return wxEmptyString ; Size cflen = CFStringGetLength( get() ) ; char* buf = NULL ; CFStringEncoding cfencoding = 0; wxString result; #if wxUSE_UNICODE #if wxUSE_UNICODE_WCHAR cfencoding = kCFStringEncodingUTF32Native; #elif wxUSE_UNICODE_UTF8 cfencoding = kCFStringEncodingUTF8; #else #error "unsupported unicode representation" #endif #else cfencoding = wxMacGetSystemEncFromFontEnc( encoding ); #endif CFIndex cStrLen ; CFStringGetBytes( get() , CFRangeMake(0, cflen) , cfencoding , '?' , false , NULL , 0 , &cStrLen ) ; buf = new char[ cStrLen ] ; CFStringGetBytes( get() , CFRangeMake(0, cflen) , cfencoding, '?' , false , (unsigned char*) buf , cStrLen , &cStrLen) ; #if wxUSE_UNICODE #if wxUSE_UNICODE_WCHAR result = wxString( (const wchar_t*) buf , cStrLen/4); #elif wxUSE_UNICODE_UTF8 result = wxString::FromUTF8( buf, cStrLen ); #else #error "unsupported unicode representation" #endif #else result = wxString(buf, cStrLen) ; #endif delete[] buf ; wxMacConvertNewlines10To13( &result); return result ; }
void encode(ArgumentEncoder* encoder, CFStringRef string) { CFIndex length = CFStringGetLength(string); CFStringEncoding encoding = CFStringGetFastestEncoding(string); CFRange range = CFRangeMake(0, length); CFIndex bufferLength = 0; CFIndex numConvertedBytes = CFStringGetBytes(string, range, encoding, 0, false, 0, 0, &bufferLength); ASSERT(numConvertedBytes == length); Vector<UInt8, 128> buffer(bufferLength); numConvertedBytes = CFStringGetBytes(string, range, encoding, 0, false, buffer.data(), buffer.size(), &bufferLength); ASSERT(numConvertedBytes == length); encoder->encodeEnum(encoding); encoder->encodeVariableLengthByteArray(buffer); }
size_t der_sizeof_string(CFStringRef str, CFErrorRef *error) { const CFIndex str_length = CFStringGetLength(str); const CFIndex maximum = CFStringGetMaximumSizeForEncoding(str_length, kCFStringEncodingUTF8); CFIndex encodedLen = 0; CFIndex converted = CFStringGetBytes(str, CFRangeMake(0, str_length), kCFStringEncodingUTF8, 0, false, NULL, maximum, &encodedLen); return ccder_sizeof(CCDER_UTF8_STRING, (converted == str_length) ? encodedLen : 0); }