jstring.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <stdarg.h>
  17. #include <assert.h>
  18. #include <string.h>
  19. #include <ctype.h>
  20. #include <time.h>
  21. #include <math.h>
  22. #include "jstring.hpp"
  23. #include "jexcept.hpp"
  24. #include "jhash.hpp"
  25. #include "jlog.hpp"
  26. #include "jfile.hpp"
  27. #include "jdebug.hpp"
  28. #include "jutil.hpp"
  29. #include "junicode.hpp"
  30. #define DOUBLE_FORMAT "%.16g"
  31. #define FLOAT_FORMAT "%.7g"
  32. #ifndef va_copy
  33. /* WARNING - DANGER - ASSUMES TYPICAL STACK MACHINE */
  34. #define va_copy(dst, src) ((void)((dst) = (src)))
  35. #endif
  36. static const char * TheNullStr = "";
  37. #define FIRST_CHUNK_SIZE 8
  38. #define DOUBLE_LIMIT 0x100000 // must be a power of 2
  39. #define DETACH_GRANULARITY 16
  40. //===========================================================================
  41. StringBuffer::StringBuffer()
  42. {
  43. init();
  44. }
  45. #if 0
  46. StringBuffer::StringBuffer(int initial)
  47. {
  48. init();
  49. ensureCapacity(initial);
  50. }
  51. #endif
  52. StringBuffer::StringBuffer(String & value)
  53. {
  54. init();
  55. append(value);
  56. }
  57. StringBuffer::StringBuffer(const char *value)
  58. {
  59. init();
  60. append(value);
  61. }
  62. StringBuffer::StringBuffer(char value)
  63. {
  64. init();
  65. append(value);
  66. }
  67. StringBuffer::StringBuffer(unsigned len, const char *value)
  68. {
  69. init();
  70. append(len, value);
  71. }
  72. StringBuffer::StringBuffer(const StringBuffer & value)
  73. {
  74. init();
  75. append(value);
  76. }
  77. StringBuffer::StringBuffer(StringBuffer && value)
  78. {
  79. init();
  80. swapWith(value);
  81. }
  82. StringBuffer::StringBuffer(bool useInternal)
  83. {
  84. if (useInternal)
  85. init();
  86. else
  87. initNoInternal();
  88. }
  89. StringBuffer::~StringBuffer()
  90. {
  91. freeBuffer();
  92. }
  93. void StringBuffer::freeBuffer()
  94. {
  95. if (buffer != internalBuffer)
  96. free(buffer);
  97. }
  98. void StringBuffer::setBuffer(size32_t buffLen, char * newBuff, size32_t strLen)
  99. {
  100. assertex(newBuff);
  101. assertex(buffLen>0 && strLen<buffLen);
  102. freeBuffer();
  103. buffer = newBuff;
  104. maxLen = buffLen;
  105. curLen = strLen;
  106. }
  107. void StringBuffer::_realloc(size32_t newLen)
  108. {
  109. if (newLen >= maxLen)
  110. {
  111. size32_t newMax = maxLen;
  112. if (newMax == 0)
  113. newMax = FIRST_CHUNK_SIZE;
  114. if (newLen > DOUBLE_LIMIT)
  115. {
  116. newMax = (newLen + DOUBLE_LIMIT) & ~(DOUBLE_LIMIT-1);
  117. if (newLen >= newMax)
  118. throw MakeStringException(MSGAUD_operator, -1, "StringBuffer::_realloc: Request for %d bytes oldMax = %d", newLen, maxLen);
  119. }
  120. else
  121. {
  122. while (newLen >= newMax)
  123. newMax += newMax;
  124. }
  125. char * newStr;
  126. char * originalBuffer = (buffer == internalBuffer) ? NULL : buffer;
  127. if (!newMax || !(newStr=(char *)realloc(originalBuffer, newMax)))
  128. {
  129. DBGLOG("StringBuffer::_realloc: Failed to realloc = %d, oldMax = %d", newMax, maxLen);
  130. PrintStackReport();
  131. PrintMemoryReport();
  132. throw MakeStringException(MSGAUD_operator, -1, "StringBuffer::_realloc: Failed to realloc = %d, oldMax = %d", newMax, maxLen);
  133. }
  134. if (useInternal())
  135. memcpy(newStr, internalBuffer, curLen);
  136. buffer = newStr;
  137. maxLen = newMax;
  138. }
  139. }
  140. char * StringBuffer::detach()
  141. {
  142. dbgassertex(buffer);
  143. char * result;
  144. if (buffer == internalBuffer)
  145. {
  146. result = (char *)malloc(curLen+1);
  147. memcpy(result, buffer, curLen);
  148. }
  149. else
  150. {
  151. if (maxLen>curLen+1+DETACH_GRANULARITY)
  152. buffer = (char *)realloc(buffer,curLen+1); // shrink
  153. result = buffer;
  154. }
  155. result[curLen] = '\0'; // There is always room for this null
  156. init();
  157. return result;
  158. }
  159. StringBuffer & StringBuffer::append(char value)
  160. {
  161. ensureCapacity(1);
  162. buffer[curLen] = value;
  163. ++curLen;
  164. return *this;
  165. }
  166. StringBuffer & StringBuffer::append(unsigned char value)
  167. {
  168. ensureCapacity(1);
  169. buffer[curLen] = value;
  170. ++curLen;
  171. return *this;
  172. }
  173. StringBuffer & StringBuffer::append(const char * value)
  174. {
  175. if (value)
  176. {
  177. size32_t SourceLen = (size32_t)::strlen(value);
  178. ensureCapacity(SourceLen);
  179. memcpy(buffer + curLen, value, SourceLen);
  180. curLen += SourceLen;
  181. }
  182. return *this;
  183. }
  184. StringBuffer & StringBuffer::append(size_t len, const char * value)
  185. {
  186. if (len)
  187. {
  188. unsigned truncLen = (unsigned)len;
  189. assertex(truncLen == len); // MORE: StringBuffer should use size_t throughout
  190. ensureCapacity(truncLen);
  191. memcpy(buffer + curLen, value, truncLen);
  192. curLen += truncLen;
  193. }
  194. return *this;
  195. }
  196. StringBuffer & StringBuffer::append(const unsigned char * value)
  197. {
  198. return append((const char *) value);
  199. }
  200. StringBuffer & StringBuffer::append(const char * value, int offset, int len)
  201. {
  202. ensureCapacity(len);
  203. memcpy(buffer + curLen, value+offset, len);
  204. curLen += len;
  205. return *this;
  206. }
  207. StringBuffer & StringBuffer::append(const IAtom * value)
  208. {
  209. if (value)
  210. append(value->queryStr());
  211. return *this;
  212. }
  213. StringBuffer & StringBuffer::append(double value)
  214. {
  215. int len = length();
  216. int newlen = appendf(DOUBLE_FORMAT, value).length();
  217. while (len < newlen)
  218. {
  219. switch (charAt(len))
  220. {
  221. case '.':
  222. case 'E':
  223. case 'e':
  224. case 'N': // Not a number/infinity
  225. case 'n':
  226. return *this;
  227. }
  228. len++;
  229. }
  230. return append(".0");
  231. }
  232. StringBuffer & StringBuffer::append(float value)
  233. {
  234. int len = length();
  235. int newlen = appendf(FLOAT_FORMAT, value).length();
  236. while (len < newlen)
  237. {
  238. switch (charAt(len))
  239. {
  240. case '.':
  241. case 'E':
  242. case 'e':
  243. case 'N': // Not a number/infinity
  244. case 'n':
  245. return *this;
  246. }
  247. len++;
  248. }
  249. return append(".0");
  250. }
  251. StringBuffer & StringBuffer::append(int value)
  252. {
  253. char temp[12];
  254. unsigned written = numtostr(temp, value);
  255. return append(written, temp);
  256. }
  257. StringBuffer & StringBuffer::append(unsigned value)
  258. {
  259. char temp[12];
  260. unsigned written = numtostr(temp, value);
  261. return append(written, temp);
  262. }
  263. StringBuffer & StringBuffer::appendlong(long value)
  264. {
  265. char temp[24];
  266. unsigned written = numtostr(temp, value);
  267. return append(written, temp);
  268. }
  269. StringBuffer & StringBuffer::appendulong(unsigned long value)
  270. {
  271. char temp[24];
  272. unsigned written = numtostr(temp, value);
  273. return append(written, temp);
  274. }
  275. StringBuffer & StringBuffer::append(__int64 value)
  276. {
  277. char temp[24];
  278. unsigned written = numtostr(temp, value);
  279. return append(written, temp);
  280. }
  281. StringBuffer & StringBuffer::append(unsigned __int64 value)
  282. {
  283. char temp[24];
  284. unsigned written = numtostr(temp, value);
  285. return append(written, temp);
  286. }
  287. StringBuffer & StringBuffer::append(const String & value)
  288. {
  289. size32_t SourceLen = value.length();
  290. ensureCapacity(SourceLen);
  291. value.getChars(0, SourceLen, buffer, curLen);
  292. curLen += SourceLen;
  293. return *this;
  294. }
  295. StringBuffer & StringBuffer::append(const IStringVal & value)
  296. {
  297. return append(value.str());
  298. }
  299. StringBuffer & StringBuffer::append(const IStringVal * value)
  300. {
  301. if (value)
  302. return append(value->str());
  303. else
  304. return *this;
  305. }
  306. StringBuffer & StringBuffer::append(const StringBuffer & value)
  307. {
  308. size32_t SourceLen = value.length();
  309. ensureCapacity(SourceLen);
  310. value.getChars(0, SourceLen, buffer + curLen);
  311. curLen += SourceLen;
  312. return *this;
  313. }
  314. StringBuffer & StringBuffer::appendf(const char *format, ...)
  315. {
  316. va_list args;
  317. va_start(args, format);
  318. valist_appendf(format, args);
  319. va_end(args);
  320. return *this;
  321. }
  322. StringBuffer & StringBuffer::appendLower(unsigned len, const char * value)
  323. {
  324. if (len)
  325. {
  326. ensureCapacity(len);
  327. const byte * from = reinterpret_cast<const byte *>(value);
  328. for (unsigned i = 0; i < len; i++)
  329. buffer[curLen + i] = tolower(from[i]);
  330. curLen += len;
  331. }
  332. return *this;
  333. }
  334. StringBuffer & StringBuffer::setf(const char *format, ...)
  335. {
  336. clear();
  337. va_list args;
  338. va_start(args, format);
  339. valist_appendf(format, args);
  340. va_end(args);
  341. return *this;
  342. }
  343. StringBuffer & StringBuffer::limited_valist_appendf(unsigned szLimit, const char *format, va_list args)
  344. {
  345. #define BUF_SIZE 1024
  346. #define MAX_BUF_SIZE (1024*1024) // limit buffer size to 1MB when doubling
  347. // handle string that is bigger that BUF_SIZE bytes
  348. unsigned size = (0 == szLimit||szLimit>BUF_SIZE)?BUF_SIZE:szLimit;
  349. int len;
  350. va_list args2;
  351. va_copy(args2, args);
  352. try { ensureCapacity(size); }
  353. catch (IException *e)
  354. {
  355. StringBuffer eMsg;
  356. IException *e2 = MakeStringException(-1, "StringBuffer::valist_appendf(\"%s\"): vsnprintf failed or result exceeds limit (%d): %s", format, size, e->errorMessage(eMsg).str());
  357. e->Release();
  358. throw e2;
  359. }
  360. len = _vsnprintf(buffer+curLen,size,format,args);
  361. if (len >= 0)
  362. {
  363. if ((unsigned)len >= size)
  364. {
  365. if (szLimit && (unsigned)len >= szLimit)
  366. {
  367. if ((unsigned)len>szLimit)
  368. {
  369. len = size;
  370. if (len>3) memcpy(buffer+len-3, "...", 3);
  371. }
  372. }
  373. else
  374. {
  375. ensureCapacity(len);
  376. // no need for _vsnprintf since the buffer is already made big enough
  377. vsprintf(buffer+curLen,format,args2);
  378. }
  379. }
  380. }
  381. else if (size == szLimit)
  382. {
  383. len = size;
  384. if (len>3) memcpy(buffer+len-3, "...", 3);
  385. }
  386. else
  387. {
  388. size = BUF_SIZE * 2;
  389. for (;;)
  390. {
  391. if (0 != szLimit && size>szLimit) size = szLimit; // if so, will be last attempt
  392. if (size>MAX_BUF_SIZE)
  393. {
  394. WARNLOG("StringBuffer::valist_appendf(\"%s\"): vsnprintf exceeds limit (%d)", format, size);
  395. size = szLimit = MAX_BUF_SIZE;
  396. }
  397. try { ensureCapacity(size); }
  398. catch (IException *e)
  399. {
  400. StringBuffer eMsg;
  401. IException *e2 = MakeStringException(-1, "StringBuffer::valist_appendf(\"%s\"): vsnprintf failed (%d): %s", format, size, e->errorMessage(eMsg).str());
  402. e->Release();
  403. throw e2;
  404. }
  405. va_list args3;
  406. va_copy(args3, args2);
  407. len = _vsnprintf(buffer+curLen,size,format,args3);
  408. va_end(args3);
  409. if (len>=0) // NB: len>size not possible, 1st _vsnprintf would have handled.
  410. break;
  411. if (size == szLimit)
  412. {
  413. len = size;
  414. if (len>3) memcpy(buffer+len-3, "...", 3);
  415. break;
  416. }
  417. size <<= 1;
  418. }
  419. }
  420. va_end(args2);
  421. curLen += len;
  422. return *this;
  423. }
  424. StringBuffer & StringBuffer::appendN(size32_t count, char fill)
  425. {
  426. ensureCapacity(count);
  427. memset(buffer+curLen, fill, count);
  428. curLen += count;
  429. return *this;
  430. }
  431. void StringBuffer::setLength(unsigned len)
  432. {
  433. if (len > curLen)
  434. {
  435. ensureCapacity(len-curLen);
  436. }
  437. curLen = len;
  438. }
  439. size32_t StringBuffer::lengthUtf8() const
  440. {
  441. size32_t chars = 0;
  442. for (unsigned offset=0; offset < curLen; offset += readUtf8Size(buffer+offset))
  443. chars++;
  444. return chars;
  445. }
  446. char * StringBuffer::reserve(size32_t size)
  447. {
  448. ensureCapacity(size);
  449. char *ret = buffer+curLen;
  450. curLen += size;
  451. return ret;
  452. }
  453. char * StringBuffer::reserveTruncate(size32_t size)
  454. {
  455. size32_t newMax = curLen+size+1;
  456. if (buffer == internalBuffer)
  457. {
  458. if (newMax > InternalBufferSize)
  459. {
  460. char * newStr = (char *)malloc(newMax);
  461. if (!newStr)
  462. throw MakeStringException(-1, "StringBuffer::_realloc: Failed to realloc newMax = %d, oldMax = %d", newMax, maxLen);
  463. memcpy(newStr, buffer, curLen);
  464. buffer = newStr;
  465. maxLen = newMax;
  466. }
  467. }
  468. else if (newMax != maxLen)
  469. {
  470. char * newStr = (char *) realloc(buffer, newMax);
  471. if (!newStr)
  472. throw MakeStringException(-1, "StringBuffer::_realloc: Failed to realloc newMax = %d, oldMax = %d", newMax, maxLen);
  473. buffer = newStr;
  474. maxLen = newMax;
  475. }
  476. char *ret = buffer+curLen;
  477. curLen += size;
  478. return ret;
  479. }
  480. void StringBuffer::swapWith(StringBuffer &other)
  481. {
  482. //Swap max
  483. size_t tempMax = maxLen;
  484. maxLen = other.maxLen;
  485. other.maxLen = tempMax;
  486. //Swap lengths
  487. size32_t thisLen = curLen;
  488. size32_t otherLen = other.curLen;
  489. curLen = otherLen;
  490. other.curLen = thisLen;
  491. //Swap buffers
  492. char * thisBuffer = buffer;
  493. char * otherBuffer = other.buffer;
  494. if (useInternal())
  495. {
  496. if (other.useInternal())
  497. {
  498. //NOTE: The c++ compiler can generate better code for the fixed size memcpy than it can
  499. // if only the required characters are copied.
  500. char temp[InternalBufferSize];
  501. memcpy(temp, thisBuffer, InternalBufferSize);
  502. memcpy(thisBuffer, otherBuffer, InternalBufferSize);
  503. memcpy(otherBuffer, temp, InternalBufferSize);
  504. //buffers already point in the correct place
  505. }
  506. else
  507. {
  508. memcpy(other.internalBuffer, thisBuffer, InternalBufferSize);
  509. buffer = otherBuffer;
  510. other.buffer = other.internalBuffer;
  511. }
  512. }
  513. else
  514. {
  515. if (other.useInternal())
  516. {
  517. memcpy(internalBuffer, otherBuffer, InternalBufferSize);
  518. buffer = internalBuffer;
  519. other.buffer = thisBuffer;
  520. }
  521. else
  522. {
  523. buffer = otherBuffer;
  524. other.buffer = thisBuffer;
  525. }
  526. }
  527. }
  528. void StringBuffer::setown(StringBuffer &other)
  529. {
  530. maxLen = other.maxLen;
  531. curLen = other.curLen;
  532. freeBuffer();
  533. if (other.useInternal())
  534. {
  535. memcpy(internalBuffer, other.internalBuffer, InternalBufferSize);
  536. buffer = internalBuffer;
  537. }
  538. else
  539. {
  540. buffer = other.buffer;
  541. }
  542. other.init();
  543. }
  544. void StringBuffer::kill()
  545. {
  546. freeBuffer();
  547. init();
  548. }
  549. void StringBuffer::getChars(int srcBegin, int srcEnd, char * target) const
  550. {
  551. if (srcBegin < 0)
  552. srcBegin = 0;
  553. if ((unsigned)srcEnd > curLen)
  554. srcEnd = curLen;
  555. const int len = srcEnd - srcBegin;
  556. if (target && buffer && len > 0)
  557. memcpy(target, buffer + srcBegin, len);
  558. }
  559. void StringBuffer::_insert(unsigned offset, size32_t insertLen)
  560. {
  561. ensureCapacity(insertLen);
  562. memmove(buffer + offset + insertLen, buffer + offset, curLen - offset);
  563. curLen += insertLen;
  564. }
  565. StringBuffer & StringBuffer::insert(int offset, char value)
  566. {
  567. _insert(offset, 1);
  568. buffer[offset] = value;
  569. return *this;
  570. }
  571. StringBuffer & StringBuffer::insert(int offset, const char * value)
  572. {
  573. if (!value) return *this;
  574. unsigned len = (size32_t)strlen(value);
  575. _insert(offset, len);
  576. memcpy(buffer + offset, value, len);
  577. return *this;
  578. }
  579. StringBuffer & StringBuffer::insert(int offset, double value)
  580. {
  581. char temp[36];
  582. sprintf(temp, "%f", value);
  583. insert(offset, temp);
  584. return *this;
  585. }
  586. StringBuffer & StringBuffer::insert(int offset, float value)
  587. {
  588. return insert(offset, (double)value);
  589. }
  590. StringBuffer & StringBuffer::insert(int offset, int value)
  591. {
  592. char temp[12];
  593. numtostr(temp, value);
  594. return insert(offset, temp);
  595. }
  596. StringBuffer & StringBuffer::insert(int offset, unsigned value)
  597. {
  598. char temp[12];
  599. numtostr(temp, value);
  600. return insert(offset, temp);
  601. }
  602. #if 0
  603. StringBuffer & StringBuffer::insert(int offset, long value)
  604. {
  605. char temp[24];
  606. numtostr(temp, value);
  607. return insert(offset, temp);
  608. }
  609. #endif
  610. StringBuffer & StringBuffer::insert(int offset, __int64 value)
  611. {
  612. char temp[24];
  613. numtostr(temp, value);
  614. return insert(offset, temp);
  615. }
  616. StringBuffer & StringBuffer::insert(int offset, const String & value)
  617. {
  618. size32_t len = value.length();
  619. _insert(offset, len);
  620. value.getChars(0, len, buffer, offset);
  621. return *this;
  622. }
  623. StringBuffer & StringBuffer::insert(int offset, const StringBuffer & value)
  624. {
  625. size32_t len = value.length();
  626. _insert(offset, len);
  627. value.getChars(0, len, buffer+offset);
  628. return *this;
  629. }
  630. StringBuffer & StringBuffer::insert(int offset, const IStringVal & value)
  631. {
  632. return insert(offset, value.str());
  633. }
  634. StringBuffer & StringBuffer::insert(int offset, const IStringVal * value)
  635. {
  636. if (value)
  637. return insert(offset, value->str());
  638. else
  639. return *this;
  640. }
  641. StringBuffer & StringBuffer::newline()
  642. {
  643. return append("\n");
  644. }
  645. StringBuffer & StringBuffer::pad(unsigned count)
  646. {
  647. ensureCapacity(count);
  648. memset(buffer + curLen, ' ', count);
  649. curLen += count;
  650. return *this;
  651. }
  652. StringBuffer & StringBuffer::padTo(unsigned count)
  653. {
  654. if (curLen<count)
  655. pad(count-curLen);
  656. return *this;
  657. }
  658. StringBuffer & StringBuffer::clip()
  659. {
  660. while (curLen && isspace(buffer[curLen-1]))
  661. curLen--;
  662. return *this;
  663. }
  664. StringBuffer & StringBuffer::trim()
  665. {
  666. return clip().trimLeft();
  667. }
  668. StringBuffer & StringBuffer::trimLeft()
  669. {
  670. char *p;
  671. if (curLen==0)
  672. return *this;
  673. buffer[curLen] = 0;
  674. for(p = buffer;isspace(*p);p++)
  675. ;
  676. if (p!=buffer)
  677. {
  678. curLen -= p-buffer;
  679. memmove(buffer,p,curLen);
  680. }
  681. return *this;
  682. }
  683. StringBuffer & StringBuffer::remove(unsigned start, unsigned len)
  684. {
  685. if (start > curLen) start = curLen;
  686. if (start + len > curLen) len = curLen - start;
  687. unsigned start2 = start + len;
  688. memmove(buffer + start, buffer + start2, curLen - start2);
  689. setLength(curLen - len);
  690. return *this;
  691. }
  692. StringBuffer &StringBuffer::reverse()
  693. {
  694. unsigned max = curLen/2;
  695. char * end = buffer + curLen;
  696. unsigned idx;
  697. for (idx = 0; idx < max; idx++)
  698. {
  699. char temp = buffer[idx];
  700. end--;
  701. buffer[idx] = *end;
  702. *end = temp;
  703. }
  704. return *this;
  705. }
  706. MemoryBuffer & StringBuffer::deserialize(MemoryBuffer & in)
  707. {
  708. unsigned len;
  709. in.read(len);
  710. append(len, (const char *)in.readDirect(len));
  711. return in;
  712. }
  713. MemoryBuffer & StringBuffer::serialize(MemoryBuffer & out) const
  714. {
  715. return out.append(curLen).append(curLen, buffer);
  716. }
  717. StringBuffer &StringBuffer::loadFile(const char *filename, bool binaryMode)
  718. {
  719. FILE *in = fopen(filename, binaryMode?"rb":"rt");
  720. if (in)
  721. {
  722. char buffer[1024];
  723. int bytes;
  724. for (;;)
  725. {
  726. bytes = (size32_t)fread(buffer, 1, sizeof(buffer), in);
  727. if (!bytes)
  728. break;
  729. append(buffer, 0, bytes);
  730. }
  731. fclose(in);
  732. return *this;
  733. }
  734. else
  735. throw MakeStringException(errno, "File %s could not be opened", filename);
  736. }
  737. StringBuffer & StringBuffer::loadFile(IFile* f)
  738. {
  739. if(!f)
  740. return *this;
  741. Owned<IFileIO> io = f->open(IFOread);
  742. if(!io)
  743. throw MakeStringException(errno, "file %s could not be opened for reading", f->queryFilename());
  744. char buf[2048];
  745. const unsigned requestedSize = sizeof(buf);
  746. offset_t pos = 0;
  747. for (;;)
  748. {
  749. size32_t len = io->read(pos, requestedSize, buf);
  750. if (len == 0)
  751. break;
  752. append(len, buf);
  753. pos += len;
  754. if (len != requestedSize)
  755. break;
  756. }
  757. return *this;
  758. }
  759. void StringBuffer::setCharAt(unsigned offset, char value)
  760. {
  761. if (offset < curLen)
  762. buffer[offset] = value;
  763. }
  764. StringBuffer & StringBuffer::toLowerCase()
  765. {
  766. size32_t l = curLen;
  767. for (size32_t i = 0; i < l; i++)
  768. {
  769. if (isupper(buffer[i]))
  770. buffer[i] = tolower(buffer[i]);
  771. }
  772. return *this;
  773. }
  774. StringBuffer & StringBuffer::toUpperCase()
  775. {
  776. size32_t l = curLen;
  777. for (size32_t i = 0; i < l; i++)
  778. {
  779. if (islower(buffer[i]))
  780. buffer[i] = toupper(buffer[i]);
  781. }
  782. return *this;
  783. }
  784. StringBuffer & StringBuffer::replace(char oldChar, char newChar)
  785. {
  786. size32_t l = curLen;
  787. for (size32_t i = 0; i < l; i++)
  788. {
  789. if (buffer[i] == oldChar)
  790. {
  791. buffer[i] = newChar;
  792. if (newChar == '\0')
  793. {
  794. curLen = i;
  795. break;
  796. }
  797. }
  798. }
  799. return *this;
  800. }
  801. // Copy source to result, replacing all occurrences of "oldStr" with "newStr"
  802. StringBuffer &replaceString(StringBuffer & result, size32_t lenSource, const char *source, size32_t lenOldStr, const char* oldStr, size32_t lenNewStr, const char* newStr)
  803. {
  804. if (lenSource)
  805. {
  806. size32_t left = lenSource;
  807. while (left >= lenOldStr)
  808. {
  809. if (memcmp(source, oldStr, lenOldStr)==0)
  810. {
  811. result.append(lenNewStr, newStr);
  812. source += lenOldStr;
  813. left -= lenOldStr;
  814. }
  815. else
  816. {
  817. result.append(*source);
  818. source++;
  819. left--;
  820. }
  821. }
  822. // there are no more possible replacements, make sure we keep the end of the original buffer
  823. result.append(left, source);
  824. }
  825. return result;
  826. }
  827. StringBuffer &replaceStringNoCase(StringBuffer & result, size32_t lenSource, const char *source, size32_t lenOldStr, const char* oldStr, size32_t lenNewStr, const char* newStr)
  828. {
  829. if (lenSource)
  830. {
  831. size32_t left = lenSource;
  832. while (left >= lenOldStr)
  833. {
  834. if (memicmp(source, oldStr, lenOldStr)==0)
  835. {
  836. result.append(lenNewStr, newStr);
  837. source += lenOldStr;
  838. left -= lenOldStr;
  839. }
  840. else
  841. {
  842. result.append(*source);
  843. source++;
  844. left--;
  845. }
  846. }
  847. // there are no more possible replacements, make sure we keep the end of the original buffer
  848. result.append(left, source);
  849. }
  850. return result;
  851. }
  852. // this method will replace all occurrences of "oldStr" with "newStr"
  853. StringBuffer & StringBuffer::replaceString(const char* oldStr, const char* newStr)
  854. {
  855. if (curLen)
  856. {
  857. StringBuffer temp;
  858. size32_t oldlen = oldStr ? strlen(oldStr) : 0;
  859. size32_t newlen = newStr ? strlen(newStr) : 0;
  860. ::replaceString(temp, curLen, buffer, oldlen, oldStr, newlen, newStr);
  861. swapWith(temp);
  862. }
  863. return *this;
  864. }
  865. StringBuffer & StringBuffer::replaceStringNoCase(const char* oldStr, const char* newStr)
  866. {
  867. if (curLen)
  868. {
  869. StringBuffer temp;
  870. size32_t oldlen = oldStr ? strlen(oldStr) : 0;
  871. size32_t newlen = newStr ? strlen(newStr) : 0;
  872. ::replaceStringNoCase(temp, curLen, buffer, oldlen, oldStr, newlen, newStr);
  873. swapWith(temp);
  874. }
  875. return *this;
  876. }
  877. StringBuffer & StringBuffer::stripChar(char oldChar)
  878. {
  879. size32_t delta = 0;
  880. size32_t l = curLen;
  881. for (size32_t i = 0; i < l; i++)
  882. {
  883. if (buffer[i] == oldChar)
  884. delta++;
  885. else if (delta)
  886. buffer[i-delta] = buffer[i];
  887. }
  888. if (delta)
  889. curLen = curLen - delta;
  890. return *this;
  891. }
  892. const char * StringBuffer::str() const
  893. {
  894. buffer[curLen] = '\0'; // There is always room for this null
  895. return buffer;
  896. }
  897. //===========================================================================
  898. VStringBuffer::VStringBuffer(const char* format, ...)
  899. {
  900. va_list args;
  901. va_start(args,format);
  902. valist_appendf(format,args);
  903. va_end(args);
  904. }
  905. //===========================================================================
  906. StringAttrBuilder::StringAttrBuilder(StringAttr & _target) : StringBuffer(false), target(_target)
  907. {
  908. }
  909. StringAttrBuilder::~StringAttrBuilder()
  910. {
  911. target.setown(*this);
  912. }
  913. //===========================================================================
  914. String::String()
  915. {
  916. text = (char *)TheNullStr;
  917. }
  918. String::String(const char * value)
  919. {
  920. text = (value ? strdup(value) : (char *)TheNullStr);
  921. }
  922. String::String(const char * value, int offset, int _count)
  923. {
  924. text = (char *)malloc(_count+1);
  925. memcpy(text, value+offset, _count);
  926. text[_count]=0;
  927. }
  928. String::String(String & value)
  929. {
  930. text = strdup(value.str());
  931. }
  932. String::String(StringBuffer & value)
  933. {
  934. unsigned len = value.length();
  935. text = (char *)malloc(len+1);
  936. value.getChars(0,len,text);
  937. text[len] = 0;
  938. }
  939. String::~String()
  940. {
  941. if (text != TheNullStr) free(text);
  942. }
  943. char String::charAt(size32_t index) const
  944. {
  945. return text[index];
  946. }
  947. int String::compareTo(const String & value) const
  948. {
  949. return strcmp(text, value.str());
  950. }
  951. int String::compareTo(const char* value) const
  952. {
  953. return strcmp(text,value);
  954. }
  955. String * String::concat(const String & value) const
  956. {
  957. StringBuffer temp(str());
  958. temp.append(value);
  959. return new String(temp.str());
  960. }
  961. bool String::endsWith(const String & value) const
  962. {
  963. unsigned lenValue = value.length();
  964. unsigned len = (size32_t)strlen(text);
  965. if (len >= lenValue)
  966. return (memcmp(text+(len-lenValue),value.str(),lenValue) == 0);
  967. return false;
  968. }
  969. bool String::endsWith(const char* value) const
  970. {
  971. return ::endsWith(this->text, value);
  972. }
  973. bool String::equals(String & value) const
  974. {
  975. return strcmp(text, value.str())==0;
  976. }
  977. bool String::equalsIgnoreCase(const String & value) const
  978. {
  979. return stricmp(text, value.str())==0;
  980. }
  981. void String::getBytes(int srcBegin, int srcEnd, void * dest, int dstBegin) const
  982. {
  983. memcpy((char *)dest+dstBegin, text+srcBegin, srcEnd-srcBegin);
  984. }
  985. void String::getChars(int srcBegin, int srcEnd, void * dest, int dstBegin) const
  986. {
  987. memcpy((char *)dest+dstBegin, text+srcBegin, srcEnd-srcBegin);
  988. }
  989. int String::hashCode() const
  990. {
  991. return (int)hashc((const byte *)text,length(),0);
  992. }
  993. int String::indexOf(int ch) const
  994. {
  995. char * match = strchr(text, ch);
  996. return match ? (int)(match - text) : -1;
  997. }
  998. int String::indexOf(int ch, int from) const
  999. {
  1000. char * match = strchr(text + from, ch);
  1001. return match ? (int)(match - text) : -1;
  1002. }
  1003. int String::indexOf(const String & search) const
  1004. {
  1005. const char * str = search.str();
  1006. const char * match = strstr(text, str);
  1007. return match ? (int)(match - text) : -1;
  1008. }
  1009. int String::indexOf(const String & search, int from) const
  1010. {
  1011. const char * str = search.str();
  1012. const char * match = strstr(text + from, str);
  1013. return match ? (int)(match - text) : -1;
  1014. }
  1015. int String::lastIndexOf(int ch) const
  1016. {
  1017. char * match = strrchr(text, ch);
  1018. return match ? (int)(match - text) : -1;
  1019. }
  1020. int String::lastIndexOf(int ch, int from) const
  1021. {
  1022. for (;(from > 0);--from)
  1023. if (text[from] == ch)
  1024. return from;
  1025. return -1;
  1026. }
  1027. int String::lastIndexOf(const String & search) const
  1028. {
  1029. assertex(!"TBD");
  1030. return -1;
  1031. }
  1032. int String::lastIndexOf(const String & search, int from) const
  1033. {
  1034. assertex(!"TBD");
  1035. return -1;
  1036. }
  1037. size32_t String::length() const
  1038. {
  1039. return (size32_t)strlen(text);
  1040. }
  1041. bool String::startsWith(String & value) const
  1042. {
  1043. unsigned lenValue = value.length();
  1044. const char * search = value.str();
  1045. return (memcmp(text, search, lenValue) == 0);
  1046. }
  1047. bool String::startsWith(String & value, int offset) const
  1048. {
  1049. unsigned lenValue = value.length();
  1050. const char * search = value.str();
  1051. return (memcmp(text + offset, search, lenValue) == 0);
  1052. }
  1053. bool String::startsWith(const char* value) const
  1054. {
  1055. return ::startsWith(this->text,value);
  1056. }
  1057. String * String::substring(int beginIndex) const
  1058. {
  1059. return new String(text+beginIndex);
  1060. }
  1061. String * String::substring(int beginIndex, int endIndex) const
  1062. {
  1063. return new String(text, beginIndex, endIndex - beginIndex);
  1064. }
  1065. const char *String::str() const
  1066. {
  1067. return text;
  1068. }
  1069. String * String::toLowerCase() const
  1070. {
  1071. String *ret = new String();
  1072. size32_t l = length();
  1073. if (l)
  1074. {
  1075. ret->text = (char *)malloc(l+1);
  1076. for (unsigned i = 0; i < l; i++)
  1077. ret->text[i] = tolower(text[i]);
  1078. ret->text[l]=0;
  1079. }
  1080. return ret;
  1081. }
  1082. String * String::toString()
  1083. {
  1084. Link();
  1085. return this;
  1086. }
  1087. String * String::toUpperCase() const
  1088. {
  1089. String *ret = new String();
  1090. size32_t l = length();
  1091. if (l)
  1092. {
  1093. ret->text = (char *)malloc(l+1);
  1094. for (unsigned i = 0; i < l; i++)
  1095. ret->text[i] = toupper(text[i]);
  1096. ret->text[l]=0;
  1097. }
  1098. return ret;
  1099. }
  1100. String * String::trim() const
  1101. {
  1102. size32_t l = length();
  1103. while (l && isspace(text[l-1]))
  1104. l--;
  1105. return new String(text, 0, l);
  1106. }
  1107. //------------------------------------------------
  1108. #if 0
  1109. String & String::valueOf(char value)
  1110. {
  1111. return * new String(&value, 0, 1);
  1112. }
  1113. String & String::valueOf(const char * value)
  1114. {
  1115. return * new String(value);
  1116. }
  1117. String & String::valueOf(const char * value, int offset, int count)
  1118. {
  1119. return * new String(value, offset, count);
  1120. }
  1121. String & String::valueOf(double value)
  1122. {
  1123. StringBuffer temp;
  1124. return temp.append(value).toString();
  1125. }
  1126. String & String::valueOf(float value)
  1127. {
  1128. StringBuffer temp;
  1129. return temp.append(value).toString();
  1130. }
  1131. String & String::valueOf(int value)
  1132. {
  1133. StringBuffer temp;
  1134. return temp.append(value).toString();
  1135. }
  1136. String & String::valueOf(long value)
  1137. {
  1138. StringBuffer temp;
  1139. return temp.append(value).toString();
  1140. }
  1141. #endif
  1142. //------------------------------------------------
  1143. StringAttr::StringAttr(const char * _text)
  1144. {
  1145. text = _text ? strdup(_text) : NULL;
  1146. }
  1147. StringAttr::StringAttr(const char * _text, size_t _len)
  1148. {
  1149. text = NULL;
  1150. set(_text, _len);
  1151. }
  1152. StringAttr::StringAttr(const StringAttr & src)
  1153. {
  1154. text = NULL;
  1155. set(src.get());
  1156. }
  1157. StringAttr::StringAttr(StringAttr && src)
  1158. {
  1159. text = src.text;
  1160. src.text = nullptr;
  1161. }
  1162. StringAttr& StringAttr::operator = (StringAttr && from)
  1163. {
  1164. char *temp = text;
  1165. text = from.text;
  1166. from.text = temp;
  1167. return *this;
  1168. }
  1169. StringAttr& StringAttr::operator = (const StringAttr & from)
  1170. {
  1171. set(from.str());
  1172. return *this;
  1173. }
  1174. void StringAttr::set(const char * _text)
  1175. {
  1176. char * oldtext = text;
  1177. text = _text ? strdup(_text) : NULL;
  1178. free(oldtext);
  1179. }
  1180. void StringAttr::set(const char * _text, size_t _len)
  1181. {
  1182. char * oldtext = text;
  1183. text = (char *)malloc(_len+1);
  1184. memcpy(text, _text, _len);
  1185. text[_len] = 0;
  1186. free(oldtext);
  1187. }
  1188. void StringAttr::setown(const char * _text)
  1189. {
  1190. char * oldtext = text;
  1191. text = (char *)_text;
  1192. free(oldtext);
  1193. }
  1194. void StringAttr::set(const StringBuffer & source)
  1195. {
  1196. if (source.length())
  1197. set(source.str());
  1198. else
  1199. clear();
  1200. }
  1201. void StringAttr::setown(StringBuffer & source)
  1202. {
  1203. if (source.length())
  1204. setown(source.detach());
  1205. else
  1206. clear();
  1207. }
  1208. void StringAttr::toLowerCase()
  1209. {
  1210. if (text)
  1211. {
  1212. char * cur = text;
  1213. char next;
  1214. while ((next = *cur) != 0)
  1215. {
  1216. if (isupper(next))
  1217. *cur = tolower(next);
  1218. cur++;
  1219. }
  1220. }
  1221. }
  1222. void StringAttr::toUpperCase()
  1223. {
  1224. if (text)
  1225. {
  1226. char * cur = text;
  1227. char next;
  1228. while ((next = *cur) != 0)
  1229. {
  1230. if (islower(next))
  1231. *cur = toupper(next);
  1232. cur++;
  1233. }
  1234. }
  1235. }
  1236. StringAttrItem::StringAttrItem(const char *_text, unsigned _len)
  1237. {
  1238. text.set(_text, _len);
  1239. }
  1240. inline char hex(char c, char lower)
  1241. {
  1242. if (c < 10)
  1243. return '0' + c;
  1244. else if (lower)
  1245. return 'a' + c - 10;
  1246. else
  1247. return 'A' + c - 10;
  1248. }
  1249. StringBuffer & StringBuffer::appendhex(unsigned char c, char lower)
  1250. {
  1251. append(hex(c>>4, lower));
  1252. append(hex(c&0xF, lower));
  1253. return *this;
  1254. }
  1255. void appendURL(StringBuffer *dest, const char *src, size32_t len, char lower)
  1256. {
  1257. if (len == (size32_t)-1)
  1258. len = (size32_t)strlen(src);
  1259. while (len)
  1260. {
  1261. // isalnum seems to give weird results for chars > 127....
  1262. unsigned char c = (unsigned char) *src;
  1263. if (c == ' ')
  1264. dest->append('+');
  1265. else if ((c & 0x80) || !isalnum(*src))
  1266. {
  1267. dest->append('%');
  1268. dest->appendhex(c, lower);
  1269. }
  1270. else
  1271. dest->append(c);
  1272. src++;
  1273. len--;
  1274. }
  1275. }
  1276. inline char translateHex(char hex)
  1277. {
  1278. if(hex >= 'A')
  1279. return (hex & 0xdf) - 'A' + 10;
  1280. else
  1281. return hex - '0';
  1282. }
  1283. inline char translateHex(char h1, char h2)
  1284. {
  1285. return (translateHex(h1) * 16 + translateHex(h2));
  1286. }
  1287. StringBuffer &appendDecodedURL(StringBuffer &s, const char *url)
  1288. {
  1289. if(!url)
  1290. return s;
  1291. while (*url)
  1292. {
  1293. char c = *url++;
  1294. if (c == '+')
  1295. c = ' ';
  1296. else if (c == '%')
  1297. {
  1298. if (isxdigit(url[0]) && isxdigit(url[1]))
  1299. {
  1300. c = translateHex(url[0], url[1]);
  1301. url+=2;
  1302. }
  1303. }
  1304. s.append(c);
  1305. }
  1306. return s;
  1307. }
  1308. static StringBuffer & appendStringExpandControl(StringBuffer &out, unsigned len, const char * src, bool addBreak, bool isCpp, bool isUtf8)
  1309. {
  1310. const int minBreakPos = 0;
  1311. const int commaBreakPos = 70;
  1312. const int maxBreakPos = 120;
  1313. const char * startLine = src;
  1314. out.ensureCapacity(len+2);
  1315. for (; len > 0; --len)
  1316. {
  1317. unsigned char c = *src++;
  1318. bool insertBreak = false;
  1319. bool allowBreak = true;
  1320. switch (c)
  1321. {
  1322. case '\n':
  1323. {
  1324. out.append("\\n");
  1325. if (src-startLine > minBreakPos)
  1326. insertBreak = true;
  1327. break;
  1328. }
  1329. case ',':
  1330. {
  1331. out.append(c);
  1332. if (src-startLine > commaBreakPos)
  1333. insertBreak = true;
  1334. break;
  1335. }
  1336. case '\r': out.append("\\r"); break;
  1337. case '\t': out.append("\\t"); break;
  1338. case '"':
  1339. if (isCpp)
  1340. out.append("\\");
  1341. out.append(c);
  1342. break;
  1343. case '\'':
  1344. if (!isCpp)
  1345. out.append("\\");
  1346. out.append(c);
  1347. break;
  1348. case '\\': out.append("\\\\"); break;
  1349. case '?':
  1350. if (isCpp)
  1351. {
  1352. //stop trigraphs being generated.... quote the second ?
  1353. out.append(c);
  1354. if ((len!=1) && (*src == '?'))
  1355. {
  1356. out.append('\\');
  1357. allowBreak = false;
  1358. }
  1359. }
  1360. else
  1361. out.append(c);
  1362. break;
  1363. default:
  1364. if (isUtf8 || ((c >= ' ') && (c <= 126)))
  1365. out.append(c);
  1366. else
  1367. out.appendf("\\%03o", c);
  1368. break;
  1369. }
  1370. if (addBreak && (insertBreak || (allowBreak && src-startLine >= maxBreakPos)))
  1371. {
  1372. out.append("\"").newline().append("\t\t\"");
  1373. startLine = src;
  1374. }
  1375. }
  1376. return out;
  1377. }
  1378. StringBuffer & appendStringAsCPP(StringBuffer &out, unsigned len, const char * src, bool addBreak)
  1379. {
  1380. return appendStringExpandControl(out, len, src, addBreak, true, false);
  1381. }
  1382. StringBuffer & appendStringAsECL(StringBuffer &out, unsigned len, const char * src)
  1383. {
  1384. return appendStringExpandControl(out, len, src, false, false, false);
  1385. }
  1386. StringBuffer & appendUtf8AsECL(StringBuffer &out, unsigned len, const char * src)
  1387. {
  1388. return appendStringExpandControl(out, len, src, false, false, true);
  1389. }
  1390. StringBuffer & appendStringAsQuotedCPP(StringBuffer &out, unsigned len, const char * src, bool addBreak)
  1391. {
  1392. out.ensureCapacity(len+2);
  1393. out.append('\"');
  1394. appendStringAsCPP(out, len, src, addBreak);
  1395. return out.append('\"');
  1396. }
  1397. StringBuffer & appendStringAsQuotedECL(StringBuffer &out, unsigned len, const char * src)
  1398. {
  1399. out.ensureCapacity(len+2);
  1400. out.append('\'');
  1401. appendStringAsECL(out, len, src);
  1402. return out.append('\'');
  1403. }
  1404. void extractItem(StringBuffer & res, const char * src, const char * sep, int whichItem, bool caps)
  1405. {
  1406. bool isSeparator[256];
  1407. memset(isSeparator,0,sizeof(isSeparator));
  1408. unsigned char * finger = (unsigned char *)sep;
  1409. while (*finger !=0)
  1410. isSeparator[*finger++] = true;
  1411. isSeparator[0]=true;
  1412. finger = (unsigned char *)src;
  1413. unsigned char next;
  1414. for (;;)
  1415. {
  1416. while (isSeparator[(next = *finger)])
  1417. {
  1418. if (next == 0) return;
  1419. finger++;
  1420. }
  1421. if (whichItem == 0)
  1422. {
  1423. while (!isSeparator[(next = *finger)])
  1424. {
  1425. if (caps)
  1426. next = toupper(next);
  1427. res.append(next);
  1428. finger++;
  1429. }
  1430. return;
  1431. }
  1432. while (!isSeparator[*finger])
  1433. finger++;
  1434. whichItem--;
  1435. }
  1436. }
  1437. int utf8CharLen(unsigned char ch)
  1438. {
  1439. //return 1 if this is an ascii character,
  1440. //or 0 if its not a valid utf-8 character
  1441. if (ch < 128)
  1442. return 1;
  1443. if (ch < 192)
  1444. return 0;
  1445. unsigned char len = 1;
  1446. for (unsigned char lead = ch << 1; (lead & 0x80); lead <<=1)
  1447. len++;
  1448. return len;
  1449. }
  1450. int utf8CharLen(const unsigned char *ch, unsigned maxsize)
  1451. {
  1452. //return 1 if this is an ascii character,
  1453. //or 0 if its not a valid utf-8 character
  1454. if (*ch < 128)
  1455. return 1;
  1456. unsigned char len = utf8CharLen(*ch);
  1457. if (len>maxsize)
  1458. return 0;
  1459. for (unsigned pos = 1; pos < len; pos++)
  1460. if ((ch[pos] < 128) || (ch[pos] >= 192))
  1461. return 0; //its not a valid utf-8 character after all
  1462. return len;
  1463. }
  1464. const char *encodeXML(const char *x, StringBuffer &ret, unsigned flags, unsigned len, bool utf8)
  1465. {
  1466. while (len)
  1467. {
  1468. switch(*x)
  1469. {
  1470. case '&':
  1471. ret.append("&amp;");
  1472. break;
  1473. case '<':
  1474. ret.append("&lt;");
  1475. break;
  1476. case '>':
  1477. ret.append("&gt;");
  1478. break;
  1479. case '\"':
  1480. ret.append("&quot;");
  1481. break;
  1482. case '\'':
  1483. ret.append("&apos;");
  1484. break;
  1485. case ' ':
  1486. ret.append(flags & ENCODE_SPACES?"&#32;":" ");
  1487. break;
  1488. case '\n':
  1489. ret.append(flags & ENCODE_NEWLINES?"&#10;":"\n");
  1490. break;
  1491. case '\r':
  1492. ret.append(flags & ENCODE_NEWLINES?"&#13;":"\r");
  1493. break;
  1494. case '\t':
  1495. ret.append(flags & ENCODE_SPACES?"&#9;":"\t");
  1496. break;
  1497. case '\0':
  1498. if (len == (unsigned) -1)
  1499. return x;
  1500. ret.append("&#xe000;"); // hack!!! Characters below 0x20 are not legal in strict xml, even encoded.
  1501. break;
  1502. default:
  1503. if (*x >= ' ' && ((byte)*x) < 128)
  1504. ret.append(*x);
  1505. else if (*x < ' ' && *x > 0)
  1506. ret.append("&#xe0").appendhex(*x, true).append(';'); // HACK
  1507. else if (utf8)
  1508. {
  1509. unsigned chlen = utf8CharLen((const unsigned char *)x);
  1510. if (chlen==0)
  1511. ret.append("&#").append((unsigned int)*(unsigned char *) x).append(';');
  1512. else
  1513. {
  1514. ret.append(*x);
  1515. while(--chlen)
  1516. {
  1517. if (len != (unsigned) -1)
  1518. len--;
  1519. ret.append(*(++x));
  1520. }
  1521. }
  1522. }
  1523. else
  1524. ret.append("&#").append((unsigned int)*(unsigned char *) x).append(';');
  1525. break;
  1526. }
  1527. if (len != (unsigned) -1)
  1528. len--;
  1529. ++x;
  1530. }
  1531. return x;
  1532. }
  1533. const char *encodeXML(const char *x, IIOStream &out, unsigned flags, unsigned len, bool utf8)
  1534. {
  1535. while (len)
  1536. {
  1537. switch(*x)
  1538. {
  1539. case '&':
  1540. writeStringToStream(out, "&amp;");
  1541. break;
  1542. case '<':
  1543. writeStringToStream(out, "&lt;");
  1544. break;
  1545. case '>':
  1546. writeStringToStream(out, "&gt;");
  1547. break;
  1548. case '\"':
  1549. writeStringToStream(out, "&quot;");
  1550. break;
  1551. case '\'':
  1552. writeStringToStream(out, "&apos;");
  1553. break;
  1554. case ' ':
  1555. writeStringToStream(out, flags & ENCODE_SPACES?"&#32;":" ");
  1556. break;
  1557. case '\n':
  1558. writeStringToStream(out, flags & ENCODE_NEWLINES?"&#10;":"\n");
  1559. break;
  1560. case '\r':
  1561. writeStringToStream(out, flags & ENCODE_NEWLINES?"&#13;":"\r");
  1562. break;
  1563. case '\t':
  1564. writeStringToStream(out, flags & ENCODE_SPACES?"&#9;":"\t");
  1565. break;
  1566. case '\0':
  1567. if (len == (unsigned) -1)
  1568. return x;
  1569. writeStringToStream(out, "&#xe000;"); // hack!!! Characters below 0x20 are not legal in strict xml, even encoded.
  1570. break;
  1571. default:
  1572. if (*x >= ' ' && ((byte)*x) < 128)
  1573. writeCharToStream(out, *x);
  1574. else if (*x < ' ' && *x > 0)
  1575. {
  1576. writeStringToStream(out, "&#xe0");
  1577. unsigned char c = *(unsigned char *)x;
  1578. writeCharToStream(out, hex(c>>4, true));
  1579. writeCharToStream(out, hex(c&0xF, true));
  1580. writeCharToStream(out, ';'); // HACK
  1581. }
  1582. else if (utf8)
  1583. {
  1584. int chlen = utf8CharLen((const unsigned char *)x);
  1585. if (chlen==0)
  1586. {
  1587. writeStringToStream(out, "&#");
  1588. char tmp[12];
  1589. unsigned written = numtostr(tmp, *(unsigned char *)x);
  1590. out.write(written, tmp);
  1591. writeCharToStream(out, ';');
  1592. }
  1593. else
  1594. {
  1595. writeCharToStream(out, *x);
  1596. while(--chlen)
  1597. {
  1598. if (len != (unsigned) -1)
  1599. len--;
  1600. writeCharToStream(out, *(++x));
  1601. }
  1602. }
  1603. }
  1604. else
  1605. {
  1606. writeStringToStream(out, "&#");
  1607. char tmp[12];
  1608. unsigned written = numtostr(tmp, *(unsigned char *)x);
  1609. out.write(written, tmp);
  1610. writeCharToStream(out, ';');
  1611. }
  1612. break;
  1613. }
  1614. if (len != (unsigned) -1)
  1615. len--;
  1616. ++x;
  1617. }
  1618. return x;
  1619. }
  1620. static void writeUtf8(unsigned c, StringBuffer &out)
  1621. {
  1622. if (c < 0x80)
  1623. out.append((char)c);
  1624. else if (c < 0x800)
  1625. {
  1626. out.append((char)(0xC0 | (c>>6)));
  1627. out.append((char)(0x80 | (c & 0x3F)));
  1628. }
  1629. else if (c < 0x10000)
  1630. {
  1631. out.append((char) (0xE0 | (c>>12)));
  1632. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1633. out.append((char) (0x80 | (c & 0x3F)));
  1634. }
  1635. else if (c < 0x200000)
  1636. {
  1637. out.append((char) (0xF0 | (c>>18)));
  1638. out.append((char) (0x80 | (c>>12 & 0x3F)));
  1639. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1640. out.append((char) (0x80 | (c & 0x3F)));
  1641. }
  1642. else if (c < 0x4000000)
  1643. {
  1644. out.append((char) (0xF8 | (c>>24)));
  1645. out.append((char) (0x80 | (c>>18 & 0x3F)));
  1646. out.append((char) (0x80 | (c>>12 & 0x3F)));
  1647. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1648. out.append((char) (0x80 | (c & 0x3F)));
  1649. }
  1650. else if (c < 0x80000000)
  1651. {
  1652. out.append((char) (0xFC | (c>>30)));
  1653. out.append((char) (0x80 | (c>>24 & 0x3F)));
  1654. out.append((char) (0x80 | (c>>18 & 0x3F)));
  1655. out.append((char) (0x80 | (c>>12 & 0x3F)));
  1656. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1657. out.append((char) (0x80 | (c & 0x3F)));
  1658. }
  1659. else
  1660. assertex(false);
  1661. }
  1662. #define JSONSTRICT
  1663. const char *decodeJSON(const char *j, StringBuffer &ret, unsigned len, const char **errMark)
  1664. {
  1665. if (!j)
  1666. return j;
  1667. if ((unsigned)-1 == len)
  1668. len = (unsigned)strlen(j);
  1669. try
  1670. {
  1671. for (const char *end = j+len; j<end && *j; j++)
  1672. {
  1673. if (*j!='\\')
  1674. ret.append(*j);
  1675. else
  1676. {
  1677. switch (*++j)
  1678. {
  1679. case 'u':
  1680. {
  1681. j++;
  1682. if (end-j>=4)
  1683. {
  1684. char *endptr;
  1685. StringAttr s(j, 4);
  1686. unsigned val = strtoul(s.get(), &endptr, 16);
  1687. if (endptr && !*endptr)
  1688. {
  1689. writeUtf8(val, ret);
  1690. j+=3;
  1691. break;
  1692. }
  1693. }
  1694. #ifdef JSONSTRICT
  1695. throw MakeStringException(-1, "invalid json \\u escaped sequence");
  1696. #endif
  1697. ret.append(*j);
  1698. break;
  1699. }
  1700. case '\"':
  1701. case '\\':
  1702. case '/':
  1703. ret.append(*j);
  1704. break;
  1705. case 'b':
  1706. ret.append('\b');
  1707. break;
  1708. case 'f':
  1709. ret.append('\f');
  1710. break;
  1711. case 'n':
  1712. ret.append('\n');
  1713. continue;
  1714. case 'r':
  1715. ret.append('\r');
  1716. break;
  1717. case 't':
  1718. ret.append('\t');
  1719. break;
  1720. default:
  1721. {
  1722. #ifdef JSONSTRICT
  1723. throw MakeStringException(-1, "invalid json escaped sequence");
  1724. #endif
  1725. ret.append('\\');
  1726. ret.append(*j);
  1727. break;
  1728. }
  1729. }
  1730. }
  1731. }
  1732. }
  1733. catch (IException *)
  1734. {
  1735. if (errMark) *errMark = j;
  1736. throw;
  1737. }
  1738. return j;
  1739. }
  1740. void decodeXML(ISimpleReadStream &in, StringBuffer &out, unsigned len)
  1741. {
  1742. // TODO
  1743. UNIMPLEMENTED;
  1744. }
  1745. const char *decodeXML(const char *x, StringBuffer &ret, const char **errMark, IEntityHelper *entityHelper, bool strict)
  1746. {
  1747. if (!x)
  1748. return x;
  1749. try
  1750. {
  1751. while (*x)
  1752. {
  1753. if ('&' == *x)
  1754. {
  1755. switch (x[1])
  1756. {
  1757. case 'a':
  1758. switch (x[2])
  1759. {
  1760. case 'm':
  1761. {
  1762. if ('p' == x[3] && ';' == x[4])
  1763. {
  1764. x += 5;
  1765. ret.append('&');
  1766. continue;
  1767. }
  1768. break;
  1769. }
  1770. case 'p':
  1771. {
  1772. if ('o' == x[3] && 's' == x[4] && ';' == x[5])
  1773. {
  1774. x += 6;
  1775. ret.append('\'');
  1776. continue;
  1777. }
  1778. break;
  1779. }
  1780. }
  1781. break;
  1782. case 'l':
  1783. if ('t' == x[2] && ';' == x[3])
  1784. {
  1785. x += 4;
  1786. ret.append('<');
  1787. continue;
  1788. }
  1789. break;
  1790. case 'g':
  1791. if ('t' == x[2] && ';' == x[3])
  1792. {
  1793. x += 4;
  1794. ret.append('>');
  1795. continue;
  1796. }
  1797. break;
  1798. case 'q':
  1799. if ('u' == x[2] && 'o' == x[3] && 't' == x[4] && ';' == x[5])
  1800. {
  1801. x += 6;
  1802. ret.append('"');
  1803. continue;
  1804. }
  1805. break;
  1806. case 'n':
  1807. if ('b' == x[2] && 's' == x[3] && 'p' == x[4] && ';' == x[5])
  1808. {
  1809. x += 6;
  1810. writeUtf8(0xa0, ret);
  1811. continue;
  1812. }
  1813. break;
  1814. case '#':
  1815. {
  1816. const char *numstart = x+2;
  1817. int base = 10;
  1818. if (*numstart == 'x')
  1819. {
  1820. base = 16;
  1821. numstart++;
  1822. }
  1823. char *numend;
  1824. unsigned val = strtoul(numstart, &numend, base);
  1825. if (numstart==numend || *numend != ';')
  1826. {
  1827. if (strict)
  1828. throw MakeStringException(-1, "invalid escaped sequence");
  1829. }
  1830. else // always convert to utf-8. Should potentially throw error if not marked as utf-8 encoded doc and out of ascii range.
  1831. {
  1832. writeUtf8(val, ret);
  1833. x = numend+1;
  1834. continue;
  1835. }
  1836. break;
  1837. }
  1838. case ';':
  1839. case '\0':
  1840. if (strict)
  1841. throw MakeStringException(-1, "invalid escaped sequence");
  1842. break;
  1843. default:
  1844. if (entityHelper)
  1845. {
  1846. const char *start=x+1;
  1847. const char *finger=start;
  1848. while (*finger && *finger != ';')
  1849. ++finger;
  1850. if (*finger == ';')
  1851. {
  1852. StringBuffer entity(finger-start, start);
  1853. if (entityHelper->find(entity, ret))
  1854. {
  1855. x = finger + 1;
  1856. continue;
  1857. }
  1858. }
  1859. }
  1860. if (strict)
  1861. throw MakeStringException(-1, "invalid escaped sequence");
  1862. break;
  1863. }
  1864. }
  1865. ret.append(*x);
  1866. ++x;
  1867. }
  1868. }
  1869. catch (IException *)
  1870. {
  1871. if (errMark) *errMark = x;
  1872. throw;
  1873. }
  1874. return x;
  1875. }
  1876. StringBuffer & appendXMLOpenTag(StringBuffer &xml, const char *tag, const char *prefix, bool complete, bool close, const char *uri)
  1877. {
  1878. if (!tag || !*tag)
  1879. return xml;
  1880. xml.append('<');
  1881. appendXMLTagName(xml, tag, prefix);
  1882. if (uri && *uri)
  1883. {
  1884. xml.append(" xmlns");
  1885. if (prefix && *prefix)
  1886. xml.append(':').append(prefix);
  1887. xml.append("=\"").append(uri).append('\"');
  1888. }
  1889. if (complete)
  1890. {
  1891. if (close)
  1892. xml.append('/');
  1893. xml.append('>');
  1894. }
  1895. return xml;
  1896. }
  1897. jlib_decl StringBuffer &appendJSONName(StringBuffer &s, const char *name)
  1898. {
  1899. if (!name || !*name)
  1900. return s;
  1901. delimitJSON(s);
  1902. return encodeJSON(s.append('"'), name).append("\": ");
  1903. }
  1904. jlib_decl StringBuffer &appendfJSONName(StringBuffer &s, const char *format, ...)
  1905. {
  1906. va_list args;
  1907. va_start(args, format);
  1908. StringBuffer vs;
  1909. vs.valist_appendf(format, args);
  1910. va_end(args);
  1911. return appendJSONName(s, vs);
  1912. }
  1913. static char hexchar[] = "0123456789ABCDEF";
  1914. jlib_decl StringBuffer &appendJSONDataValue(StringBuffer& s, const char *name, unsigned len, const void *_value)
  1915. {
  1916. appendJSONNameOrDelimit(s, name);
  1917. s.append('"');
  1918. const unsigned char *value = (const unsigned char *) _value;
  1919. for (unsigned int i = 0; i < len; i++)
  1920. s.append(hexchar[value[i] >> 4]).append(hexchar[value[i] & 0x0f]);
  1921. return s.append('"');
  1922. }
  1923. StringBuffer &appendJSONRealValue(StringBuffer& s, const char *name, double value)
  1924. {
  1925. appendJSONNameOrDelimit(s, name);
  1926. bool quoted = j_isnan(value) || j_isinf(value);
  1927. if (quoted)
  1928. s.append('"');
  1929. s.append(value);
  1930. if (quoted)
  1931. s.append('"');
  1932. return s;
  1933. }
  1934. inline StringBuffer &encodeJSONChar(StringBuffer &s, const char *&ch, unsigned &remaining)
  1935. {
  1936. byte next = *ch;
  1937. switch (next)
  1938. {
  1939. case '\b':
  1940. s.append("\\b");
  1941. break;
  1942. case '\f':
  1943. s.append("\\f");
  1944. break;
  1945. case '\n':
  1946. s.append("\\n");
  1947. break;
  1948. case '\r':
  1949. s.append("\\r");
  1950. break;
  1951. case '\t':
  1952. s.append("\\t");
  1953. break;
  1954. case '\"':
  1955. case '\\':
  1956. case '/':
  1957. s.append('\\');
  1958. s.append(next);
  1959. break;
  1960. case '\0':
  1961. s.append("\\u0000");
  1962. break;
  1963. case '\x7f':
  1964. s.append("\\u007f");
  1965. break;
  1966. default:
  1967. if (next >= ' ' && next < 128)
  1968. s.append(next);
  1969. else if (next < ' ')
  1970. s.append("\\u00").appendhex(next, true);
  1971. else //json is always supposed to be utf8 (or other unicode formats)
  1972. {
  1973. unsigned chlen = utf8CharLen((const unsigned char *)ch, remaining);
  1974. if (chlen==0)
  1975. s.append("\\u00").appendhex(next, true);
  1976. else
  1977. {
  1978. s.append(chlen, ch);
  1979. ch += (chlen-1);
  1980. remaining -= (chlen-1);
  1981. }
  1982. }
  1983. break;
  1984. }
  1985. ch++;
  1986. remaining--;
  1987. return s;
  1988. }
  1989. StringBuffer &encodeJSON(StringBuffer &s, unsigned size, const char *value)
  1990. {
  1991. if (!value)
  1992. return s;
  1993. while (size)
  1994. encodeJSONChar(s, value, size);
  1995. return s;
  1996. }
  1997. StringBuffer &encodeJSON(StringBuffer &s, const char *value)
  1998. {
  1999. if (!value)
  2000. return s;
  2001. return encodeJSON(s, strlen(value), value);
  2002. }
  2003. bool checkUnicodeLiteral(char const * str, unsigned length, unsigned & ep, StringBuffer & msg)
  2004. {
  2005. unsigned i;
  2006. for(i = 0; i < length; i++)
  2007. {
  2008. if (str[i] == '\\')
  2009. {
  2010. unsigned char next = str[++i];
  2011. if (next == '\'' || next == '\\' || next == 'n' || next == 'r' || next == 't' || next == 'a' || next == 'b' || next == 'f' || next == 'v' || next == '?' || next == '"')
  2012. {
  2013. continue;
  2014. }
  2015. else if (isdigit(next) && next < '8')
  2016. {
  2017. unsigned count;
  2018. for(count = 1; count < 3; count++)
  2019. {
  2020. next = str[++i];
  2021. if(!isdigit(next) || next >= '8')
  2022. {
  2023. msg.append("3-digit numeric escape sequence contained non-octal digit: ").append(next);
  2024. ep = i;
  2025. return false;
  2026. }
  2027. }
  2028. }
  2029. else if (next == 'u' || next == 'U')
  2030. {
  2031. unsigned count;
  2032. unsigned max = (next == 'u') ? 4 : 8;
  2033. for(count = 0; count < max; count++)
  2034. {
  2035. next = str[++i];
  2036. if(!isdigit(next) && (!isalpha(next) || tolower(next) > 'f'))
  2037. {
  2038. msg.append((max == 4) ? '4' : '8').append("-digit unicode escape sequence contained non-hex digit: ").append(next);
  2039. ep = i;
  2040. return false;
  2041. }
  2042. }
  2043. }
  2044. else
  2045. {
  2046. msg.append("Unrecognized escape sequence: ").append("\\").append(next);
  2047. ep = i;
  2048. return false;
  2049. }
  2050. }
  2051. }
  2052. return true;
  2053. }
  2054. void decodeCppEscapeSequence(StringBuffer & out, const char * in, bool errorIfInvalid)
  2055. {
  2056. out.ensureCapacity((size32_t)strlen(in));
  2057. while (*in)
  2058. {
  2059. char c = *in++;
  2060. if (c == '\\')
  2061. {
  2062. char next = *in;
  2063. if (next)
  2064. {
  2065. in++;
  2066. switch (next)
  2067. {
  2068. case 'a': c = '\a'; break;
  2069. case 'b': c = '\b'; break;
  2070. case 'f': c = '\f'; break;
  2071. case 'n': c = '\n'; break;
  2072. case 'r': c = '\r'; break;
  2073. case 't': c = '\t'; break;
  2074. case 'v': c = '\v'; break;
  2075. case '\\':
  2076. case '\'':
  2077. case '?':
  2078. case '\"': break;
  2079. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
  2080. {
  2081. c = next - '0';
  2082. if (*in >= '0' && *in <= '7')
  2083. {
  2084. c = c << 3 | (*in++-'0');
  2085. if (*in >= '0' && *in <= '7')
  2086. c = c << 3 | (*in++-'0');
  2087. }
  2088. break;
  2089. }
  2090. case 'x':
  2091. c = 0;
  2092. while (isxdigit(*in))
  2093. {
  2094. next = *in++;
  2095. c = c << 4;
  2096. if (next >= '0' && next <= '9') c |= (next - '0');
  2097. else if (next >= 'A' && next <= 'F') c |= (next - 'A' + 10);
  2098. else if (next >= 'a' && next <= 'f') c |= (next - 'a' + 10);
  2099. }
  2100. break;
  2101. default:
  2102. if (errorIfInvalid)
  2103. throw MakeStringException(1, "unrecognised character escape sequence '\\%c'", next);
  2104. in--; // keep it as is.
  2105. break;
  2106. }
  2107. }
  2108. }
  2109. out.append(c);
  2110. }
  2111. }
  2112. bool isPrintable(unsigned len, const char * src)
  2113. {
  2114. while (len--)
  2115. {
  2116. if (!isprint(*((unsigned char *)src)))
  2117. return false;
  2118. src++;
  2119. }
  2120. return true;
  2121. }
  2122. //make this as fast as possible...
  2123. StringBuffer & appendStringAsSQL(StringBuffer & out, unsigned len, const char * src)
  2124. {
  2125. if (!isPrintable(len, src))
  2126. {
  2127. out.append("X'");
  2128. appendDataAsHex(out, len, src);
  2129. return out.append('\'');
  2130. }
  2131. out.ensureCapacity(2 + len);
  2132. out.append('\'');
  2133. for (;;)
  2134. {
  2135. char * next = (char *)memchr(src, '\'', len);
  2136. if (!next)
  2137. break;
  2138. unsigned chunk=(size32_t)(next-src)+1;
  2139. out.append(chunk, src).append('\'');
  2140. len -= chunk;
  2141. src += chunk;
  2142. }
  2143. return out.append(len, src).append('\'');
  2144. }
  2145. static const char * hexText = "0123456789ABCDEF";
  2146. StringBuffer & appendDataAsHex(StringBuffer &out, unsigned len, const void * data)
  2147. {
  2148. char * target = (char *)out.reserve(len*2);
  2149. unsigned char * start = (unsigned char *)data;
  2150. for (unsigned count=len; count> 0; --count)
  2151. {
  2152. unsigned next = *start++;
  2153. *target++ = hexText[next >>4];
  2154. *target++ = hexText[next & 15];
  2155. }
  2156. return out;
  2157. }
  2158. bool strToBool(size_t len, const char * text)
  2159. {
  2160. switch (len)
  2161. {
  2162. case 4:
  2163. if (memicmp(text, "true", 4) == 0)
  2164. return true;
  2165. break;
  2166. case 3:
  2167. if (memicmp(text, "yes", 3) == 0)
  2168. return true;
  2169. break;
  2170. case 2:
  2171. if (memicmp(text, "on", 2) == 0)
  2172. return true;
  2173. break;
  2174. case 1:
  2175. if ((memicmp(text, "t", 1) == 0) || (memicmp(text, "y", 1) == 0))
  2176. return true;
  2177. break;
  2178. }
  2179. while (len && isspace(*text))
  2180. {
  2181. len--;
  2182. text++;
  2183. }
  2184. while (len-- && isdigit(*text))
  2185. {
  2186. if (*text++ != '0') return true;
  2187. }
  2188. return false;
  2189. }
  2190. bool strToBool(const char * text)
  2191. {
  2192. return strToBool(strlen(text), text);
  2193. }
  2194. bool clipStrToBool(size_t len, const char * text)
  2195. {
  2196. while (len && *text==' ')
  2197. {
  2198. len--;
  2199. text++;
  2200. }
  2201. while (len && text[len-1]== ' ')
  2202. len--;
  2203. return strToBool(len, text);
  2204. }
  2205. bool clipStrToBool(const char * text)
  2206. {
  2207. return clipStrToBool(strlen(text), text);
  2208. }
  2209. StringBuffer & ncnameEscape(char const * in, StringBuffer & out)
  2210. {
  2211. if(!isalpha(*in))
  2212. {
  2213. out.appendf("_%02X", static_cast<unsigned char>(*in));
  2214. in++;
  2215. }
  2216. char const * finger = in;
  2217. while(*finger)
  2218. {
  2219. if(!isalnum(*finger))
  2220. {
  2221. if(finger>in)
  2222. out.append((size32_t)(finger-in), in);
  2223. out.appendf("_%02X", static_cast<unsigned char>(*finger));
  2224. in = ++finger;
  2225. }
  2226. else
  2227. {
  2228. finger++;
  2229. }
  2230. }
  2231. if(finger>in)
  2232. out.append((size32_t)(finger-in), in);
  2233. return out;
  2234. }
  2235. StringBuffer & ncnameUnescape(char const * in, StringBuffer & out)
  2236. {
  2237. char const * finger = in;
  2238. while(*finger)
  2239. {
  2240. if(*finger == '_')
  2241. {
  2242. if(finger>in)
  2243. out.append((size32_t)(finger-in), in);
  2244. unsigned char chr = 16 * hex2num(finger[1]) + hex2num(finger[2]);
  2245. out.append(static_cast<char>(chr));
  2246. in = (finger+=3);
  2247. }
  2248. else
  2249. {
  2250. finger++;
  2251. }
  2252. }
  2253. if(finger>in)
  2254. out.append((size32_t)(finger-in), in);
  2255. return out;
  2256. }
  2257. bool startsWith(const char* src, const char* prefix)
  2258. {
  2259. while (*prefix && *prefix == *src) { src++; prefix++; }
  2260. return *prefix==0;
  2261. }
  2262. bool startsWithIgnoreCase(const char* src, const char* prefix)
  2263. {
  2264. while (*prefix && tolower(*prefix) == tolower(*src)) { src++; prefix++; }
  2265. return *prefix==0;
  2266. }
  2267. bool endsWith(const char* src, const char* dst)
  2268. {
  2269. size_t srcLen = strlen(src);
  2270. size_t dstLen = strlen(dst);
  2271. if (dstLen<=srcLen)
  2272. return memcmp(dst, src+srcLen-dstLen, dstLen)==0;
  2273. return false;
  2274. }
  2275. bool endsWithIgnoreCase(const char* src, const char* dst)
  2276. {
  2277. size_t srcLen = strlen(src);
  2278. size_t dstLen = strlen(dst);
  2279. if (dstLen<=srcLen)
  2280. return memicmp(dst, src+srcLen-dstLen, dstLen)==0;
  2281. return false;
  2282. }
  2283. unsigned matchString(const char * search, const char * const * strings)
  2284. {
  2285. for (unsigned i=0;;i++)
  2286. {
  2287. const char * cur = strings[i];
  2288. if (!cur)
  2289. return UINT_MAX;
  2290. if (streq(search, cur))
  2291. return i;
  2292. }
  2293. }
  2294. char *j_strtok_r(char *str, const char *delim, char **saveptr)
  2295. {
  2296. if (!str)
  2297. str = *saveptr;
  2298. char c;
  2299. for (;;) {
  2300. c = *str;
  2301. if (!c) {
  2302. *saveptr = str;
  2303. return NULL;
  2304. }
  2305. if (!strchr(delim,c))
  2306. break;
  2307. str++;
  2308. }
  2309. char *ret=str;
  2310. do {
  2311. c = *(++str);
  2312. } while (c&&!strchr(delim,c));
  2313. if (c)
  2314. *(str++) = 0;
  2315. *saveptr = str;
  2316. return ret;
  2317. }
  2318. int j_memicmp (const void *s1, const void *s2, size32_t len)
  2319. {
  2320. const byte *b1 = (const byte *)s1;
  2321. const byte *b2 = (const byte *)s2;
  2322. int ret = 0;
  2323. while (len&&((ret = tolower(*b1)-tolower(*b2)) == 0)) {
  2324. b1++;
  2325. b2++;
  2326. len--;
  2327. }
  2328. return ret;
  2329. }
  2330. size32_t memcount(size32_t len, const char * str, char search)
  2331. {
  2332. size32_t count = 0;
  2333. for (size32_t i=0; i < len; i++)
  2334. {
  2335. if (str[i] == search)
  2336. count++;
  2337. }
  2338. return count;
  2339. }
  2340. StringBuffer & elideString(StringBuffer & s, unsigned maxLength)
  2341. {
  2342. if (s.length() > maxLength)
  2343. {
  2344. s.setLength(maxLength);
  2345. s.append("...");
  2346. }
  2347. return s;
  2348. }
  2349. const char * nullText(const char * text)
  2350. {
  2351. if (text) return text;
  2352. return "(null)";
  2353. }
  2354. StringBuffer& StringBuffer::operator=(StringBuffer&& value)
  2355. {
  2356. swapWith(value);
  2357. return *this;
  2358. }