cstr.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. *******************************************************************************
  5. * Copyright (C) 2015-2016, International Business Machines
  6. * Corporation and others. All Rights Reserved.
  7. *******************************************************************************
  8. * file name: charstr.cpp
  9. */
  10. #include "unicode/utypes.h"
  11. #include "unicode/putil.h"
  12. #include "unicode/unistr.h"
  13. #include "cstr.h"
  14. #include "charstr.h"
  15. #include "uinvchar.h"
  16. U_NAMESPACE_BEGIN
  17. CStr::CStr(const UnicodeString &in) {
  18. UErrorCode status = U_ZERO_ERROR;
  19. #if !UCONFIG_NO_CONVERSION || U_CHARSET_IS_UTF8
  20. int32_t length = in.extract(0, in.length(), static_cast<char *>(nullptr), static_cast<uint32_t>(0));
  21. int32_t resultCapacity = 0;
  22. char *buf = s.getAppendBuffer(length, length, resultCapacity, status);
  23. if (U_SUCCESS(status)) {
  24. in.extract(0, in.length(), buf, resultCapacity);
  25. s.append(buf, length, status);
  26. }
  27. #else
  28. // No conversion available. Convert any invariant characters; substitute '?' for the rest.
  29. // Note: can't just call u_UCharsToChars() or CharString.appendInvariantChars() on the
  30. // whole string because they require that the entire input be invariant.
  31. char buf[2];
  32. for (int i=0; i<in.length(); i = in.moveIndex32(i, 1)) {
  33. if (uprv_isInvariantUString(in.getBuffer()+i, 1)) {
  34. u_UCharsToChars(in.getBuffer()+i, buf, 1);
  35. } else {
  36. buf[0] = '?';
  37. }
  38. s.append(buf, 1, status);
  39. }
  40. #endif
  41. }
  42. CStr::~CStr() {
  43. }
  44. const char * CStr::operator ()() const {
  45. return s.data();
  46. }
  47. U_NAMESPACE_END