(*outCString)[dstLength] = '\0';
if (unicharLength < originalLength) { PR_Free(*outCString); unicharLength = originalLength; dstLength = estimatedLength * 4; *outCString = (char *) PR_Malloc(dstLength + 1); if (*outCString != nsnull) { res = encoder->Convert(unichars, &unicharLength, *outCString, &dstLength); NS_ASSERTION(unicharLength == originalLength, "unicharLength != originalLength"); } } if (*outCString != nsnull) { (*outCString)[dstLength] = '\0'; }
nsresult ConvertFromUnicode(const nsString aCharset,                             const nsString inString,                            char** outCString){  nsICharsetConverterManager * ccm = nsnull;  nsresult res;  res = nsServiceManager::GetService(kCharsetConverterManagerCID,                                      kICharsetConverterManagerIID,                                      (nsISupports**)&ccm);  if(NS_SUCCEEDED(res) && (nsnull != ccm)) {    nsIUnicodeEncoder* encoder = nsnull;    nsString convCharset;    // map to converter charset    if (aCharset.EqualsIgnoreCase("us-ascii")) {      convCharset.SetString("iso-8859-1");    }    else {      convCharset = aCharset;     }    // get an unicode converter    res = ccm->GetUnicodeEncoder(&convCharset, &encoder);    if(NS_SUCCEEDED(res) && (nsnull != encoder)) {      const PRUnichar *unichars = inString.GetUnicode();      PRInt32 unicharLength = inString.Length();      PRInt32 dstLength;      res = encoder->GetMaxLength(unichars, unicharLength, &dstLength);      // allocale an output buffer      *outCString = (char *) PR_Malloc(dstLength + 1);      if (*outCString != nsnull) {        // convert from unicode        res = encoder->Convert(unichars, &unicharLength, *outCString, &dstLength);        (*outCString)[dstLength] = '\0';      }      else {        res = NS_ERROR_OUT_OF_MEMORY;      }      NS_IF_RELEASE(encoder);    }        nsServiceManager::ReleaseService(kCharsetConverterManagerCID, ccm);  }  return res;}