ucnv.cpp 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. *
  6. * Copyright (C) 1998-2016, International Business Machines
  7. * Corporation and others. All Rights Reserved.
  8. *
  9. ******************************************************************************
  10. *
  11. * ucnv.c:
  12. * Implements APIs for the ICU's codeset conversion library;
  13. * mostly calls through internal functions;
  14. * created by Bertrand A. Damiba
  15. *
  16. * Modification History:
  17. *
  18. * Date Name Description
  19. * 04/04/99 helena Fixed internal header inclusion.
  20. * 05/09/00 helena Added implementation to handle fallback mappings.
  21. * 06/20/2000 helena OS/400 port changes; mostly typecast.
  22. */
  23. #include "unicode/utypes.h"
  24. #if !UCONFIG_NO_CONVERSION
  25. #include <memory>
  26. #include "unicode/ustring.h"
  27. #include "unicode/ucnv.h"
  28. #include "unicode/ucnv_err.h"
  29. #include "unicode/uset.h"
  30. #include "unicode/utf.h"
  31. #include "unicode/utf16.h"
  32. #include "putilimp.h"
  33. #include "cmemory.h"
  34. #include "cstring.h"
  35. #include "uassert.h"
  36. #include "utracimp.h"
  37. #include "ustr_imp.h"
  38. #include "ucnv_imp.h"
  39. #include "ucnv_cnv.h"
  40. #include "ucnv_bld.h"
  41. /* size of intermediate and preflighting buffers in ucnv_convert() */
  42. #define CHUNK_SIZE 1024
  43. typedef struct UAmbiguousConverter {
  44. const char *name;
  45. const char16_t variant5c;
  46. } UAmbiguousConverter;
  47. static const UAmbiguousConverter ambiguousConverters[]={
  48. { "ibm-897_P100-1995", 0xa5 },
  49. { "ibm-942_P120-1999", 0xa5 },
  50. { "ibm-943_P130-1999", 0xa5 },
  51. { "ibm-946_P100-1995", 0xa5 },
  52. { "ibm-33722_P120-1999", 0xa5 },
  53. { "ibm-1041_P100-1995", 0xa5 },
  54. /*{ "ibm-54191_P100-2006", 0xa5 },*/
  55. /*{ "ibm-62383_P100-2007", 0xa5 },*/
  56. /*{ "ibm-891_P100-1995", 0x20a9 },*/
  57. { "ibm-944_P100-1995", 0x20a9 },
  58. { "ibm-949_P110-1999", 0x20a9 },
  59. { "ibm-1363_P110-1997", 0x20a9 },
  60. { "ISO_2022,locale=ko,version=0", 0x20a9 },
  61. { "ibm-1088_P100-1995", 0x20a9 }
  62. };
  63. /*Calls through createConverter */
  64. U_CAPI UConverter* U_EXPORT2
  65. ucnv_open (const char *name,
  66. UErrorCode * err)
  67. {
  68. UConverter *r;
  69. if (err == nullptr || U_FAILURE (*err)) {
  70. return nullptr;
  71. }
  72. r = ucnv_createConverter(nullptr, name, err);
  73. return r;
  74. }
  75. U_CAPI UConverter* U_EXPORT2
  76. ucnv_openPackage (const char *packageName, const char *converterName, UErrorCode * err)
  77. {
  78. return ucnv_createConverterFromPackage(packageName, converterName, err);
  79. }
  80. /*Extracts the char16_t* to a char* and calls through createConverter */
  81. U_CAPI UConverter* U_EXPORT2
  82. ucnv_openU (const char16_t * name,
  83. UErrorCode * err)
  84. {
  85. char asciiName[UCNV_MAX_CONVERTER_NAME_LENGTH];
  86. if (err == nullptr || U_FAILURE(*err))
  87. return nullptr;
  88. if (name == nullptr)
  89. return ucnv_open (nullptr, err);
  90. if (u_strlen(name) >= UCNV_MAX_CONVERTER_NAME_LENGTH)
  91. {
  92. *err = U_ILLEGAL_ARGUMENT_ERROR;
  93. return nullptr;
  94. }
  95. return ucnv_open(u_austrcpy(asciiName, name), err);
  96. }
  97. /* Copy the string that is represented by the UConverterPlatform enum
  98. * @param platformString An output buffer
  99. * @param platform An enum representing a platform
  100. * @return the length of the copied string.
  101. */
  102. static int32_t
  103. ucnv_copyPlatformString(char *platformString, UConverterPlatform pltfrm)
  104. {
  105. switch (pltfrm)
  106. {
  107. case UCNV_IBM:
  108. uprv_strcpy(platformString, "ibm-");
  109. return 4;
  110. case UCNV_UNKNOWN:
  111. break;
  112. }
  113. /* default to empty string */
  114. *platformString = 0;
  115. return 0;
  116. }
  117. /*Assumes a $platform-#codepage.$CONVERTER_FILE_EXTENSION scheme and calls
  118. *through createConverter*/
  119. U_CAPI UConverter* U_EXPORT2
  120. ucnv_openCCSID (int32_t codepage,
  121. UConverterPlatform platform,
  122. UErrorCode * err)
  123. {
  124. char myName[UCNV_MAX_CONVERTER_NAME_LENGTH];
  125. int32_t myNameLen;
  126. if (err == nullptr || U_FAILURE (*err))
  127. return nullptr;
  128. /* ucnv_copyPlatformString could return "ibm-" or "cp" */
  129. myNameLen = ucnv_copyPlatformString(myName, platform);
  130. T_CString_integerToString(myName + myNameLen, codepage, 10);
  131. return ucnv_createConverter(nullptr, myName, err);
  132. }
  133. /* Creating a temporary stack-based object that can be used in one thread,
  134. and created from a converter that is shared across threads.
  135. */
  136. U_CAPI UConverter* U_EXPORT2
  137. ucnv_safeClone(const UConverter* cnv, void *stackBuffer, int32_t *pBufferSize, UErrorCode *status)
  138. {
  139. UConverter *localConverter, *allocatedConverter;
  140. int32_t stackBufferSize;
  141. int32_t bufferSizeNeeded;
  142. UErrorCode cbErr;
  143. UConverterToUnicodeArgs toUArgs = {
  144. sizeof(UConverterToUnicodeArgs),
  145. true,
  146. nullptr,
  147. nullptr,
  148. nullptr,
  149. nullptr,
  150. nullptr,
  151. nullptr
  152. };
  153. UConverterFromUnicodeArgs fromUArgs = {
  154. sizeof(UConverterFromUnicodeArgs),
  155. true,
  156. nullptr,
  157. nullptr,
  158. nullptr,
  159. nullptr,
  160. nullptr,
  161. nullptr
  162. };
  163. UTRACE_ENTRY_OC(UTRACE_UCNV_CLONE);
  164. if (status == nullptr || U_FAILURE(*status)){
  165. UTRACE_EXIT_STATUS(status? *status: U_ILLEGAL_ARGUMENT_ERROR);
  166. return nullptr;
  167. }
  168. if (cnv == nullptr) {
  169. *status = U_ILLEGAL_ARGUMENT_ERROR;
  170. UTRACE_EXIT_STATUS(*status);
  171. return nullptr;
  172. }
  173. UTRACE_DATA3(UTRACE_OPEN_CLOSE, "clone converter %s at %p into stackBuffer %p",
  174. ucnv_getName(cnv, status), cnv, stackBuffer);
  175. if (cnv->sharedData->impl->safeClone != nullptr) {
  176. /* call the custom safeClone function for sizing */
  177. bufferSizeNeeded = 0;
  178. cnv->sharedData->impl->safeClone(cnv, nullptr, &bufferSizeNeeded, status);
  179. if (U_FAILURE(*status)) {
  180. UTRACE_EXIT_STATUS(*status);
  181. return nullptr;
  182. }
  183. }
  184. else
  185. {
  186. /* inherent sizing */
  187. bufferSizeNeeded = sizeof(UConverter);
  188. }
  189. if (pBufferSize == nullptr) {
  190. stackBufferSize = 1;
  191. pBufferSize = &stackBufferSize;
  192. } else {
  193. stackBufferSize = *pBufferSize;
  194. if (stackBufferSize <= 0){ /* 'preflighting' request - set needed size into *pBufferSize */
  195. *pBufferSize = bufferSizeNeeded;
  196. UTRACE_EXIT_VALUE(bufferSizeNeeded);
  197. return nullptr;
  198. }
  199. }
  200. /* Adjust (if necessary) the stackBuffer pointer to be aligned correctly for a UConverter.
  201. * TODO(Jira ICU-20736) Redo this using std::align() once g++4.9 compatibility is no longer needed.
  202. */
  203. if (stackBuffer) {
  204. uintptr_t p = reinterpret_cast<uintptr_t>(stackBuffer);
  205. uintptr_t aligned_p = (p + alignof(UConverter) - 1) & ~(alignof(UConverter) - 1);
  206. ptrdiff_t pointerAdjustment = aligned_p - p;
  207. if (bufferSizeNeeded + pointerAdjustment <= stackBufferSize) {
  208. stackBuffer = reinterpret_cast<void *>(aligned_p);
  209. stackBufferSize -= static_cast<int32_t>(pointerAdjustment);
  210. } else {
  211. /* prevent using the stack buffer but keep the size > 0 so that we do not just preflight */
  212. stackBufferSize = 1;
  213. }
  214. }
  215. /* Now, see if we must allocate any memory */
  216. if (stackBufferSize < bufferSizeNeeded || stackBuffer == nullptr)
  217. {
  218. /* allocate one here...*/
  219. localConverter = allocatedConverter = (UConverter *) uprv_malloc (bufferSizeNeeded);
  220. if(localConverter == nullptr) {
  221. *status = U_MEMORY_ALLOCATION_ERROR;
  222. UTRACE_EXIT_STATUS(*status);
  223. return nullptr;
  224. }
  225. // If pBufferSize was nullptr as the input, pBufferSize is set to &stackBufferSize in this function.
  226. if (pBufferSize != &stackBufferSize) {
  227. *status = U_SAFECLONE_ALLOCATED_WARNING;
  228. }
  229. /* record the fact that memory was allocated */
  230. *pBufferSize = bufferSizeNeeded;
  231. } else {
  232. /* just use the stack buffer */
  233. localConverter = (UConverter*) stackBuffer;
  234. allocatedConverter = nullptr;
  235. }
  236. uprv_memset(localConverter, 0, bufferSizeNeeded);
  237. /* Copy initial state */
  238. uprv_memcpy(localConverter, cnv, sizeof(UConverter));
  239. localConverter->isCopyLocal = localConverter->isExtraLocal = false;
  240. /* copy the substitution string */
  241. if (cnv->subChars == (uint8_t *)cnv->subUChars) {
  242. localConverter->subChars = (uint8_t *)localConverter->subUChars;
  243. } else {
  244. localConverter->subChars = (uint8_t *)uprv_malloc(UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR);
  245. if (localConverter->subChars == nullptr) {
  246. uprv_free(allocatedConverter);
  247. UTRACE_EXIT_STATUS(*status);
  248. return nullptr;
  249. }
  250. uprv_memcpy(localConverter->subChars, cnv->subChars, UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR);
  251. }
  252. /* now either call the safeclone fcn or not */
  253. if (cnv->sharedData->impl->safeClone != nullptr) {
  254. /* call the custom safeClone function */
  255. localConverter = cnv->sharedData->impl->safeClone(cnv, localConverter, pBufferSize, status);
  256. }
  257. if(localConverter==nullptr || U_FAILURE(*status)) {
  258. if (allocatedConverter != nullptr && allocatedConverter->subChars != (uint8_t *)allocatedConverter->subUChars) {
  259. uprv_free(allocatedConverter->subChars);
  260. }
  261. uprv_free(allocatedConverter);
  262. UTRACE_EXIT_STATUS(*status);
  263. return nullptr;
  264. }
  265. /* increment refcount of shared data if needed */
  266. if (cnv->sharedData->isReferenceCounted) {
  267. ucnv_incrementRefCount(cnv->sharedData);
  268. }
  269. if(localConverter == (UConverter*)stackBuffer) {
  270. /* we're using user provided data - set to not destroy */
  271. localConverter->isCopyLocal = true;
  272. }
  273. /* allow callback functions to handle any memory allocation */
  274. toUArgs.converter = fromUArgs.converter = localConverter;
  275. cbErr = U_ZERO_ERROR;
  276. cnv->fromCharErrorBehaviour(cnv->toUContext, &toUArgs, nullptr, 0, UCNV_CLONE, &cbErr);
  277. cbErr = U_ZERO_ERROR;
  278. cnv->fromUCharErrorBehaviour(cnv->fromUContext, &fromUArgs, nullptr, 0, 0, UCNV_CLONE, &cbErr);
  279. UTRACE_EXIT_PTR_STATUS(localConverter, *status);
  280. return localConverter;
  281. }
  282. U_CAPI UConverter* U_EXPORT2
  283. ucnv_clone(const UConverter* cnv, UErrorCode *status)
  284. {
  285. return ucnv_safeClone(cnv, nullptr, nullptr, status);
  286. }
  287. /*Decreases the reference counter in the shared immutable section of the object
  288. *and frees the mutable part*/
  289. U_CAPI void U_EXPORT2
  290. ucnv_close (UConverter * converter)
  291. {
  292. UErrorCode errorCode = U_ZERO_ERROR;
  293. UTRACE_ENTRY_OC(UTRACE_UCNV_CLOSE);
  294. if (converter == nullptr)
  295. {
  296. UTRACE_EXIT();
  297. return;
  298. }
  299. UTRACE_DATA3(UTRACE_OPEN_CLOSE, "close converter %s at %p, isCopyLocal=%b",
  300. ucnv_getName(converter, &errorCode), converter, converter->isCopyLocal);
  301. /* In order to speed up the close, only call the callbacks when they have been changed.
  302. This performance check will only work when the callbacks are set within a shared library
  303. or from user code that statically links this code. */
  304. /* first, notify the callback functions that the converter is closed */
  305. if (converter->fromCharErrorBehaviour != UCNV_TO_U_DEFAULT_CALLBACK) {
  306. UConverterToUnicodeArgs toUArgs = {
  307. sizeof(UConverterToUnicodeArgs),
  308. true,
  309. nullptr,
  310. nullptr,
  311. nullptr,
  312. nullptr,
  313. nullptr,
  314. nullptr
  315. };
  316. toUArgs.converter = converter;
  317. errorCode = U_ZERO_ERROR;
  318. converter->fromCharErrorBehaviour(converter->toUContext, &toUArgs, nullptr, 0, UCNV_CLOSE, &errorCode);
  319. }
  320. if (converter->fromUCharErrorBehaviour != UCNV_FROM_U_DEFAULT_CALLBACK) {
  321. UConverterFromUnicodeArgs fromUArgs = {
  322. sizeof(UConverterFromUnicodeArgs),
  323. true,
  324. nullptr,
  325. nullptr,
  326. nullptr,
  327. nullptr,
  328. nullptr,
  329. nullptr
  330. };
  331. fromUArgs.converter = converter;
  332. errorCode = U_ZERO_ERROR;
  333. converter->fromUCharErrorBehaviour(converter->fromUContext, &fromUArgs, nullptr, 0, 0, UCNV_CLOSE, &errorCode);
  334. }
  335. if (converter->sharedData->impl->close != nullptr) {
  336. converter->sharedData->impl->close(converter);
  337. }
  338. if (converter->subChars != (uint8_t *)converter->subUChars) {
  339. uprv_free(converter->subChars);
  340. }
  341. if (converter->sharedData->isReferenceCounted) {
  342. ucnv_unloadSharedDataIfReady(converter->sharedData);
  343. }
  344. if(!converter->isCopyLocal){
  345. uprv_free(converter);
  346. }
  347. UTRACE_EXIT();
  348. }
  349. /*returns a single Name from the list, will return nullptr if out of bounds
  350. */
  351. U_CAPI const char* U_EXPORT2
  352. ucnv_getAvailableName (int32_t n)
  353. {
  354. if (0 <= n && n <= 0xffff) {
  355. UErrorCode err = U_ZERO_ERROR;
  356. const char *name = ucnv_bld_getAvailableConverter((uint16_t)n, &err);
  357. if (U_SUCCESS(err)) {
  358. return name;
  359. }
  360. }
  361. return nullptr;
  362. }
  363. U_CAPI int32_t U_EXPORT2
  364. ucnv_countAvailable ()
  365. {
  366. UErrorCode err = U_ZERO_ERROR;
  367. return ucnv_bld_countAvailableConverters(&err);
  368. }
  369. U_CAPI void U_EXPORT2
  370. ucnv_getSubstChars (const UConverter * converter,
  371. char *mySubChar,
  372. int8_t * len,
  373. UErrorCode * err)
  374. {
  375. if (U_FAILURE (*err))
  376. return;
  377. if (converter->subCharLen <= 0) {
  378. /* Unicode string or empty string from ucnv_setSubstString(). */
  379. *len = 0;
  380. return;
  381. }
  382. if (*len < converter->subCharLen) /*not enough space in subChars */
  383. {
  384. *err = U_INDEX_OUTOFBOUNDS_ERROR;
  385. return;
  386. }
  387. uprv_memcpy (mySubChar, converter->subChars, converter->subCharLen); /*fills in the subchars */
  388. *len = converter->subCharLen; /*store # of bytes copied to buffer */
  389. }
  390. U_CAPI void U_EXPORT2
  391. ucnv_setSubstChars (UConverter * converter,
  392. const char *mySubChar,
  393. int8_t len,
  394. UErrorCode * err)
  395. {
  396. if (U_FAILURE (*err))
  397. return;
  398. /*Makes sure that the subChar is within the codepages char length boundaries */
  399. if ((len > converter->sharedData->staticData->maxBytesPerChar)
  400. || (len < converter->sharedData->staticData->minBytesPerChar))
  401. {
  402. *err = U_ILLEGAL_ARGUMENT_ERROR;
  403. return;
  404. }
  405. uprv_memcpy (converter->subChars, mySubChar, len); /*copies the subchars */
  406. converter->subCharLen = len; /*sets the new len */
  407. /*
  408. * There is currently (2001Feb) no separate API to set/get subChar1.
  409. * In order to always have subChar written after it is explicitly set,
  410. * we set subChar1 to 0.
  411. */
  412. converter->subChar1 = 0;
  413. return;
  414. }
  415. U_CAPI void U_EXPORT2
  416. ucnv_setSubstString(UConverter *cnv,
  417. const char16_t *s,
  418. int32_t length,
  419. UErrorCode *err) {
  420. alignas(UConverter) char cloneBuffer[U_CNV_SAFECLONE_BUFFERSIZE];
  421. char chars[UCNV_ERROR_BUFFER_LENGTH];
  422. UConverter *clone;
  423. uint8_t *subChars;
  424. int32_t cloneSize, length8;
  425. /* Let the following functions check all arguments. */
  426. cloneSize = sizeof(cloneBuffer);
  427. clone = ucnv_safeClone(cnv, cloneBuffer, &cloneSize, err);
  428. ucnv_setFromUCallBack(clone, UCNV_FROM_U_CALLBACK_STOP, nullptr, nullptr, nullptr, err);
  429. length8 = ucnv_fromUChars(clone, chars, (int32_t)sizeof(chars), s, length, err);
  430. ucnv_close(clone);
  431. if (U_FAILURE(*err)) {
  432. return;
  433. }
  434. if (cnv->sharedData->impl->writeSub == nullptr
  435. #if !UCONFIG_NO_LEGACY_CONVERSION
  436. || (cnv->sharedData->staticData->conversionType == UCNV_MBCS &&
  437. ucnv_MBCSGetType(cnv) != UCNV_EBCDIC_STATEFUL)
  438. #endif
  439. ) {
  440. /* The converter is not stateful. Store the charset bytes as a fixed string. */
  441. subChars = (uint8_t *)chars;
  442. } else {
  443. /*
  444. * The converter has a non-default writeSub() function, indicating
  445. * that it is stateful.
  446. * Store the Unicode string for on-the-fly conversion for correct
  447. * state handling.
  448. */
  449. if (length > UCNV_ERROR_BUFFER_LENGTH) {
  450. /*
  451. * Should not occur. The converter should output at least one byte
  452. * per char16_t, which means that ucnv_fromUChars() should catch all
  453. * overflows.
  454. */
  455. *err = U_BUFFER_OVERFLOW_ERROR;
  456. return;
  457. }
  458. subChars = (uint8_t *)s;
  459. if (length < 0) {
  460. length = u_strlen(s);
  461. }
  462. length8 = length * U_SIZEOF_UCHAR;
  463. }
  464. /*
  465. * For storing the substitution string, select either the small buffer inside
  466. * UConverter or allocate a subChars buffer.
  467. */
  468. if (length8 > UCNV_MAX_SUBCHAR_LEN) {
  469. /* Use a separate buffer for the string. Outside UConverter to not make it too large. */
  470. if (cnv->subChars == (uint8_t *)cnv->subUChars) {
  471. /* Allocate a new buffer for the string. */
  472. cnv->subChars = (uint8_t *)uprv_malloc(UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR);
  473. if (cnv->subChars == nullptr) {
  474. cnv->subChars = (uint8_t *)cnv->subUChars;
  475. *err = U_MEMORY_ALLOCATION_ERROR;
  476. return;
  477. }
  478. uprv_memset(cnv->subChars, 0, UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR);
  479. }
  480. }
  481. /* Copy the substitution string into the UConverter or its subChars buffer. */
  482. if (length8 == 0) {
  483. cnv->subCharLen = 0;
  484. } else {
  485. uprv_memcpy(cnv->subChars, subChars, length8);
  486. if (subChars == (uint8_t *)chars) {
  487. cnv->subCharLen = (int8_t)length8;
  488. } else /* subChars == s */ {
  489. cnv->subCharLen = (int8_t)-length;
  490. }
  491. }
  492. /* See comment in ucnv_setSubstChars(). */
  493. cnv->subChar1 = 0;
  494. }
  495. /*resets the internal states of a converter
  496. *goal : have the same behaviour than a freshly created converter
  497. */
  498. static void _reset(UConverter *converter, UConverterResetChoice choice,
  499. UBool callCallback) {
  500. if(converter == nullptr) {
  501. return;
  502. }
  503. if(callCallback) {
  504. /* first, notify the callback functions that the converter is reset */
  505. UErrorCode errorCode;
  506. if(choice<=UCNV_RESET_TO_UNICODE && converter->fromCharErrorBehaviour != UCNV_TO_U_DEFAULT_CALLBACK) {
  507. UConverterToUnicodeArgs toUArgs = {
  508. sizeof(UConverterToUnicodeArgs),
  509. true,
  510. nullptr,
  511. nullptr,
  512. nullptr,
  513. nullptr,
  514. nullptr,
  515. nullptr
  516. };
  517. toUArgs.converter = converter;
  518. errorCode = U_ZERO_ERROR;
  519. converter->fromCharErrorBehaviour(converter->toUContext, &toUArgs, nullptr, 0, UCNV_RESET, &errorCode);
  520. }
  521. if(choice!=UCNV_RESET_TO_UNICODE && converter->fromUCharErrorBehaviour != UCNV_FROM_U_DEFAULT_CALLBACK) {
  522. UConverterFromUnicodeArgs fromUArgs = {
  523. sizeof(UConverterFromUnicodeArgs),
  524. true,
  525. nullptr,
  526. nullptr,
  527. nullptr,
  528. nullptr,
  529. nullptr,
  530. nullptr
  531. };
  532. fromUArgs.converter = converter;
  533. errorCode = U_ZERO_ERROR;
  534. converter->fromUCharErrorBehaviour(converter->fromUContext, &fromUArgs, nullptr, 0, 0, UCNV_RESET, &errorCode);
  535. }
  536. }
  537. /* now reset the converter itself */
  538. if(choice<=UCNV_RESET_TO_UNICODE) {
  539. converter->toUnicodeStatus = converter->sharedData->toUnicodeStatus;
  540. converter->mode = 0;
  541. converter->toULength = 0;
  542. converter->invalidCharLength = converter->UCharErrorBufferLength = 0;
  543. converter->preToULength = 0;
  544. }
  545. if(choice!=UCNV_RESET_TO_UNICODE) {
  546. converter->fromUnicodeStatus = 0;
  547. converter->fromUChar32 = 0;
  548. converter->invalidUCharLength = converter->charErrorBufferLength = 0;
  549. converter->preFromUFirstCP = U_SENTINEL;
  550. converter->preFromULength = 0;
  551. }
  552. if (converter->sharedData->impl->reset != nullptr) {
  553. /* call the custom reset function */
  554. converter->sharedData->impl->reset(converter, choice);
  555. }
  556. }
  557. U_CAPI void U_EXPORT2
  558. ucnv_reset(UConverter *converter)
  559. {
  560. _reset(converter, UCNV_RESET_BOTH, true);
  561. }
  562. U_CAPI void U_EXPORT2
  563. ucnv_resetToUnicode(UConverter *converter)
  564. {
  565. _reset(converter, UCNV_RESET_TO_UNICODE, true);
  566. }
  567. U_CAPI void U_EXPORT2
  568. ucnv_resetFromUnicode(UConverter *converter)
  569. {
  570. _reset(converter, UCNV_RESET_FROM_UNICODE, true);
  571. }
  572. U_CAPI int8_t U_EXPORT2
  573. ucnv_getMaxCharSize (const UConverter * converter)
  574. {
  575. return converter->maxBytesPerUChar;
  576. }
  577. U_CAPI int8_t U_EXPORT2
  578. ucnv_getMinCharSize (const UConverter * converter)
  579. {
  580. return converter->sharedData->staticData->minBytesPerChar;
  581. }
  582. U_CAPI const char* U_EXPORT2
  583. ucnv_getName (const UConverter * converter, UErrorCode * err)
  584. {
  585. if (U_FAILURE (*err))
  586. return nullptr;
  587. if(converter->sharedData->impl->getName){
  588. const char* temp= converter->sharedData->impl->getName(converter);
  589. if(temp)
  590. return temp;
  591. }
  592. return converter->sharedData->staticData->name;
  593. }
  594. U_CAPI int32_t U_EXPORT2
  595. ucnv_getCCSID(const UConverter * converter,
  596. UErrorCode * err)
  597. {
  598. int32_t ccsid;
  599. if (U_FAILURE (*err))
  600. return -1;
  601. ccsid = converter->sharedData->staticData->codepage;
  602. if (ccsid == 0) {
  603. /* Rare case. This is for cases like gb18030,
  604. which doesn't have an IBM canonical name, but does have an IBM alias. */
  605. const char *standardName = ucnv_getStandardName(ucnv_getName(converter, err), "IBM", err);
  606. if (U_SUCCESS(*err) && standardName) {
  607. const char *ccsidStr = uprv_strchr(standardName, '-');
  608. if (ccsidStr) {
  609. ccsid = (int32_t)atol(ccsidStr+1); /* +1 to skip '-' */
  610. }
  611. }
  612. }
  613. return ccsid;
  614. }
  615. U_CAPI UConverterPlatform U_EXPORT2
  616. ucnv_getPlatform (const UConverter * converter,
  617. UErrorCode * err)
  618. {
  619. if (U_FAILURE (*err))
  620. return UCNV_UNKNOWN;
  621. return (UConverterPlatform)converter->sharedData->staticData->platform;
  622. }
  623. U_CAPI void U_EXPORT2
  624. ucnv_getToUCallBack (const UConverter * converter,
  625. UConverterToUCallback *action,
  626. const void **context)
  627. {
  628. *action = converter->fromCharErrorBehaviour;
  629. *context = converter->toUContext;
  630. }
  631. U_CAPI void U_EXPORT2
  632. ucnv_getFromUCallBack (const UConverter * converter,
  633. UConverterFromUCallback *action,
  634. const void **context)
  635. {
  636. *action = converter->fromUCharErrorBehaviour;
  637. *context = converter->fromUContext;
  638. }
  639. U_CAPI void U_EXPORT2
  640. ucnv_setToUCallBack (UConverter * converter,
  641. UConverterToUCallback newAction,
  642. const void* newContext,
  643. UConverterToUCallback *oldAction,
  644. const void** oldContext,
  645. UErrorCode * err)
  646. {
  647. if (U_FAILURE (*err))
  648. return;
  649. if (oldAction) *oldAction = converter->fromCharErrorBehaviour;
  650. converter->fromCharErrorBehaviour = newAction;
  651. if (oldContext) *oldContext = converter->toUContext;
  652. converter->toUContext = newContext;
  653. }
  654. U_CAPI void U_EXPORT2
  655. ucnv_setFromUCallBack (UConverter * converter,
  656. UConverterFromUCallback newAction,
  657. const void* newContext,
  658. UConverterFromUCallback *oldAction,
  659. const void** oldContext,
  660. UErrorCode * err)
  661. {
  662. if (U_FAILURE (*err))
  663. return;
  664. if (oldAction) *oldAction = converter->fromUCharErrorBehaviour;
  665. converter->fromUCharErrorBehaviour = newAction;
  666. if (oldContext) *oldContext = converter->fromUContext;
  667. converter->fromUContext = newContext;
  668. }
  669. static void
  670. _updateOffsets(int32_t *offsets, int32_t length,
  671. int32_t sourceIndex, int32_t errorInputLength) {
  672. int32_t *limit;
  673. int32_t delta, offset;
  674. if(sourceIndex>=0) {
  675. /*
  676. * adjust each offset by adding the previous sourceIndex
  677. * minus the length of the input sequence that caused an
  678. * error, if any
  679. */
  680. delta=sourceIndex-errorInputLength;
  681. } else {
  682. /*
  683. * set each offset to -1 because this conversion function
  684. * does not handle offsets
  685. */
  686. delta=-1;
  687. }
  688. limit=offsets+length;
  689. if(delta==0) {
  690. /* most common case, nothing to do */
  691. } else if(delta>0) {
  692. /* add the delta to each offset (but not if the offset is <0) */
  693. while(offsets<limit) {
  694. offset=*offsets;
  695. if(offset>=0) {
  696. *offsets=offset+delta;
  697. }
  698. ++offsets;
  699. }
  700. } else /* delta<0 */ {
  701. /*
  702. * set each offset to -1 because this conversion function
  703. * does not handle offsets
  704. * or the error input sequence started in a previous buffer
  705. */
  706. while(offsets<limit) {
  707. *offsets++=-1;
  708. }
  709. }
  710. }
  711. /* ucnv_fromUnicode --------------------------------------------------------- */
  712. /*
  713. * Implementation note for m:n conversions
  714. *
  715. * While collecting source units to find the longest match for m:n conversion,
  716. * some source units may need to be stored for a partial match.
  717. * When a second buffer does not yield a match on all of the previously stored
  718. * source units, then they must be "replayed", i.e., fed back into the converter.
  719. *
  720. * The code relies on the fact that replaying will not nest -
  721. * converting a replay buffer will not result in a replay.
  722. * This is because a replay is necessary only after the _continuation_ of a
  723. * partial match failed, but a replay buffer is converted as a whole.
  724. * It may result in some of its units being stored again for a partial match,
  725. * but there will not be a continuation _during_ the replay which could fail.
  726. *
  727. * It is conceivable that a callback function could call the converter
  728. * recursively in a way that causes another replay to be stored, but that
  729. * would be an error in the callback function.
  730. * Such violations will cause assertion failures in a debug build,
  731. * and wrong output, but they will not cause a crash.
  732. */
  733. static void
  734. _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) {
  735. UConverterFromUnicode fromUnicode;
  736. UConverter *cnv;
  737. const char16_t *s;
  738. char *t;
  739. int32_t *offsets;
  740. int32_t sourceIndex;
  741. int32_t errorInputLength;
  742. UBool converterSawEndOfInput, calledCallback;
  743. /* variables for m:n conversion */
  744. char16_t replay[UCNV_EXT_MAX_UCHARS];
  745. const char16_t *realSource, *realSourceLimit;
  746. int32_t realSourceIndex;
  747. UBool realFlush;
  748. cnv=pArgs->converter;
  749. s=pArgs->source;
  750. t=pArgs->target;
  751. offsets=pArgs->offsets;
  752. /* get the converter implementation function */
  753. sourceIndex=0;
  754. if(offsets==nullptr) {
  755. fromUnicode=cnv->sharedData->impl->fromUnicode;
  756. } else {
  757. fromUnicode=cnv->sharedData->impl->fromUnicodeWithOffsets;
  758. if(fromUnicode==nullptr) {
  759. /* there is no WithOffsets implementation */
  760. fromUnicode=cnv->sharedData->impl->fromUnicode;
  761. /* we will write -1 for each offset */
  762. sourceIndex=-1;
  763. }
  764. }
  765. if(cnv->preFromULength>=0) {
  766. /* normal mode */
  767. realSource=nullptr;
  768. /* avoid compiler warnings - not otherwise necessary, and the values do not matter */
  769. realSourceLimit=nullptr;
  770. realFlush=false;
  771. realSourceIndex=0;
  772. } else {
  773. /*
  774. * Previous m:n conversion stored source units from a partial match
  775. * and failed to consume all of them.
  776. * We need to "replay" them from a temporary buffer and convert them first.
  777. */
  778. realSource=pArgs->source;
  779. realSourceLimit=pArgs->sourceLimit;
  780. realFlush=pArgs->flush;
  781. realSourceIndex=sourceIndex;
  782. uprv_memcpy(replay, cnv->preFromU, -cnv->preFromULength*U_SIZEOF_UCHAR);
  783. pArgs->source=replay;
  784. pArgs->sourceLimit=replay-cnv->preFromULength;
  785. pArgs->flush=false;
  786. sourceIndex=-1;
  787. cnv->preFromULength=0;
  788. }
  789. /*
  790. * loop for conversion and error handling
  791. *
  792. * loop {
  793. * convert
  794. * loop {
  795. * update offsets
  796. * handle end of input
  797. * handle errors/call callback
  798. * }
  799. * }
  800. */
  801. for(;;) {
  802. if(U_SUCCESS(*err)) {
  803. /* convert */
  804. fromUnicode(pArgs, err);
  805. /*
  806. * set a flag for whether the converter
  807. * successfully processed the end of the input
  808. *
  809. * need not check cnv->preFromULength==0 because a replay (<0) will cause
  810. * s<sourceLimit before converterSawEndOfInput is checked
  811. */
  812. converterSawEndOfInput=
  813. (UBool)(U_SUCCESS(*err) &&
  814. pArgs->flush && pArgs->source==pArgs->sourceLimit &&
  815. cnv->fromUChar32==0);
  816. } else {
  817. /* handle error from ucnv_convertEx() */
  818. converterSawEndOfInput=false;
  819. }
  820. /* no callback called yet for this iteration */
  821. calledCallback=false;
  822. /* no sourceIndex adjustment for conversion, only for callback output */
  823. errorInputLength=0;
  824. /*
  825. * loop for offsets and error handling
  826. *
  827. * iterates at most 3 times:
  828. * 1. to clean up after the conversion function
  829. * 2. after the callback
  830. * 3. after the callback again if there was truncated input
  831. */
  832. for(;;) {
  833. /* update offsets if we write any */
  834. if(offsets!=nullptr) {
  835. int32_t length=(int32_t)(pArgs->target-t);
  836. if(length>0) {
  837. _updateOffsets(offsets, length, sourceIndex, errorInputLength);
  838. /*
  839. * if a converter handles offsets and updates the offsets
  840. * pointer at the end, then pArgs->offset should not change
  841. * here;
  842. * however, some converters do not handle offsets at all
  843. * (sourceIndex<0) or may not update the offsets pointer
  844. */
  845. pArgs->offsets=offsets+=length;
  846. }
  847. if(sourceIndex>=0) {
  848. sourceIndex+=(int32_t)(pArgs->source-s);
  849. }
  850. }
  851. if(cnv->preFromULength<0) {
  852. /*
  853. * switch the source to new replay units (cannot occur while replaying)
  854. * after offset handling and before end-of-input and callback handling
  855. */
  856. if(realSource==nullptr) {
  857. realSource=pArgs->source;
  858. realSourceLimit=pArgs->sourceLimit;
  859. realFlush=pArgs->flush;
  860. realSourceIndex=sourceIndex;
  861. uprv_memcpy(replay, cnv->preFromU, -cnv->preFromULength*U_SIZEOF_UCHAR);
  862. pArgs->source=replay;
  863. pArgs->sourceLimit=replay-cnv->preFromULength;
  864. pArgs->flush=false;
  865. if((sourceIndex+=cnv->preFromULength)<0) {
  866. sourceIndex=-1;
  867. }
  868. cnv->preFromULength=0;
  869. } else {
  870. /* see implementation note before _fromUnicodeWithCallback() */
  871. U_ASSERT(realSource==nullptr);
  872. *err=U_INTERNAL_PROGRAM_ERROR;
  873. }
  874. }
  875. /* update pointers */
  876. s=pArgs->source;
  877. t=pArgs->target;
  878. if(U_SUCCESS(*err)) {
  879. if(s<pArgs->sourceLimit) {
  880. /*
  881. * continue with the conversion loop while there is still input left
  882. * (continue converting by breaking out of only the inner loop)
  883. */
  884. break;
  885. } else if(realSource!=nullptr) {
  886. /* switch back from replaying to the real source and continue */
  887. pArgs->source=realSource;
  888. pArgs->sourceLimit=realSourceLimit;
  889. pArgs->flush=realFlush;
  890. sourceIndex=realSourceIndex;
  891. realSource=nullptr;
  892. break;
  893. } else if(pArgs->flush && cnv->fromUChar32!=0) {
  894. /*
  895. * the entire input stream is consumed
  896. * and there is a partial, truncated input sequence left
  897. */
  898. /* inject an error and continue with callback handling */
  899. *err=U_TRUNCATED_CHAR_FOUND;
  900. calledCallback=false; /* new error condition */
  901. } else {
  902. /* input consumed */
  903. if(pArgs->flush) {
  904. /*
  905. * return to the conversion loop once more if the flush
  906. * flag is set and the conversion function has not
  907. * successfully processed the end of the input yet
  908. *
  909. * (continue converting by breaking out of only the inner loop)
  910. */
  911. if(!converterSawEndOfInput) {
  912. break;
  913. }
  914. /* reset the converter without calling the callback function */
  915. _reset(cnv, UCNV_RESET_FROM_UNICODE, false);
  916. }
  917. /* done successfully */
  918. return;
  919. }
  920. }
  921. /* U_FAILURE(*err) */
  922. {
  923. UErrorCode e;
  924. if( calledCallback ||
  925. (e=*err)==U_BUFFER_OVERFLOW_ERROR ||
  926. (e!=U_INVALID_CHAR_FOUND &&
  927. e!=U_ILLEGAL_CHAR_FOUND &&
  928. e!=U_TRUNCATED_CHAR_FOUND)
  929. ) {
  930. /*
  931. * the callback did not or cannot resolve the error:
  932. * set output pointers and return
  933. *
  934. * the check for buffer overflow is redundant but it is
  935. * a high-runner case and hopefully documents the intent
  936. * well
  937. *
  938. * if we were replaying, then the replay buffer must be
  939. * copied back into the UConverter
  940. * and the real arguments must be restored
  941. */
  942. if(realSource!=nullptr) {
  943. int32_t length;
  944. U_ASSERT(cnv->preFromULength==0);
  945. length=(int32_t)(pArgs->sourceLimit-pArgs->source);
  946. if(length>0) {
  947. u_memcpy(cnv->preFromU, pArgs->source, length);
  948. cnv->preFromULength=(int8_t)-length;
  949. }
  950. pArgs->source=realSource;
  951. pArgs->sourceLimit=realSourceLimit;
  952. pArgs->flush=realFlush;
  953. }
  954. return;
  955. }
  956. }
  957. /* callback handling */
  958. {
  959. UChar32 codePoint;
  960. /* get and write the code point */
  961. codePoint=cnv->fromUChar32;
  962. errorInputLength=0;
  963. U16_APPEND_UNSAFE(cnv->invalidUCharBuffer, errorInputLength, codePoint);
  964. cnv->invalidUCharLength=(int8_t)errorInputLength;
  965. /* set the converter state to deal with the next character */
  966. cnv->fromUChar32=0;
  967. /* call the callback function */
  968. cnv->fromUCharErrorBehaviour(cnv->fromUContext, pArgs,
  969. cnv->invalidUCharBuffer, errorInputLength, codePoint,
  970. *err==U_INVALID_CHAR_FOUND ? UCNV_UNASSIGNED : UCNV_ILLEGAL,
  971. err);
  972. }
  973. /*
  974. * loop back to the offset handling
  975. *
  976. * this flag will indicate after offset handling
  977. * that a callback was called;
  978. * if the callback did not resolve the error, then we return
  979. */
  980. calledCallback=true;
  981. }
  982. }
  983. }
  984. /*
  985. * Output the fromUnicode overflow buffer.
  986. * Call this function if(cnv->charErrorBufferLength>0).
  987. * @return true if overflow
  988. */
  989. static UBool
  990. ucnv_outputOverflowFromUnicode(UConverter *cnv,
  991. char **target, const char *targetLimit,
  992. int32_t **pOffsets,
  993. UErrorCode *err) {
  994. int32_t *offsets;
  995. char *overflow, *t;
  996. int32_t i, length;
  997. t=*target;
  998. if(pOffsets!=nullptr) {
  999. offsets=*pOffsets;
  1000. } else {
  1001. offsets=nullptr;
  1002. }
  1003. overflow=(char *)cnv->charErrorBuffer;
  1004. length=cnv->charErrorBufferLength;
  1005. i=0;
  1006. while(i<length) {
  1007. if(t==targetLimit) {
  1008. /* the overflow buffer contains too much, keep the rest */
  1009. int32_t j=0;
  1010. do {
  1011. overflow[j++]=overflow[i++];
  1012. } while(i<length);
  1013. cnv->charErrorBufferLength=(int8_t)j;
  1014. *target=t;
  1015. if(offsets!=nullptr) {
  1016. *pOffsets=offsets;
  1017. }
  1018. *err=U_BUFFER_OVERFLOW_ERROR;
  1019. return true;
  1020. }
  1021. /* copy the overflow contents to the target */
  1022. *t++=overflow[i++];
  1023. if(offsets!=nullptr) {
  1024. *offsets++=-1; /* no source index available for old output */
  1025. }
  1026. }
  1027. /* the overflow buffer is completely copied to the target */
  1028. cnv->charErrorBufferLength=0;
  1029. *target=t;
  1030. if(offsets!=nullptr) {
  1031. *pOffsets=offsets;
  1032. }
  1033. return false;
  1034. }
  1035. U_CAPI void U_EXPORT2
  1036. ucnv_fromUnicode(UConverter *cnv,
  1037. char **target, const char *targetLimit,
  1038. const char16_t **source, const char16_t *sourceLimit,
  1039. int32_t *offsets,
  1040. UBool flush,
  1041. UErrorCode *err) {
  1042. UConverterFromUnicodeArgs args;
  1043. const char16_t *s;
  1044. char *t;
  1045. /* check parameters */
  1046. if(err==nullptr || U_FAILURE(*err)) {
  1047. return;
  1048. }
  1049. if(cnv==nullptr || target==nullptr || source==nullptr) {
  1050. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1051. return;
  1052. }
  1053. s=*source;
  1054. t=*target;
  1055. if ((const void *)U_MAX_PTR(sourceLimit) == (const void *)sourceLimit) {
  1056. /*
  1057. Prevent code from going into an infinite loop in case we do hit this
  1058. limit. The limit pointer is expected to be on a char16_t * boundary.
  1059. This also prevents the next argument check from failing.
  1060. */
  1061. sourceLimit = (const char16_t *)(((const char *)sourceLimit) - 1);
  1062. }
  1063. /*
  1064. * All these conditions should never happen.
  1065. *
  1066. * 1) Make sure that the limits are >= to the address source or target
  1067. *
  1068. * 2) Make sure that the buffer sizes do not exceed the number range for
  1069. * int32_t because some functions use the size (in units or bytes)
  1070. * rather than comparing pointers, and because offsets are int32_t values.
  1071. *
  1072. * size_t is guaranteed to be unsigned and large enough for the job.
  1073. *
  1074. * Return with an error instead of adjusting the limits because we would
  1075. * not be able to maintain the semantics that either the source must be
  1076. * consumed or the target filled (unless an error occurs).
  1077. * An adjustment would be targetLimit=t+0x7fffffff; for example.
  1078. *
  1079. * 3) Make sure that the user didn't incorrectly cast a char16_t * pointer
  1080. * to a char * pointer and provide an incomplete char16_t code unit.
  1081. */
  1082. if (sourceLimit<s || targetLimit<t ||
  1083. ((size_t)(sourceLimit-s)>(size_t)0x3fffffff && sourceLimit>s) ||
  1084. ((size_t)(targetLimit-t)>(size_t)0x7fffffff && targetLimit>t) ||
  1085. (((const char *)sourceLimit-(const char *)s) & 1) != 0)
  1086. {
  1087. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1088. return;
  1089. }
  1090. /* output the target overflow buffer */
  1091. if( cnv->charErrorBufferLength>0 &&
  1092. ucnv_outputOverflowFromUnicode(cnv, target, targetLimit, &offsets, err)
  1093. ) {
  1094. /* U_BUFFER_OVERFLOW_ERROR */
  1095. return;
  1096. }
  1097. /* *target may have moved, therefore stop using t */
  1098. if(!flush && s==sourceLimit && cnv->preFromULength>=0) {
  1099. /* the overflow buffer is emptied and there is no new input: we are done */
  1100. return;
  1101. }
  1102. /*
  1103. * Do not simply return with a buffer overflow error if
  1104. * !flush && t==targetLimit
  1105. * because it is possible that the source will not generate any output.
  1106. * For example, the skip callback may be called;
  1107. * it does not output anything.
  1108. */
  1109. /* prepare the converter arguments */
  1110. args.converter=cnv;
  1111. args.flush=flush;
  1112. args.offsets=offsets;
  1113. args.source=s;
  1114. args.sourceLimit=sourceLimit;
  1115. args.target=*target;
  1116. args.targetLimit=targetLimit;
  1117. args.size=sizeof(args);
  1118. _fromUnicodeWithCallback(&args, err);
  1119. *source=args.source;
  1120. *target=args.target;
  1121. }
  1122. /* ucnv_toUnicode() --------------------------------------------------------- */
  1123. static void
  1124. _toUnicodeWithCallback(UConverterToUnicodeArgs *pArgs, UErrorCode *err) {
  1125. UConverterToUnicode toUnicode;
  1126. UConverter *cnv;
  1127. const char *s;
  1128. char16_t *t;
  1129. int32_t *offsets;
  1130. int32_t sourceIndex;
  1131. int32_t errorInputLength;
  1132. UBool converterSawEndOfInput, calledCallback;
  1133. /* variables for m:n conversion */
  1134. char replay[UCNV_EXT_MAX_BYTES];
  1135. const char *realSource, *realSourceLimit;
  1136. int32_t realSourceIndex;
  1137. UBool realFlush;
  1138. cnv=pArgs->converter;
  1139. s=pArgs->source;
  1140. t=pArgs->target;
  1141. offsets=pArgs->offsets;
  1142. /* get the converter implementation function */
  1143. sourceIndex=0;
  1144. if(offsets==nullptr) {
  1145. toUnicode=cnv->sharedData->impl->toUnicode;
  1146. } else {
  1147. toUnicode=cnv->sharedData->impl->toUnicodeWithOffsets;
  1148. if(toUnicode==nullptr) {
  1149. /* there is no WithOffsets implementation */
  1150. toUnicode=cnv->sharedData->impl->toUnicode;
  1151. /* we will write -1 for each offset */
  1152. sourceIndex=-1;
  1153. }
  1154. }
  1155. if(cnv->preToULength>=0) {
  1156. /* normal mode */
  1157. realSource=nullptr;
  1158. /* avoid compiler warnings - not otherwise necessary, and the values do not matter */
  1159. realSourceLimit=nullptr;
  1160. realFlush=false;
  1161. realSourceIndex=0;
  1162. } else {
  1163. /*
  1164. * Previous m:n conversion stored source units from a partial match
  1165. * and failed to consume all of them.
  1166. * We need to "replay" them from a temporary buffer and convert them first.
  1167. */
  1168. realSource=pArgs->source;
  1169. realSourceLimit=pArgs->sourceLimit;
  1170. realFlush=pArgs->flush;
  1171. realSourceIndex=sourceIndex;
  1172. uprv_memcpy(replay, cnv->preToU, -cnv->preToULength);
  1173. pArgs->source=replay;
  1174. pArgs->sourceLimit=replay-cnv->preToULength;
  1175. pArgs->flush=false;
  1176. sourceIndex=-1;
  1177. cnv->preToULength=0;
  1178. }
  1179. /*
  1180. * loop for conversion and error handling
  1181. *
  1182. * loop {
  1183. * convert
  1184. * loop {
  1185. * update offsets
  1186. * handle end of input
  1187. * handle errors/call callback
  1188. * }
  1189. * }
  1190. */
  1191. for(;;) {
  1192. if(U_SUCCESS(*err)) {
  1193. /* convert */
  1194. toUnicode(pArgs, err);
  1195. /*
  1196. * set a flag for whether the converter
  1197. * successfully processed the end of the input
  1198. *
  1199. * need not check cnv->preToULength==0 because a replay (<0) will cause
  1200. * s<sourceLimit before converterSawEndOfInput is checked
  1201. */
  1202. converterSawEndOfInput=
  1203. (UBool)(U_SUCCESS(*err) &&
  1204. pArgs->flush && pArgs->source==pArgs->sourceLimit &&
  1205. cnv->toULength==0);
  1206. } else {
  1207. /* handle error from getNextUChar() or ucnv_convertEx() */
  1208. converterSawEndOfInput=false;
  1209. }
  1210. /* no callback called yet for this iteration */
  1211. calledCallback=false;
  1212. /* no sourceIndex adjustment for conversion, only for callback output */
  1213. errorInputLength=0;
  1214. /*
  1215. * loop for offsets and error handling
  1216. *
  1217. * iterates at most 3 times:
  1218. * 1. to clean up after the conversion function
  1219. * 2. after the callback
  1220. * 3. after the callback again if there was truncated input
  1221. */
  1222. for(;;) {
  1223. /* update offsets if we write any */
  1224. if(offsets!=nullptr) {
  1225. int32_t length=(int32_t)(pArgs->target-t);
  1226. if(length>0) {
  1227. _updateOffsets(offsets, length, sourceIndex, errorInputLength);
  1228. /*
  1229. * if a converter handles offsets and updates the offsets
  1230. * pointer at the end, then pArgs->offset should not change
  1231. * here;
  1232. * however, some converters do not handle offsets at all
  1233. * (sourceIndex<0) or may not update the offsets pointer
  1234. */
  1235. pArgs->offsets=offsets+=length;
  1236. }
  1237. if(sourceIndex>=0) {
  1238. sourceIndex+=(int32_t)(pArgs->source-s);
  1239. }
  1240. }
  1241. if(cnv->preToULength<0) {
  1242. /*
  1243. * switch the source to new replay units (cannot occur while replaying)
  1244. * after offset handling and before end-of-input and callback handling
  1245. */
  1246. if(realSource==nullptr) {
  1247. realSource=pArgs->source;
  1248. realSourceLimit=pArgs->sourceLimit;
  1249. realFlush=pArgs->flush;
  1250. realSourceIndex=sourceIndex;
  1251. uprv_memcpy(replay, cnv->preToU, -cnv->preToULength);
  1252. pArgs->source=replay;
  1253. pArgs->sourceLimit=replay-cnv->preToULength;
  1254. pArgs->flush=false;
  1255. if((sourceIndex+=cnv->preToULength)<0) {
  1256. sourceIndex=-1;
  1257. }
  1258. cnv->preToULength=0;
  1259. } else {
  1260. /* see implementation note before _fromUnicodeWithCallback() */
  1261. U_ASSERT(realSource==nullptr);
  1262. *err=U_INTERNAL_PROGRAM_ERROR;
  1263. }
  1264. }
  1265. /* update pointers */
  1266. s=pArgs->source;
  1267. t=pArgs->target;
  1268. if(U_SUCCESS(*err)) {
  1269. if(s<pArgs->sourceLimit) {
  1270. /*
  1271. * continue with the conversion loop while there is still input left
  1272. * (continue converting by breaking out of only the inner loop)
  1273. */
  1274. break;
  1275. } else if(realSource!=nullptr) {
  1276. /* switch back from replaying to the real source and continue */
  1277. pArgs->source=realSource;
  1278. pArgs->sourceLimit=realSourceLimit;
  1279. pArgs->flush=realFlush;
  1280. sourceIndex=realSourceIndex;
  1281. realSource=nullptr;
  1282. break;
  1283. } else if(pArgs->flush && cnv->toULength>0) {
  1284. /*
  1285. * the entire input stream is consumed
  1286. * and there is a partial, truncated input sequence left
  1287. */
  1288. /* inject an error and continue with callback handling */
  1289. *err=U_TRUNCATED_CHAR_FOUND;
  1290. calledCallback=false; /* new error condition */
  1291. } else {
  1292. /* input consumed */
  1293. if(pArgs->flush) {
  1294. /*
  1295. * return to the conversion loop once more if the flush
  1296. * flag is set and the conversion function has not
  1297. * successfully processed the end of the input yet
  1298. *
  1299. * (continue converting by breaking out of only the inner loop)
  1300. */
  1301. if(!converterSawEndOfInput) {
  1302. break;
  1303. }
  1304. /* reset the converter without calling the callback function */
  1305. _reset(cnv, UCNV_RESET_TO_UNICODE, false);
  1306. }
  1307. /* done successfully */
  1308. return;
  1309. }
  1310. }
  1311. /* U_FAILURE(*err) */
  1312. {
  1313. UErrorCode e;
  1314. if( calledCallback ||
  1315. (e=*err)==U_BUFFER_OVERFLOW_ERROR ||
  1316. (e!=U_INVALID_CHAR_FOUND &&
  1317. e!=U_ILLEGAL_CHAR_FOUND &&
  1318. e!=U_TRUNCATED_CHAR_FOUND &&
  1319. e!=U_ILLEGAL_ESCAPE_SEQUENCE &&
  1320. e!=U_UNSUPPORTED_ESCAPE_SEQUENCE)
  1321. ) {
  1322. /*
  1323. * the callback did not or cannot resolve the error:
  1324. * set output pointers and return
  1325. *
  1326. * the check for buffer overflow is redundant but it is
  1327. * a high-runner case and hopefully documents the intent
  1328. * well
  1329. *
  1330. * if we were replaying, then the replay buffer must be
  1331. * copied back into the UConverter
  1332. * and the real arguments must be restored
  1333. */
  1334. if(realSource!=nullptr) {
  1335. int32_t length;
  1336. U_ASSERT(cnv->preToULength==0);
  1337. length=(int32_t)(pArgs->sourceLimit-pArgs->source);
  1338. if(length>0) {
  1339. uprv_memcpy(cnv->preToU, pArgs->source, length);
  1340. cnv->preToULength=(int8_t)-length;
  1341. }
  1342. pArgs->source=realSource;
  1343. pArgs->sourceLimit=realSourceLimit;
  1344. pArgs->flush=realFlush;
  1345. }
  1346. return;
  1347. }
  1348. }
  1349. /* copy toUBytes[] to invalidCharBuffer[] */
  1350. errorInputLength=cnv->invalidCharLength=cnv->toULength;
  1351. if(errorInputLength>0) {
  1352. uprv_memcpy(cnv->invalidCharBuffer, cnv->toUBytes, errorInputLength);
  1353. }
  1354. /* set the converter state to deal with the next character */
  1355. cnv->toULength=0;
  1356. /* call the callback function */
  1357. if(cnv->toUCallbackReason==UCNV_ILLEGAL && *err==U_INVALID_CHAR_FOUND) {
  1358. cnv->toUCallbackReason = UCNV_UNASSIGNED;
  1359. }
  1360. cnv->fromCharErrorBehaviour(cnv->toUContext, pArgs,
  1361. cnv->invalidCharBuffer, errorInputLength,
  1362. cnv->toUCallbackReason,
  1363. err);
  1364. cnv->toUCallbackReason = UCNV_ILLEGAL; /* reset to default value */
  1365. /*
  1366. * loop back to the offset handling
  1367. *
  1368. * this flag will indicate after offset handling
  1369. * that a callback was called;
  1370. * if the callback did not resolve the error, then we return
  1371. */
  1372. calledCallback=true;
  1373. }
  1374. }
  1375. }
  1376. /*
  1377. * Output the toUnicode overflow buffer.
  1378. * Call this function if(cnv->UCharErrorBufferLength>0).
  1379. * @return true if overflow
  1380. */
  1381. static UBool
  1382. ucnv_outputOverflowToUnicode(UConverter *cnv,
  1383. char16_t **target, const char16_t *targetLimit,
  1384. int32_t **pOffsets,
  1385. UErrorCode *err) {
  1386. int32_t *offsets;
  1387. char16_t *overflow, *t;
  1388. int32_t i, length;
  1389. t=*target;
  1390. if(pOffsets!=nullptr) {
  1391. offsets=*pOffsets;
  1392. } else {
  1393. offsets=nullptr;
  1394. }
  1395. overflow=cnv->UCharErrorBuffer;
  1396. length=cnv->UCharErrorBufferLength;
  1397. i=0;
  1398. while(i<length) {
  1399. if(t==targetLimit) {
  1400. /* the overflow buffer contains too much, keep the rest */
  1401. int32_t j=0;
  1402. do {
  1403. overflow[j++]=overflow[i++];
  1404. } while(i<length);
  1405. cnv->UCharErrorBufferLength=(int8_t)j;
  1406. *target=t;
  1407. if(offsets!=nullptr) {
  1408. *pOffsets=offsets;
  1409. }
  1410. *err=U_BUFFER_OVERFLOW_ERROR;
  1411. return true;
  1412. }
  1413. /* copy the overflow contents to the target */
  1414. *t++=overflow[i++];
  1415. if(offsets!=nullptr) {
  1416. *offsets++=-1; /* no source index available for old output */
  1417. }
  1418. }
  1419. /* the overflow buffer is completely copied to the target */
  1420. cnv->UCharErrorBufferLength=0;
  1421. *target=t;
  1422. if(offsets!=nullptr) {
  1423. *pOffsets=offsets;
  1424. }
  1425. return false;
  1426. }
  1427. U_CAPI void U_EXPORT2
  1428. ucnv_toUnicode(UConverter *cnv,
  1429. char16_t **target, const char16_t *targetLimit,
  1430. const char **source, const char *sourceLimit,
  1431. int32_t *offsets,
  1432. UBool flush,
  1433. UErrorCode *err) {
  1434. UConverterToUnicodeArgs args;
  1435. const char *s;
  1436. char16_t *t;
  1437. /* check parameters */
  1438. if(err==nullptr || U_FAILURE(*err)) {
  1439. return;
  1440. }
  1441. if(cnv==nullptr || target==nullptr || source==nullptr) {
  1442. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1443. return;
  1444. }
  1445. s=*source;
  1446. t=*target;
  1447. if ((const void *)U_MAX_PTR(targetLimit) == (const void *)targetLimit) {
  1448. /*
  1449. Prevent code from going into an infinite loop in case we do hit this
  1450. limit. The limit pointer is expected to be on a char16_t * boundary.
  1451. This also prevents the next argument check from failing.
  1452. */
  1453. targetLimit = (const char16_t *)(((const char *)targetLimit) - 1);
  1454. }
  1455. /*
  1456. * All these conditions should never happen.
  1457. *
  1458. * 1) Make sure that the limits are >= to the address source or target
  1459. *
  1460. * 2) Make sure that the buffer sizes do not exceed the number range for
  1461. * int32_t because some functions use the size (in units or bytes)
  1462. * rather than comparing pointers, and because offsets are int32_t values.
  1463. *
  1464. * size_t is guaranteed to be unsigned and large enough for the job.
  1465. *
  1466. * Return with an error instead of adjusting the limits because we would
  1467. * not be able to maintain the semantics that either the source must be
  1468. * consumed or the target filled (unless an error occurs).
  1469. * An adjustment would be sourceLimit=t+0x7fffffff; for example.
  1470. *
  1471. * 3) Make sure that the user didn't incorrectly cast a char16_t * pointer
  1472. * to a char * pointer and provide an incomplete char16_t code unit.
  1473. */
  1474. if (sourceLimit<s || targetLimit<t ||
  1475. ((size_t)(sourceLimit-s)>(size_t)0x7fffffff && sourceLimit>s) ||
  1476. ((size_t)(targetLimit-t)>(size_t)0x3fffffff && targetLimit>t) ||
  1477. (((const char *)targetLimit-(const char *)t) & 1) != 0
  1478. ) {
  1479. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1480. return;
  1481. }
  1482. /* output the target overflow buffer */
  1483. if( cnv->UCharErrorBufferLength>0 &&
  1484. ucnv_outputOverflowToUnicode(cnv, target, targetLimit, &offsets, err)
  1485. ) {
  1486. /* U_BUFFER_OVERFLOW_ERROR */
  1487. return;
  1488. }
  1489. /* *target may have moved, therefore stop using t */
  1490. if(!flush && s==sourceLimit && cnv->preToULength>=0) {
  1491. /* the overflow buffer is emptied and there is no new input: we are done */
  1492. return;
  1493. }
  1494. /*
  1495. * Do not simply return with a buffer overflow error if
  1496. * !flush && t==targetLimit
  1497. * because it is possible that the source will not generate any output.
  1498. * For example, the skip callback may be called;
  1499. * it does not output anything.
  1500. */
  1501. /* prepare the converter arguments */
  1502. args.converter=cnv;
  1503. args.flush=flush;
  1504. args.offsets=offsets;
  1505. args.source=s;
  1506. args.sourceLimit=sourceLimit;
  1507. args.target=*target;
  1508. args.targetLimit=targetLimit;
  1509. args.size=sizeof(args);
  1510. _toUnicodeWithCallback(&args, err);
  1511. *source=args.source;
  1512. *target=args.target;
  1513. }
  1514. /* ucnv_to/fromUChars() ----------------------------------------------------- */
  1515. U_CAPI int32_t U_EXPORT2
  1516. ucnv_fromUChars(UConverter *cnv,
  1517. char *dest, int32_t destCapacity,
  1518. const char16_t *src, int32_t srcLength,
  1519. UErrorCode *pErrorCode) {
  1520. const char16_t *srcLimit;
  1521. char *originalDest, *destLimit;
  1522. int32_t destLength;
  1523. /* check arguments */
  1524. if(pErrorCode==nullptr || U_FAILURE(*pErrorCode)) {
  1525. return 0;
  1526. }
  1527. if( cnv==nullptr ||
  1528. destCapacity<0 || (destCapacity>0 && dest==nullptr) ||
  1529. srcLength<-1 || (srcLength!=0 && src==nullptr)
  1530. ) {
  1531. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1532. return 0;
  1533. }
  1534. /* initialize */
  1535. ucnv_resetFromUnicode(cnv);
  1536. originalDest=dest;
  1537. if(srcLength==-1) {
  1538. srcLength=u_strlen(src);
  1539. }
  1540. if(srcLength>0) {
  1541. srcLimit=src+srcLength;
  1542. destCapacity=pinCapacity(dest, destCapacity);
  1543. destLimit=dest+destCapacity;
  1544. /* perform the conversion */
  1545. ucnv_fromUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, true, pErrorCode);
  1546. destLength=(int32_t)(dest-originalDest);
  1547. /* if an overflow occurs, then get the preflighting length */
  1548. if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
  1549. char buffer[1024];
  1550. destLimit=buffer+sizeof(buffer);
  1551. do {
  1552. dest=buffer;
  1553. *pErrorCode=U_ZERO_ERROR;
  1554. ucnv_fromUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, true, pErrorCode);
  1555. destLength+=(int32_t)(dest-buffer);
  1556. } while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR);
  1557. }
  1558. } else {
  1559. destLength=0;
  1560. }
  1561. return u_terminateChars(originalDest, destCapacity, destLength, pErrorCode);
  1562. }
  1563. U_CAPI int32_t U_EXPORT2
  1564. ucnv_toUChars(UConverter *cnv,
  1565. char16_t *dest, int32_t destCapacity,
  1566. const char *src, int32_t srcLength,
  1567. UErrorCode *pErrorCode) {
  1568. const char *srcLimit;
  1569. char16_t *originalDest, *destLimit;
  1570. int32_t destLength;
  1571. /* check arguments */
  1572. if(pErrorCode==nullptr || U_FAILURE(*pErrorCode)) {
  1573. return 0;
  1574. }
  1575. if( cnv==nullptr ||
  1576. destCapacity<0 || (destCapacity>0 && dest==nullptr) ||
  1577. srcLength<-1 || (srcLength!=0 && src==nullptr))
  1578. {
  1579. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1580. return 0;
  1581. }
  1582. /* initialize */
  1583. ucnv_resetToUnicode(cnv);
  1584. originalDest=dest;
  1585. if(srcLength==-1) {
  1586. srcLength=(int32_t)uprv_strlen(src);
  1587. }
  1588. if(srcLength>0) {
  1589. srcLimit=src+srcLength;
  1590. destCapacity=pinCapacity(dest, destCapacity);
  1591. destLimit=dest+destCapacity;
  1592. /* perform the conversion */
  1593. ucnv_toUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, true, pErrorCode);
  1594. destLength=(int32_t)(dest-originalDest);
  1595. /* if an overflow occurs, then get the preflighting length */
  1596. if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR)
  1597. {
  1598. char16_t buffer[1024];
  1599. destLimit=buffer+UPRV_LENGTHOF(buffer);
  1600. do {
  1601. dest=buffer;
  1602. *pErrorCode=U_ZERO_ERROR;
  1603. ucnv_toUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, true, pErrorCode);
  1604. destLength+=(int32_t)(dest-buffer);
  1605. }
  1606. while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR);
  1607. }
  1608. } else {
  1609. destLength=0;
  1610. }
  1611. return u_terminateUChars(originalDest, destCapacity, destLength, pErrorCode);
  1612. }
  1613. /* ucnv_getNextUChar() ------------------------------------------------------ */
  1614. U_CAPI UChar32 U_EXPORT2
  1615. ucnv_getNextUChar(UConverter *cnv,
  1616. const char **source, const char *sourceLimit,
  1617. UErrorCode *err) {
  1618. UConverterToUnicodeArgs args;
  1619. char16_t buffer[U16_MAX_LENGTH];
  1620. const char *s;
  1621. UChar32 c;
  1622. int32_t i, length;
  1623. /* check parameters */
  1624. if(err==nullptr || U_FAILURE(*err)) {
  1625. return 0xffff;
  1626. }
  1627. if(cnv==nullptr || source==nullptr) {
  1628. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1629. return 0xffff;
  1630. }
  1631. s=*source;
  1632. if(sourceLimit<s) {
  1633. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1634. return 0xffff;
  1635. }
  1636. /*
  1637. * Make sure that the buffer sizes do not exceed the number range for
  1638. * int32_t because some functions use the size (in units or bytes)
  1639. * rather than comparing pointers, and because offsets are int32_t values.
  1640. *
  1641. * size_t is guaranteed to be unsigned and large enough for the job.
  1642. *
  1643. * Return with an error instead of adjusting the limits because we would
  1644. * not be able to maintain the semantics that either the source must be
  1645. * consumed or the target filled (unless an error occurs).
  1646. * An adjustment would be sourceLimit=t+0x7fffffff; for example.
  1647. */
  1648. if(((size_t)(sourceLimit-s)>(size_t)0x7fffffff && sourceLimit>s)) {
  1649. *err=U_ILLEGAL_ARGUMENT_ERROR;
  1650. return 0xffff;
  1651. }
  1652. c=U_SENTINEL;
  1653. /* flush the target overflow buffer */
  1654. if(cnv->UCharErrorBufferLength>0) {
  1655. char16_t *overflow;
  1656. overflow=cnv->UCharErrorBuffer;
  1657. i=0;
  1658. length=cnv->UCharErrorBufferLength;
  1659. U16_NEXT(overflow, i, length, c);
  1660. /* move the remaining overflow contents up to the beginning */
  1661. if((cnv->UCharErrorBufferLength=(int8_t)(length-i))>0) {
  1662. uprv_memmove(cnv->UCharErrorBuffer, cnv->UCharErrorBuffer+i,
  1663. cnv->UCharErrorBufferLength*U_SIZEOF_UCHAR);
  1664. }
  1665. if(!U16_IS_LEAD(c) || i<length) {
  1666. return c;
  1667. }
  1668. /*
  1669. * Continue if the overflow buffer contained only a lead surrogate,
  1670. * in case the converter outputs single surrogates from complete
  1671. * input sequences.
  1672. */
  1673. }
  1674. /*
  1675. * flush==true is implied for ucnv_getNextUChar()
  1676. *
  1677. * do not simply return even if s==sourceLimit because the converter may
  1678. * not have seen flush==true before
  1679. */
  1680. /* prepare the converter arguments */
  1681. args.converter=cnv;
  1682. args.flush=true;
  1683. args.offsets=nullptr;
  1684. args.source=s;
  1685. args.sourceLimit=sourceLimit;
  1686. args.target=buffer;
  1687. args.targetLimit=buffer+1;
  1688. args.size=sizeof(args);
  1689. if(c<0) {
  1690. /*
  1691. * call the native getNextUChar() implementation if we are
  1692. * at a character boundary (toULength==0)
  1693. *
  1694. * unlike with _toUnicode(), getNextUChar() implementations must set
  1695. * U_TRUNCATED_CHAR_FOUND for truncated input,
  1696. * in addition to setting toULength/toUBytes[]
  1697. */
  1698. if(cnv->toULength==0 && cnv->sharedData->impl->getNextUChar!=nullptr) {
  1699. c=cnv->sharedData->impl->getNextUChar(&args, err);
  1700. *source=s=args.source;
  1701. if(*err==U_INDEX_OUTOFBOUNDS_ERROR) {
  1702. /* reset the converter without calling the callback function */
  1703. _reset(cnv, UCNV_RESET_TO_UNICODE, false);
  1704. return 0xffff; /* no output */
  1705. } else if(U_SUCCESS(*err) && c>=0) {
  1706. return c;
  1707. /*
  1708. * else fall through to use _toUnicode() because
  1709. * UCNV_GET_NEXT_UCHAR_USE_TO_U: the native function did not want to handle it after all
  1710. * U_FAILURE: call _toUnicode() for callback handling (do not output c)
  1711. */
  1712. }
  1713. }
  1714. /* convert to one char16_t in buffer[0], or handle getNextUChar() errors */
  1715. _toUnicodeWithCallback(&args, err);
  1716. if(*err==U_BUFFER_OVERFLOW_ERROR) {
  1717. *err=U_ZERO_ERROR;
  1718. }
  1719. i=0;
  1720. length=(int32_t)(args.target-buffer);
  1721. } else {
  1722. /* write the lead surrogate from the overflow buffer */
  1723. buffer[0]=(char16_t)c;
  1724. args.target=buffer+1;
  1725. i=0;
  1726. length=1;
  1727. }
  1728. /* buffer contents starts at i and ends before length */
  1729. if(U_FAILURE(*err)) {
  1730. c=0xffff; /* no output */
  1731. } else if(length==0) {
  1732. /* no input or only state changes */
  1733. *err=U_INDEX_OUTOFBOUNDS_ERROR;
  1734. /* no need to reset explicitly because _toUnicodeWithCallback() did it */
  1735. c=0xffff; /* no output */
  1736. } else {
  1737. c=buffer[0];
  1738. i=1;
  1739. if(!U16_IS_LEAD(c)) {
  1740. /* consume c=buffer[0], done */
  1741. } else {
  1742. /* got a lead surrogate, see if a trail surrogate follows */
  1743. char16_t c2;
  1744. if(cnv->UCharErrorBufferLength>0) {
  1745. /* got overflow output from the conversion */
  1746. if(U16_IS_TRAIL(c2=cnv->UCharErrorBuffer[0])) {
  1747. /* got a trail surrogate, too */
  1748. c=U16_GET_SUPPLEMENTARY(c, c2);
  1749. /* move the remaining overflow contents up to the beginning */
  1750. if((--cnv->UCharErrorBufferLength)>0) {
  1751. uprv_memmove(cnv->UCharErrorBuffer, cnv->UCharErrorBuffer+1,
  1752. cnv->UCharErrorBufferLength*U_SIZEOF_UCHAR);
  1753. }
  1754. } else {
  1755. /* c is an unpaired lead surrogate, just return it */
  1756. }
  1757. } else if(args.source<sourceLimit) {
  1758. /* convert once more, to buffer[1] */
  1759. args.targetLimit=buffer+2;
  1760. _toUnicodeWithCallback(&args, err);
  1761. if(*err==U_BUFFER_OVERFLOW_ERROR) {
  1762. *err=U_ZERO_ERROR;
  1763. }
  1764. length=(int32_t)(args.target-buffer);
  1765. if(U_SUCCESS(*err) && length==2 && U16_IS_TRAIL(c2=buffer[1])) {
  1766. /* got a trail surrogate, too */
  1767. c=U16_GET_SUPPLEMENTARY(c, c2);
  1768. i=2;
  1769. }
  1770. }
  1771. }
  1772. }
  1773. /*
  1774. * move leftover output from buffer[i..length[
  1775. * into the beginning of the overflow buffer
  1776. */
  1777. if(i<length) {
  1778. /* move further overflow back */
  1779. int32_t delta=length-i;
  1780. if((length=cnv->UCharErrorBufferLength)>0) {
  1781. uprv_memmove(cnv->UCharErrorBuffer+delta, cnv->UCharErrorBuffer,
  1782. length*U_SIZEOF_UCHAR);
  1783. }
  1784. cnv->UCharErrorBufferLength=(int8_t)(length+delta);
  1785. cnv->UCharErrorBuffer[0]=buffer[i++];
  1786. if(delta>1) {
  1787. cnv->UCharErrorBuffer[1]=buffer[i];
  1788. }
  1789. }
  1790. *source=args.source;
  1791. return c;
  1792. }
  1793. /* ucnv_convert() and siblings ---------------------------------------------- */
  1794. U_CAPI void U_EXPORT2
  1795. ucnv_convertEx(UConverter *targetCnv, UConverter *sourceCnv,
  1796. char **target, const char *targetLimit,
  1797. const char **source, const char *sourceLimit,
  1798. char16_t *pivotStart, char16_t **pivotSource,
  1799. char16_t **pivotTarget, const char16_t *pivotLimit,
  1800. UBool reset, UBool flush,
  1801. UErrorCode *pErrorCode) {
  1802. char16_t pivotBuffer[CHUNK_SIZE];
  1803. const char16_t *myPivotSource;
  1804. char16_t *myPivotTarget;
  1805. const char *s;
  1806. char *t;
  1807. UConverterToUnicodeArgs toUArgs;
  1808. UConverterFromUnicodeArgs fromUArgs;
  1809. UConverterConvert convert;
  1810. /* error checking */
  1811. if(pErrorCode==nullptr || U_FAILURE(*pErrorCode)) {
  1812. return;
  1813. }
  1814. if( targetCnv==nullptr || sourceCnv==nullptr ||
  1815. source==nullptr || *source==nullptr ||
  1816. target==nullptr || *target==nullptr || targetLimit==nullptr
  1817. ) {
  1818. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1819. return;
  1820. }
  1821. s=*source;
  1822. t=*target;
  1823. if((sourceLimit!=nullptr && sourceLimit<s) || targetLimit<t) {
  1824. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1825. return;
  1826. }
  1827. /*
  1828. * Make sure that the buffer sizes do not exceed the number range for
  1829. * int32_t. See ucnv_toUnicode() for a more detailed comment.
  1830. */
  1831. if(
  1832. (sourceLimit!=nullptr && ((size_t)(sourceLimit-s)>(size_t)0x7fffffff && sourceLimit>s)) ||
  1833. ((size_t)(targetLimit-t)>(size_t)0x7fffffff && targetLimit>t)
  1834. ) {
  1835. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1836. return;
  1837. }
  1838. if(pivotStart==nullptr) {
  1839. if(!flush) {
  1840. /* streaming conversion requires an explicit pivot buffer */
  1841. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1842. return;
  1843. }
  1844. /* use the stack pivot buffer */
  1845. myPivotSource=myPivotTarget=pivotStart=pivotBuffer;
  1846. pivotSource=(char16_t **)&myPivotSource;
  1847. pivotTarget=&myPivotTarget;
  1848. pivotLimit=pivotBuffer+CHUNK_SIZE;
  1849. } else if( pivotStart>=pivotLimit ||
  1850. pivotSource==nullptr || *pivotSource==nullptr ||
  1851. pivotTarget==nullptr || *pivotTarget==nullptr ||
  1852. pivotLimit==nullptr
  1853. ) {
  1854. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  1855. return;
  1856. }
  1857. if(sourceLimit==nullptr) {
  1858. /* get limit of single-byte-NUL-terminated source string */
  1859. sourceLimit=uprv_strchr(*source, 0);
  1860. }
  1861. if(reset) {
  1862. ucnv_resetToUnicode(sourceCnv);
  1863. ucnv_resetFromUnicode(targetCnv);
  1864. *pivotSource=*pivotTarget=pivotStart;
  1865. } else if(targetCnv->charErrorBufferLength>0) {
  1866. /* output the targetCnv overflow buffer */
  1867. if(ucnv_outputOverflowFromUnicode(targetCnv, target, targetLimit, nullptr, pErrorCode)) {
  1868. /* U_BUFFER_OVERFLOW_ERROR */
  1869. return;
  1870. }
  1871. /* *target has moved, therefore stop using t */
  1872. if( !flush &&
  1873. targetCnv->preFromULength>=0 && *pivotSource==*pivotTarget &&
  1874. sourceCnv->UCharErrorBufferLength==0 && sourceCnv->preToULength>=0 && s==sourceLimit
  1875. ) {
  1876. /* the fromUnicode overflow buffer is emptied and there is no new input: we are done */
  1877. return;
  1878. }
  1879. }
  1880. /* Is direct-UTF-8 conversion available? */
  1881. if( sourceCnv->sharedData->staticData->conversionType==UCNV_UTF8 &&
  1882. targetCnv->sharedData->impl->fromUTF8!=nullptr
  1883. ) {
  1884. convert=targetCnv->sharedData->impl->fromUTF8;
  1885. } else if( targetCnv->sharedData->staticData->conversionType==UCNV_UTF8 &&
  1886. sourceCnv->sharedData->impl->toUTF8!=nullptr
  1887. ) {
  1888. convert=sourceCnv->sharedData->impl->toUTF8;
  1889. } else {
  1890. convert=nullptr;
  1891. }
  1892. /*
  1893. * If direct-UTF-8 conversion is available, then we use a smaller
  1894. * pivot buffer for error handling and partial matches
  1895. * so that we quickly return to direct conversion.
  1896. *
  1897. * 32 is large enough for UCNV_EXT_MAX_UCHARS and UCNV_ERROR_BUFFER_LENGTH.
  1898. *
  1899. * We could reduce the pivot buffer size further, at the cost of
  1900. * buffer overflows from callbacks.
  1901. * The pivot buffer should not be smaller than the maximum number of
  1902. * fromUnicode extension table input UChars
  1903. * (for m:n conversion, see
  1904. * targetCnv->sharedData->mbcs.extIndexes[UCNV_EXT_COUNT_UCHARS])
  1905. * or 2 for surrogate pairs.
  1906. *
  1907. * Too small a buffer can cause thrashing between pivoting and direct
  1908. * conversion, with function call overhead outweighing the benefits
  1909. * of direct conversion.
  1910. */
  1911. if(convert!=nullptr && (pivotLimit-pivotStart)>32) {
  1912. pivotLimit=pivotStart+32;
  1913. }
  1914. /* prepare the converter arguments */
  1915. fromUArgs.converter=targetCnv;
  1916. fromUArgs.flush=false;
  1917. fromUArgs.offsets=nullptr;
  1918. fromUArgs.target=*target;
  1919. fromUArgs.targetLimit=targetLimit;
  1920. fromUArgs.size=sizeof(fromUArgs);
  1921. toUArgs.converter=sourceCnv;
  1922. toUArgs.flush=flush;
  1923. toUArgs.offsets=nullptr;
  1924. toUArgs.source=s;
  1925. toUArgs.sourceLimit=sourceLimit;
  1926. toUArgs.targetLimit=pivotLimit;
  1927. toUArgs.size=sizeof(toUArgs);
  1928. /*
  1929. * TODO: Consider separating this function into two functions,
  1930. * extracting exactly the conversion loop,
  1931. * for readability and to reduce the set of visible variables.
  1932. *
  1933. * Otherwise stop using s and t from here on.
  1934. */
  1935. s=t=nullptr;
  1936. /*
  1937. * conversion loop
  1938. *
  1939. * The sequence of steps in the loop may appear backward,
  1940. * but the principle is simple:
  1941. * In the chain of
  1942. * source - sourceCnv overflow - pivot - targetCnv overflow - target
  1943. * empty out later buffers before refilling them from earlier ones.
  1944. *
  1945. * The targetCnv overflow buffer is flushed out only once before the loop.
  1946. */
  1947. for(;;) {
  1948. /*
  1949. * if(pivot not empty or error or replay or flush fromUnicode) {
  1950. * fromUnicode(pivot -> target);
  1951. * }
  1952. *
  1953. * For pivoting conversion; and for direct conversion for
  1954. * error callback handling and flushing the replay buffer.
  1955. */
  1956. if( *pivotSource<*pivotTarget ||
  1957. U_FAILURE(*pErrorCode) ||
  1958. targetCnv->preFromULength<0 ||
  1959. fromUArgs.flush
  1960. ) {
  1961. fromUArgs.source=*pivotSource;
  1962. fromUArgs.sourceLimit=*pivotTarget;
  1963. _fromUnicodeWithCallback(&fromUArgs, pErrorCode);
  1964. if(U_FAILURE(*pErrorCode)) {
  1965. /* target overflow, or conversion error */
  1966. *pivotSource=(char16_t *)fromUArgs.source;
  1967. break;
  1968. }
  1969. /*
  1970. * _fromUnicodeWithCallback() must have consumed the pivot contents
  1971. * (*pivotSource==*pivotTarget) since it returned with U_SUCCESS()
  1972. */
  1973. }
  1974. /* The pivot buffer is empty; reset it so we start at pivotStart. */
  1975. *pivotSource=*pivotTarget=pivotStart;
  1976. /*
  1977. * if(sourceCnv overflow buffer not empty) {
  1978. * move(sourceCnv overflow buffer -> pivot);
  1979. * continue;
  1980. * }
  1981. */
  1982. /* output the sourceCnv overflow buffer */
  1983. if(sourceCnv->UCharErrorBufferLength>0) {
  1984. if(ucnv_outputOverflowToUnicode(sourceCnv, pivotTarget, pivotLimit, nullptr, pErrorCode)) {
  1985. /* U_BUFFER_OVERFLOW_ERROR */
  1986. *pErrorCode=U_ZERO_ERROR;
  1987. }
  1988. continue;
  1989. }
  1990. /*
  1991. * check for end of input and break if done
  1992. *
  1993. * Checking both flush and fromUArgs.flush ensures that the converters
  1994. * have been called with the flush flag set if the ucnv_convertEx()
  1995. * caller set it.
  1996. */
  1997. if( toUArgs.source==sourceLimit &&
  1998. sourceCnv->preToULength>=0 && sourceCnv->toULength==0 &&
  1999. (!flush || fromUArgs.flush)
  2000. ) {
  2001. /* done successfully */
  2002. break;
  2003. }
  2004. /*
  2005. * use direct conversion if available
  2006. * but not if continuing a partial match
  2007. * or flushing the toUnicode replay buffer
  2008. */
  2009. if(convert!=nullptr && targetCnv->preFromUFirstCP<0 && sourceCnv->preToULength==0) {
  2010. if(*pErrorCode==U_USING_DEFAULT_WARNING) {
  2011. /* remove a warning that may be set by this function */
  2012. *pErrorCode=U_ZERO_ERROR;
  2013. }
  2014. convert(&fromUArgs, &toUArgs, pErrorCode);
  2015. if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
  2016. break;
  2017. } else if(U_FAILURE(*pErrorCode)) {
  2018. if(sourceCnv->toULength>0) {
  2019. /*
  2020. * Fall through to calling _toUnicodeWithCallback()
  2021. * for callback handling.
  2022. *
  2023. * The pivot buffer will be reset with
  2024. * *pivotSource=*pivotTarget=pivotStart;
  2025. * which indicates a toUnicode error to the caller
  2026. * (*pivotSource==pivotStart shows no pivot UChars consumed).
  2027. */
  2028. } else {
  2029. /*
  2030. * Indicate a fromUnicode error to the caller
  2031. * (*pivotSource>pivotStart shows some pivot UChars consumed).
  2032. */
  2033. *pivotSource=*pivotTarget=pivotStart+1;
  2034. /*
  2035. * Loop around to calling _fromUnicodeWithCallbacks()
  2036. * for callback handling.
  2037. */
  2038. continue;
  2039. }
  2040. } else if(*pErrorCode==U_USING_DEFAULT_WARNING) {
  2041. /*
  2042. * No error, but the implementation requested to temporarily
  2043. * fall back to pivoting.
  2044. */
  2045. *pErrorCode=U_ZERO_ERROR;
  2046. /*
  2047. * The following else branches are almost identical to the end-of-input
  2048. * handling in _toUnicodeWithCallback().
  2049. * Avoid calling it just for the end of input.
  2050. */
  2051. } else if(flush && sourceCnv->toULength>0) { /* flush==toUArgs.flush */
  2052. /*
  2053. * the entire input stream is consumed
  2054. * and there is a partial, truncated input sequence left
  2055. */
  2056. /* inject an error and continue with callback handling */
  2057. *pErrorCode=U_TRUNCATED_CHAR_FOUND;
  2058. } else {
  2059. /* input consumed */
  2060. if(flush) {
  2061. /* reset the converters without calling the callback functions */
  2062. _reset(sourceCnv, UCNV_RESET_TO_UNICODE, false);
  2063. _reset(targetCnv, UCNV_RESET_FROM_UNICODE, false);
  2064. }
  2065. /* done successfully */
  2066. break;
  2067. }
  2068. }
  2069. /*
  2070. * toUnicode(source -> pivot);
  2071. *
  2072. * For pivoting conversion; and for direct conversion for
  2073. * error callback handling, continuing partial matches
  2074. * and flushing the replay buffer.
  2075. *
  2076. * The pivot buffer is empty and reset.
  2077. */
  2078. toUArgs.target=pivotStart; /* ==*pivotTarget */
  2079. /* toUArgs.targetLimit=pivotLimit; already set before the loop */
  2080. _toUnicodeWithCallback(&toUArgs, pErrorCode);
  2081. *pivotTarget=toUArgs.target;
  2082. if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
  2083. /* pivot overflow: continue with the conversion loop */
  2084. *pErrorCode=U_ZERO_ERROR;
  2085. } else if(U_FAILURE(*pErrorCode) || (!flush && *pivotTarget==pivotStart)) {
  2086. /* conversion error, or there was nothing left to convert */
  2087. break;
  2088. }
  2089. /*
  2090. * else:
  2091. * _toUnicodeWithCallback() wrote into the pivot buffer,
  2092. * continue with fromUnicode conversion.
  2093. *
  2094. * Set the fromUnicode flush flag if we flush and if toUnicode has
  2095. * processed the end of the input.
  2096. */
  2097. if( flush && toUArgs.source==sourceLimit &&
  2098. sourceCnv->preToULength>=0 &&
  2099. sourceCnv->UCharErrorBufferLength==0
  2100. ) {
  2101. fromUArgs.flush=true;
  2102. }
  2103. }
  2104. /*
  2105. * The conversion loop is exited when one of the following is true:
  2106. * - the entire source text has been converted successfully to the target buffer
  2107. * - a target buffer overflow occurred
  2108. * - a conversion error occurred
  2109. */
  2110. *source=toUArgs.source;
  2111. *target=fromUArgs.target;
  2112. /* terminate the target buffer if possible */
  2113. if(flush && U_SUCCESS(*pErrorCode)) {
  2114. if(*target!=targetLimit) {
  2115. **target=0;
  2116. if(*pErrorCode==U_STRING_NOT_TERMINATED_WARNING) {
  2117. *pErrorCode=U_ZERO_ERROR;
  2118. }
  2119. } else {
  2120. *pErrorCode=U_STRING_NOT_TERMINATED_WARNING;
  2121. }
  2122. }
  2123. }
  2124. /* internal implementation of ucnv_convert() etc. with preflighting */
  2125. static int32_t
  2126. ucnv_internalConvert(UConverter *outConverter, UConverter *inConverter,
  2127. char *target, int32_t targetCapacity,
  2128. const char *source, int32_t sourceLength,
  2129. UErrorCode *pErrorCode) {
  2130. char16_t pivotBuffer[CHUNK_SIZE];
  2131. char16_t *pivot, *pivot2;
  2132. char *myTarget;
  2133. const char *sourceLimit;
  2134. const char *targetLimit;
  2135. int32_t targetLength=0;
  2136. /* set up */
  2137. if(sourceLength<0) {
  2138. sourceLimit=uprv_strchr(source, 0);
  2139. } else {
  2140. sourceLimit=source+sourceLength;
  2141. }
  2142. /* if there is no input data, we're done */
  2143. if(source==sourceLimit) {
  2144. return u_terminateChars(target, targetCapacity, 0, pErrorCode);
  2145. }
  2146. pivot=pivot2=pivotBuffer;
  2147. myTarget=target;
  2148. targetLength=0;
  2149. if(targetCapacity>0) {
  2150. /* perform real conversion */
  2151. targetLimit=target+targetCapacity;
  2152. ucnv_convertEx(outConverter, inConverter,
  2153. &myTarget, targetLimit,
  2154. &source, sourceLimit,
  2155. pivotBuffer, &pivot, &pivot2, pivotBuffer+CHUNK_SIZE,
  2156. false,
  2157. true,
  2158. pErrorCode);
  2159. targetLength=(int32_t)(myTarget-target);
  2160. }
  2161. /*
  2162. * If the output buffer is exhausted (or we are only "preflighting"), we need to stop writing
  2163. * to it but continue the conversion in order to store in targetCapacity
  2164. * the number of bytes that was required.
  2165. */
  2166. if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR || targetCapacity==0)
  2167. {
  2168. char targetBuffer[CHUNK_SIZE];
  2169. targetLimit=targetBuffer+CHUNK_SIZE;
  2170. do {
  2171. *pErrorCode=U_ZERO_ERROR;
  2172. myTarget=targetBuffer;
  2173. ucnv_convertEx(outConverter, inConverter,
  2174. &myTarget, targetLimit,
  2175. &source, sourceLimit,
  2176. pivotBuffer, &pivot, &pivot2, pivotBuffer+CHUNK_SIZE,
  2177. false,
  2178. true,
  2179. pErrorCode);
  2180. targetLength+=(int32_t)(myTarget-targetBuffer);
  2181. } while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR);
  2182. /* done with preflighting, set warnings and errors as appropriate */
  2183. return u_terminateChars(target, targetCapacity, targetLength, pErrorCode);
  2184. }
  2185. /* no need to call u_terminateChars() because ucnv_convertEx() took care of that */
  2186. return targetLength;
  2187. }
  2188. U_CAPI int32_t U_EXPORT2
  2189. ucnv_convert(const char *toConverterName, const char *fromConverterName,
  2190. char *target, int32_t targetCapacity,
  2191. const char *source, int32_t sourceLength,
  2192. UErrorCode *pErrorCode) {
  2193. UConverter in, out; /* stack-allocated */
  2194. UConverter *inConverter, *outConverter;
  2195. int32_t targetLength;
  2196. if(pErrorCode==nullptr || U_FAILURE(*pErrorCode)) {
  2197. return 0;
  2198. }
  2199. if( source==nullptr || sourceLength<-1 ||
  2200. targetCapacity<0 || (targetCapacity>0 && target==nullptr)
  2201. ) {
  2202. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  2203. return 0;
  2204. }
  2205. /* if there is no input data, we're done */
  2206. if(sourceLength==0 || (sourceLength<0 && *source==0)) {
  2207. return u_terminateChars(target, targetCapacity, 0, pErrorCode);
  2208. }
  2209. /* create the converters */
  2210. inConverter=ucnv_createConverter(&in, fromConverterName, pErrorCode);
  2211. if(U_FAILURE(*pErrorCode)) {
  2212. return 0;
  2213. }
  2214. outConverter=ucnv_createConverter(&out, toConverterName, pErrorCode);
  2215. if(U_FAILURE(*pErrorCode)) {
  2216. ucnv_close(inConverter);
  2217. return 0;
  2218. }
  2219. targetLength=ucnv_internalConvert(outConverter, inConverter,
  2220. target, targetCapacity,
  2221. source, sourceLength,
  2222. pErrorCode);
  2223. ucnv_close(inConverter);
  2224. ucnv_close(outConverter);
  2225. return targetLength;
  2226. }
  2227. /* @internal */
  2228. static int32_t
  2229. ucnv_convertAlgorithmic(UBool convertToAlgorithmic,
  2230. UConverterType algorithmicType,
  2231. UConverter *cnv,
  2232. char *target, int32_t targetCapacity,
  2233. const char *source, int32_t sourceLength,
  2234. UErrorCode *pErrorCode) {
  2235. UConverter algoConverterStatic; /* stack-allocated */
  2236. UConverter *algoConverter, *to, *from;
  2237. int32_t targetLength;
  2238. if(pErrorCode==nullptr || U_FAILURE(*pErrorCode)) {
  2239. return 0;
  2240. }
  2241. if( cnv==nullptr || source==nullptr || sourceLength<-1 ||
  2242. targetCapacity<0 || (targetCapacity>0 && target==nullptr)
  2243. ) {
  2244. *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
  2245. return 0;
  2246. }
  2247. /* if there is no input data, we're done */
  2248. if(sourceLength==0 || (sourceLength<0 && *source==0)) {
  2249. return u_terminateChars(target, targetCapacity, 0, pErrorCode);
  2250. }
  2251. /* create the algorithmic converter */
  2252. algoConverter=ucnv_createAlgorithmicConverter(&algoConverterStatic, algorithmicType,
  2253. "", 0, pErrorCode);
  2254. if(U_FAILURE(*pErrorCode)) {
  2255. return 0;
  2256. }
  2257. /* reset the other converter */
  2258. if(convertToAlgorithmic) {
  2259. /* cnv->Unicode->algo */
  2260. ucnv_resetToUnicode(cnv);
  2261. to=algoConverter;
  2262. from=cnv;
  2263. } else {
  2264. /* algo->Unicode->cnv */
  2265. ucnv_resetFromUnicode(cnv);
  2266. from=algoConverter;
  2267. to=cnv;
  2268. }
  2269. targetLength=ucnv_internalConvert(to, from,
  2270. target, targetCapacity,
  2271. source, sourceLength,
  2272. pErrorCode);
  2273. ucnv_close(algoConverter);
  2274. return targetLength;
  2275. }
  2276. U_CAPI int32_t U_EXPORT2
  2277. ucnv_toAlgorithmic(UConverterType algorithmicType,
  2278. UConverter *cnv,
  2279. char *target, int32_t targetCapacity,
  2280. const char *source, int32_t sourceLength,
  2281. UErrorCode *pErrorCode) {
  2282. return ucnv_convertAlgorithmic(true, algorithmicType, cnv,
  2283. target, targetCapacity,
  2284. source, sourceLength,
  2285. pErrorCode);
  2286. }
  2287. U_CAPI int32_t U_EXPORT2
  2288. ucnv_fromAlgorithmic(UConverter *cnv,
  2289. UConverterType algorithmicType,
  2290. char *target, int32_t targetCapacity,
  2291. const char *source, int32_t sourceLength,
  2292. UErrorCode *pErrorCode) UPRV_NO_SANITIZE_UNDEFINED {
  2293. if(algorithmicType<0 || UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES<=algorithmicType) {
  2294. *pErrorCode = U_ILLEGAL_ARGUMENT_ERROR;
  2295. return 0;
  2296. }
  2297. return ucnv_convertAlgorithmic(false, algorithmicType, cnv,
  2298. target, targetCapacity,
  2299. source, sourceLength,
  2300. pErrorCode);
  2301. }
  2302. U_CAPI UConverterType U_EXPORT2
  2303. ucnv_getType(const UConverter* converter)
  2304. {
  2305. int8_t type = converter->sharedData->staticData->conversionType;
  2306. #if !UCONFIG_NO_LEGACY_CONVERSION
  2307. if(type == UCNV_MBCS) {
  2308. return ucnv_MBCSGetType(converter);
  2309. }
  2310. #endif
  2311. return (UConverterType)type;
  2312. }
  2313. U_CAPI void U_EXPORT2
  2314. ucnv_getStarters(const UConverter* converter,
  2315. UBool starters[256],
  2316. UErrorCode* err)
  2317. {
  2318. if (err == nullptr || U_FAILURE(*err)) {
  2319. return;
  2320. }
  2321. if(converter->sharedData->impl->getStarters != nullptr) {
  2322. converter->sharedData->impl->getStarters(converter, starters, err);
  2323. } else {
  2324. *err = U_ILLEGAL_ARGUMENT_ERROR;
  2325. }
  2326. }
  2327. static const UAmbiguousConverter *ucnv_getAmbiguous(const UConverter *cnv)
  2328. {
  2329. UErrorCode errorCode;
  2330. const char *name;
  2331. int32_t i;
  2332. if(cnv==nullptr) {
  2333. return nullptr;
  2334. }
  2335. errorCode=U_ZERO_ERROR;
  2336. name=ucnv_getName(cnv, &errorCode);
  2337. if(U_FAILURE(errorCode)) {
  2338. return nullptr;
  2339. }
  2340. for(i=0; i<UPRV_LENGTHOF(ambiguousConverters); ++i)
  2341. {
  2342. if(0==uprv_strcmp(name, ambiguousConverters[i].name))
  2343. {
  2344. return ambiguousConverters+i;
  2345. }
  2346. }
  2347. return nullptr;
  2348. }
  2349. U_CAPI void U_EXPORT2
  2350. ucnv_fixFileSeparator(const UConverter *cnv,
  2351. char16_t* source,
  2352. int32_t sourceLength) {
  2353. const UAmbiguousConverter *a;
  2354. int32_t i;
  2355. char16_t variant5c;
  2356. if(cnv==nullptr || source==nullptr || sourceLength<=0 || (a=ucnv_getAmbiguous(cnv))==nullptr)
  2357. {
  2358. return;
  2359. }
  2360. variant5c=a->variant5c;
  2361. for(i=0; i<sourceLength; ++i) {
  2362. if(source[i]==variant5c) {
  2363. source[i]=0x5c;
  2364. }
  2365. }
  2366. }
  2367. U_CAPI UBool U_EXPORT2
  2368. ucnv_isAmbiguous(const UConverter *cnv) {
  2369. return (UBool)(ucnv_getAmbiguous(cnv)!=nullptr);
  2370. }
  2371. U_CAPI void U_EXPORT2
  2372. ucnv_setFallback(UConverter *cnv, UBool usesFallback)
  2373. {
  2374. cnv->useFallback = usesFallback;
  2375. }
  2376. U_CAPI UBool U_EXPORT2
  2377. ucnv_usesFallback(const UConverter *cnv)
  2378. {
  2379. return cnv->useFallback;
  2380. }
  2381. U_CAPI void U_EXPORT2
  2382. ucnv_getInvalidChars (const UConverter * converter,
  2383. char *errBytes,
  2384. int8_t * len,
  2385. UErrorCode * err)
  2386. {
  2387. if (err == nullptr || U_FAILURE(*err))
  2388. {
  2389. return;
  2390. }
  2391. if (len == nullptr || errBytes == nullptr || converter == nullptr)
  2392. {
  2393. *err = U_ILLEGAL_ARGUMENT_ERROR;
  2394. return;
  2395. }
  2396. if (*len < converter->invalidCharLength)
  2397. {
  2398. *err = U_INDEX_OUTOFBOUNDS_ERROR;
  2399. return;
  2400. }
  2401. if ((*len = converter->invalidCharLength) > 0)
  2402. {
  2403. uprv_memcpy (errBytes, converter->invalidCharBuffer, *len);
  2404. }
  2405. }
  2406. U_CAPI void U_EXPORT2
  2407. ucnv_getInvalidUChars (const UConverter * converter,
  2408. char16_t *errChars,
  2409. int8_t * len,
  2410. UErrorCode * err)
  2411. {
  2412. if (err == nullptr || U_FAILURE(*err))
  2413. {
  2414. return;
  2415. }
  2416. if (len == nullptr || errChars == nullptr || converter == nullptr)
  2417. {
  2418. *err = U_ILLEGAL_ARGUMENT_ERROR;
  2419. return;
  2420. }
  2421. if (*len < converter->invalidUCharLength)
  2422. {
  2423. *err = U_INDEX_OUTOFBOUNDS_ERROR;
  2424. return;
  2425. }
  2426. if ((*len = converter->invalidUCharLength) > 0)
  2427. {
  2428. u_memcpy (errChars, converter->invalidUCharBuffer, *len);
  2429. }
  2430. }
  2431. #define SIG_MAX_LEN 5
  2432. U_CAPI const char* U_EXPORT2
  2433. ucnv_detectUnicodeSignature( const char* source,
  2434. int32_t sourceLength,
  2435. int32_t* signatureLength,
  2436. UErrorCode* pErrorCode) {
  2437. int32_t dummy;
  2438. /* initial 0xa5 bytes: make sure that if we read <SIG_MAX_LEN
  2439. * bytes we don't misdetect something
  2440. */
  2441. char start[SIG_MAX_LEN]={ '\xa5', '\xa5', '\xa5', '\xa5', '\xa5' };
  2442. int i = 0;
  2443. if((pErrorCode==nullptr) || U_FAILURE(*pErrorCode)){
  2444. return nullptr;
  2445. }
  2446. if(source == nullptr || sourceLength < -1){
  2447. *pErrorCode = U_ILLEGAL_ARGUMENT_ERROR;
  2448. return nullptr;
  2449. }
  2450. if(signatureLength == nullptr) {
  2451. signatureLength = &dummy;
  2452. }
  2453. if(sourceLength==-1){
  2454. sourceLength=(int32_t)uprv_strlen(source);
  2455. }
  2456. while(i<sourceLength&& i<SIG_MAX_LEN){
  2457. start[i]=source[i];
  2458. i++;
  2459. }
  2460. if(start[0] == '\xFE' && start[1] == '\xFF') {
  2461. *signatureLength=2;
  2462. return "UTF-16BE";
  2463. } else if(start[0] == '\xFF' && start[1] == '\xFE') {
  2464. if(start[2] == '\x00' && start[3] =='\x00') {
  2465. *signatureLength=4;
  2466. return "UTF-32LE";
  2467. } else {
  2468. *signatureLength=2;
  2469. return "UTF-16LE";
  2470. }
  2471. } else if(start[0] == '\xEF' && start[1] == '\xBB' && start[2] == '\xBF') {
  2472. *signatureLength=3;
  2473. return "UTF-8";
  2474. } else if(start[0] == '\x00' && start[1] == '\x00' &&
  2475. start[2] == '\xFE' && start[3]=='\xFF') {
  2476. *signatureLength=4;
  2477. return "UTF-32BE";
  2478. } else if(start[0] == '\x0E' && start[1] == '\xFE' && start[2] == '\xFF') {
  2479. *signatureLength=3;
  2480. return "SCSU";
  2481. } else if(start[0] == '\xFB' && start[1] == '\xEE' && start[2] == '\x28') {
  2482. *signatureLength=3;
  2483. return "BOCU-1";
  2484. } else if(start[0] == '\x2B' && start[1] == '\x2F' && start[2] == '\x76') {
  2485. /*
  2486. * UTF-7: Initial U+FEFF is encoded as +/v8 or +/v9 or +/v+ or +/v/
  2487. * depending on the second UTF-16 code unit.
  2488. * Detect the entire, closed Unicode mode sequence +/v8- for only U+FEFF
  2489. * if it occurs.
  2490. *
  2491. * So far we have +/v
  2492. */
  2493. if(start[3] == '\x38' && start[4] == '\x2D') {
  2494. /* 5 bytes +/v8- */
  2495. *signatureLength=5;
  2496. return "UTF-7";
  2497. } else if(start[3] == '\x38' || start[3] == '\x39' || start[3] == '\x2B' || start[3] == '\x2F') {
  2498. /* 4 bytes +/v8 or +/v9 or +/v+ or +/v/ */
  2499. *signatureLength=4;
  2500. return "UTF-7";
  2501. }
  2502. }else if(start[0]=='\xDD' && start[1]== '\x73'&& start[2]=='\x66' && start[3]=='\x73'){
  2503. *signatureLength=4;
  2504. return "UTF-EBCDIC";
  2505. }
  2506. /* no known Unicode signature byte sequence recognized */
  2507. *signatureLength=0;
  2508. return nullptr;
  2509. }
  2510. U_CAPI int32_t U_EXPORT2
  2511. ucnv_fromUCountPending(const UConverter* cnv, UErrorCode* status)
  2512. {
  2513. if(status == nullptr || U_FAILURE(*status)){
  2514. return -1;
  2515. }
  2516. if(cnv == nullptr){
  2517. *status = U_ILLEGAL_ARGUMENT_ERROR;
  2518. return -1;
  2519. }
  2520. if(cnv->preFromUFirstCP >= 0){
  2521. return U16_LENGTH(cnv->preFromUFirstCP)+cnv->preFromULength ;
  2522. }else if(cnv->preFromULength < 0){
  2523. return -cnv->preFromULength ;
  2524. }else if(cnv->fromUChar32 > 0){
  2525. return 1;
  2526. }
  2527. return 0;
  2528. }
  2529. U_CAPI int32_t U_EXPORT2
  2530. ucnv_toUCountPending(const UConverter* cnv, UErrorCode* status){
  2531. if(status == nullptr || U_FAILURE(*status)){
  2532. return -1;
  2533. }
  2534. if(cnv == nullptr){
  2535. *status = U_ILLEGAL_ARGUMENT_ERROR;
  2536. return -1;
  2537. }
  2538. if(cnv->preToULength > 0){
  2539. return cnv->preToULength ;
  2540. }else if(cnv->preToULength < 0){
  2541. return -cnv->preToULength;
  2542. }else if(cnv->toULength > 0){
  2543. return cnv->toULength;
  2544. }
  2545. return 0;
  2546. }
  2547. U_CAPI UBool U_EXPORT2
  2548. ucnv_isFixedWidth(UConverter *cnv, UErrorCode *status){
  2549. if (U_FAILURE(*status)) {
  2550. return false;
  2551. }
  2552. if (cnv == nullptr) {
  2553. *status = U_ILLEGAL_ARGUMENT_ERROR;
  2554. return false;
  2555. }
  2556. switch (ucnv_getType(cnv)) {
  2557. case UCNV_SBCS:
  2558. case UCNV_DBCS:
  2559. case UCNV_UTF32_BigEndian:
  2560. case UCNV_UTF32_LittleEndian:
  2561. case UCNV_UTF32:
  2562. case UCNV_US_ASCII:
  2563. return true;
  2564. default:
  2565. return false;
  2566. }
  2567. }
  2568. #endif
  2569. /*
  2570. * Hey, Emacs, please set the following:
  2571. *
  2572. * Local Variables:
  2573. * indent-tabs-mode: nil
  2574. * End:
  2575. *
  2576. */