net_string_util_icu.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/base/net_string_util.h"
  5. #include "base/i18n/case_conversion.h"
  6. #include "base/i18n/i18n_constants.h"
  7. #include "base/i18n/icu_string_conversions.h"
  8. #include "base/strings/string_piece.h"
  9. #include "base/strings/string_util.h"
  10. #include "third_party/icu/source/common/unicode/ucnv.h"
  11. namespace net {
  12. const char* const kCharsetLatin1 = base::kCodepageLatin1;
  13. bool ConvertToUtf8(base::StringPiece text,
  14. const char* charset,
  15. std::string* output) {
  16. output->clear();
  17. UErrorCode err = U_ZERO_ERROR;
  18. UConverter* converter(ucnv_open(charset, &err));
  19. if (U_FAILURE(err))
  20. return false;
  21. // A single byte in a legacy encoding can be expanded to 3 bytes in UTF-8.
  22. // A 'two-byte character' in a legacy encoding can be expanded to 4 bytes
  23. // in UTF-8. Therefore, the expansion ratio is 3 at most. Add one for a
  24. // trailing '\0'.
  25. size_t output_length = text.length() * 3 + 1;
  26. char* buf = base::WriteInto(output, output_length);
  27. output_length = ucnv_toAlgorithmic(UCNV_UTF8, converter, buf, output_length,
  28. text.data(), text.length(), &err);
  29. ucnv_close(converter);
  30. if (U_FAILURE(err)) {
  31. output->clear();
  32. return false;
  33. }
  34. output->resize(output_length);
  35. return true;
  36. }
  37. bool ConvertToUtf8AndNormalize(base::StringPiece text,
  38. const char* charset,
  39. std::string* output) {
  40. return base::ConvertToUtf8AndNormalize(text, charset, output);
  41. }
  42. bool ConvertToUTF16(base::StringPiece text,
  43. const char* charset,
  44. std::u16string* output) {
  45. return base::CodepageToUTF16(text, charset,
  46. base::OnStringConversionError::FAIL, output);
  47. }
  48. bool ConvertToUTF16WithSubstitutions(base::StringPiece text,
  49. const char* charset,
  50. std::u16string* output) {
  51. return base::CodepageToUTF16(
  52. text, charset, base::OnStringConversionError::SUBSTITUTE, output);
  53. }
  54. bool ToUpper(base::StringPiece16 str, std::u16string* output) {
  55. *output = base::i18n::ToUpper(str);
  56. return true;
  57. }
  58. } // namespace net