jstring.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536
  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. // this method will replace all occurrences of "oldStr" with "newStr"
  828. StringBuffer & StringBuffer::replaceString(const char* oldStr, const char* newStr)
  829. {
  830. if (curLen)
  831. {
  832. StringBuffer temp;
  833. size32_t oldlen = oldStr ? strlen(oldStr) : 0;
  834. size32_t newlen = newStr ? strlen(newStr) : 0;
  835. ::replaceString(temp, curLen, buffer, oldlen, oldStr, newlen, newStr);
  836. swapWith(temp);
  837. }
  838. return *this;
  839. }
  840. StringBuffer & StringBuffer::stripChar(char oldChar)
  841. {
  842. size32_t delta = 0;
  843. size32_t l = curLen;
  844. for (size32_t i = 0; i < l; i++)
  845. {
  846. if (buffer[i] == oldChar)
  847. delta++;
  848. else if (delta)
  849. buffer[i-delta] = buffer[i];
  850. }
  851. if (delta)
  852. curLen = curLen - delta;
  853. return *this;
  854. }
  855. const char * StringBuffer::str() const
  856. {
  857. buffer[curLen] = '\0'; // There is always room for this null
  858. return buffer;
  859. }
  860. //===========================================================================
  861. VStringBuffer::VStringBuffer(const char* format, ...)
  862. {
  863. va_list args;
  864. va_start(args,format);
  865. valist_appendf(format,args);
  866. va_end(args);
  867. }
  868. //===========================================================================
  869. StringAttrBuilder::StringAttrBuilder(StringAttr & _target) : StringBuffer(false), target(_target)
  870. {
  871. }
  872. StringAttrBuilder::~StringAttrBuilder()
  873. {
  874. target.setown(*this);
  875. }
  876. //===========================================================================
  877. String::String()
  878. {
  879. text = (char *)TheNullStr;
  880. }
  881. String::String(const char * value)
  882. {
  883. text = (value ? strdup(value) : (char *)TheNullStr);
  884. }
  885. String::String(const char * value, int offset, int _count)
  886. {
  887. text = (char *)malloc(_count+1);
  888. memcpy(text, value+offset, _count);
  889. text[_count]=0;
  890. }
  891. String::String(String & value)
  892. {
  893. text = strdup(value.str());
  894. }
  895. String::String(StringBuffer & value)
  896. {
  897. unsigned len = value.length();
  898. text = (char *)malloc(len+1);
  899. value.getChars(0,len,text);
  900. text[len] = 0;
  901. }
  902. String::~String()
  903. {
  904. if (text != TheNullStr) free(text);
  905. }
  906. char String::charAt(size32_t index) const
  907. {
  908. return text[index];
  909. }
  910. int String::compareTo(const String & value) const
  911. {
  912. return strcmp(text, value.str());
  913. }
  914. int String::compareTo(const char* value) const
  915. {
  916. return strcmp(text,value);
  917. }
  918. String * String::concat(const String & value) const
  919. {
  920. StringBuffer temp(str());
  921. temp.append(value);
  922. return new String(temp.str());
  923. }
  924. bool String::endsWith(const String & value) const
  925. {
  926. unsigned lenValue = value.length();
  927. unsigned len = (size32_t)strlen(text);
  928. if (len >= lenValue)
  929. return (memcmp(text+(len-lenValue),value.str(),lenValue) == 0);
  930. return false;
  931. }
  932. bool String::endsWith(const char* value) const
  933. {
  934. return ::endsWith(this->text, value);
  935. }
  936. bool String::equals(String & value) const
  937. {
  938. return strcmp(text, value.str())==0;
  939. }
  940. bool String::equalsIgnoreCase(const String & value) const
  941. {
  942. return stricmp(text, value.str())==0;
  943. }
  944. void String::getBytes(int srcBegin, int srcEnd, void * dest, int dstBegin) const
  945. {
  946. memcpy((char *)dest+dstBegin, text+srcBegin, srcEnd-srcBegin);
  947. }
  948. void String::getChars(int srcBegin, int srcEnd, void * dest, int dstBegin) const
  949. {
  950. memcpy((char *)dest+dstBegin, text+srcBegin, srcEnd-srcBegin);
  951. }
  952. int String::hashCode() const
  953. {
  954. return (int)hashc((const byte *)text,length(),0);
  955. }
  956. int String::indexOf(int ch) const
  957. {
  958. char * match = strchr(text, ch);
  959. return match ? (int)(match - text) : -1;
  960. }
  961. int String::indexOf(int ch, int from) const
  962. {
  963. char * match = strchr(text + from, ch);
  964. return match ? (int)(match - text) : -1;
  965. }
  966. int String::indexOf(const String & search) const
  967. {
  968. const char * str = search.str();
  969. const char * match = strstr(text, str);
  970. return match ? (int)(match - text) : -1;
  971. }
  972. int String::indexOf(const String & search, int from) const
  973. {
  974. const char * str = search.str();
  975. const char * match = strstr(text + from, str);
  976. return match ? (int)(match - text) : -1;
  977. }
  978. int String::lastIndexOf(int ch) const
  979. {
  980. char * match = strrchr(text, ch);
  981. return match ? (int)(match - text) : -1;
  982. }
  983. int String::lastIndexOf(int ch, int from) const
  984. {
  985. for (;(from > 0);--from)
  986. if (text[from] == ch)
  987. return from;
  988. return -1;
  989. }
  990. int String::lastIndexOf(const String & search) const
  991. {
  992. assertex(!"TBD");
  993. return -1;
  994. }
  995. int String::lastIndexOf(const String & search, int from) const
  996. {
  997. assertex(!"TBD");
  998. return -1;
  999. }
  1000. size32_t String::length() const
  1001. {
  1002. return (size32_t)strlen(text);
  1003. }
  1004. bool String::startsWith(String & value) const
  1005. {
  1006. unsigned lenValue = value.length();
  1007. const char * search = value.str();
  1008. return (memcmp(text, search, lenValue) == 0);
  1009. }
  1010. bool String::startsWith(String & value, int offset) const
  1011. {
  1012. unsigned lenValue = value.length();
  1013. const char * search = value.str();
  1014. return (memcmp(text + offset, search, lenValue) == 0);
  1015. }
  1016. bool String::startsWith(const char* value) const
  1017. {
  1018. return ::startsWith(this->text,value);
  1019. }
  1020. String * String::substring(int beginIndex) const
  1021. {
  1022. return new String(text+beginIndex);
  1023. }
  1024. String * String::substring(int beginIndex, int endIndex) const
  1025. {
  1026. return new String(text, beginIndex, endIndex - beginIndex);
  1027. }
  1028. const char *String::str() const
  1029. {
  1030. return text;
  1031. }
  1032. String * String::toLowerCase() const
  1033. {
  1034. String *ret = new String();
  1035. size32_t l = length();
  1036. if (l)
  1037. {
  1038. ret->text = (char *)malloc(l+1);
  1039. for (unsigned i = 0; i < l; i++)
  1040. ret->text[i] = tolower(text[i]);
  1041. ret->text[l]=0;
  1042. }
  1043. return ret;
  1044. }
  1045. String * String::toString()
  1046. {
  1047. Link();
  1048. return this;
  1049. }
  1050. String * String::toUpperCase() const
  1051. {
  1052. String *ret = new String();
  1053. size32_t l = length();
  1054. if (l)
  1055. {
  1056. ret->text = (char *)malloc(l+1);
  1057. for (unsigned i = 0; i < l; i++)
  1058. ret->text[i] = toupper(text[i]);
  1059. ret->text[l]=0;
  1060. }
  1061. return ret;
  1062. }
  1063. String * String::trim() const
  1064. {
  1065. size32_t l = length();
  1066. while (l && isspace(text[l-1]))
  1067. l--;
  1068. return new String(text, 0, l);
  1069. }
  1070. //------------------------------------------------
  1071. #if 0
  1072. String & String::valueOf(char value)
  1073. {
  1074. return * new String(&value, 0, 1);
  1075. }
  1076. String & String::valueOf(const char * value)
  1077. {
  1078. return * new String(value);
  1079. }
  1080. String & String::valueOf(const char * value, int offset, int count)
  1081. {
  1082. return * new String(value, offset, count);
  1083. }
  1084. String & String::valueOf(double value)
  1085. {
  1086. StringBuffer temp;
  1087. return temp.append(value).toString();
  1088. }
  1089. String & String::valueOf(float value)
  1090. {
  1091. StringBuffer temp;
  1092. return temp.append(value).toString();
  1093. }
  1094. String & String::valueOf(int value)
  1095. {
  1096. StringBuffer temp;
  1097. return temp.append(value).toString();
  1098. }
  1099. String & String::valueOf(long value)
  1100. {
  1101. StringBuffer temp;
  1102. return temp.append(value).toString();
  1103. }
  1104. #endif
  1105. //------------------------------------------------
  1106. StringAttr::StringAttr(const char * _text)
  1107. {
  1108. text = _text ? strdup(_text) : NULL;
  1109. }
  1110. StringAttr::StringAttr(const char * _text, size_t _len)
  1111. {
  1112. text = NULL;
  1113. set(_text, _len);
  1114. }
  1115. StringAttr::StringAttr(const StringAttr & src)
  1116. {
  1117. text = NULL;
  1118. set(src.get());
  1119. }
  1120. StringAttr::StringAttr(StringAttr && src)
  1121. {
  1122. text = src.text;
  1123. src.text = nullptr;
  1124. }
  1125. StringAttr& StringAttr::operator = (StringAttr && from)
  1126. {
  1127. char *temp = text;
  1128. text = from.text;
  1129. from.text = temp;
  1130. return *this;
  1131. }
  1132. StringAttr& StringAttr::operator = (const StringAttr & from)
  1133. {
  1134. set(from.str());
  1135. return *this;
  1136. }
  1137. void StringAttr::set(const char * _text)
  1138. {
  1139. char * oldtext = text;
  1140. text = _text ? strdup(_text) : NULL;
  1141. free(oldtext);
  1142. }
  1143. void StringAttr::set(const char * _text, size_t _len)
  1144. {
  1145. char * oldtext = text;
  1146. text = (char *)malloc(_len+1);
  1147. memcpy(text, _text, _len);
  1148. text[_len] = 0;
  1149. free(oldtext);
  1150. }
  1151. void StringAttr::setown(const char * _text)
  1152. {
  1153. char * oldtext = text;
  1154. text = (char *)_text;
  1155. free(oldtext);
  1156. }
  1157. void StringAttr::set(const StringBuffer & source)
  1158. {
  1159. if (source.length())
  1160. set(source.str());
  1161. else
  1162. clear();
  1163. }
  1164. void StringAttr::setown(StringBuffer & source)
  1165. {
  1166. if (source.length())
  1167. setown(source.detach());
  1168. else
  1169. clear();
  1170. }
  1171. void StringAttr::toLowerCase()
  1172. {
  1173. if (text)
  1174. {
  1175. char * cur = text;
  1176. char next;
  1177. while ((next = *cur) != 0)
  1178. {
  1179. if (isupper(next))
  1180. *cur = tolower(next);
  1181. cur++;
  1182. }
  1183. }
  1184. }
  1185. void StringAttr::toUpperCase()
  1186. {
  1187. if (text)
  1188. {
  1189. char * cur = text;
  1190. char next;
  1191. while ((next = *cur) != 0)
  1192. {
  1193. if (islower(next))
  1194. *cur = toupper(next);
  1195. cur++;
  1196. }
  1197. }
  1198. }
  1199. StringAttrItem::StringAttrItem(const char *_text, unsigned _len)
  1200. {
  1201. text.set(_text, _len);
  1202. }
  1203. inline char hex(char c, char lower)
  1204. {
  1205. if (c < 10)
  1206. return '0' + c;
  1207. else if (lower)
  1208. return 'a' + c - 10;
  1209. else
  1210. return 'A' + c - 10;
  1211. }
  1212. StringBuffer & StringBuffer::appendhex(unsigned char c, char lower)
  1213. {
  1214. append(hex(c>>4, lower));
  1215. append(hex(c&0xF, lower));
  1216. return *this;
  1217. }
  1218. void appendURL(StringBuffer *dest, const char *src, size32_t len, char lower)
  1219. {
  1220. if (len == (size32_t)-1)
  1221. len = (size32_t)strlen(src);
  1222. while (len)
  1223. {
  1224. // isalnum seems to give weird results for chars > 127....
  1225. unsigned char c = (unsigned char) *src;
  1226. if (c == ' ')
  1227. dest->append('+');
  1228. else if ((c & 0x80) || !isalnum(*src))
  1229. {
  1230. dest->append('%');
  1231. dest->appendhex(c, lower);
  1232. }
  1233. else
  1234. dest->append(c);
  1235. src++;
  1236. len--;
  1237. }
  1238. }
  1239. inline char translateHex(char hex)
  1240. {
  1241. if(hex >= 'A')
  1242. return (hex & 0xdf) - 'A' + 10;
  1243. else
  1244. return hex - '0';
  1245. }
  1246. inline char translateHex(char h1, char h2)
  1247. {
  1248. return (translateHex(h1) * 16 + translateHex(h2));
  1249. }
  1250. StringBuffer &appendDecodedURL(StringBuffer &s, const char *url)
  1251. {
  1252. if(!url)
  1253. return s;
  1254. while (*url)
  1255. {
  1256. char c = *url++;
  1257. if (c == '+')
  1258. c = ' ';
  1259. else if (c == '%')
  1260. {
  1261. if (isxdigit(url[0]) && isxdigit(url[1]))
  1262. {
  1263. c = translateHex(url[0], url[1]);
  1264. url+=2;
  1265. }
  1266. }
  1267. s.append(c);
  1268. }
  1269. return s;
  1270. }
  1271. static StringBuffer & appendStringExpandControl(StringBuffer &out, unsigned len, const char * src, bool addBreak, bool isCpp, bool isUtf8)
  1272. {
  1273. const int minBreakPos = 0;
  1274. const int commaBreakPos = 70;
  1275. const int maxBreakPos = 120;
  1276. const char * startLine = src;
  1277. out.ensureCapacity(len+2);
  1278. for (; len > 0; --len)
  1279. {
  1280. unsigned char c = *src++;
  1281. bool insertBreak = false;
  1282. bool allowBreak = true;
  1283. switch (c)
  1284. {
  1285. case '\n':
  1286. {
  1287. out.append("\\n");
  1288. if (src-startLine > minBreakPos)
  1289. insertBreak = true;
  1290. break;
  1291. }
  1292. case ',':
  1293. {
  1294. out.append(c);
  1295. if (src-startLine > commaBreakPos)
  1296. insertBreak = true;
  1297. break;
  1298. }
  1299. case '\r': out.append("\\r"); break;
  1300. case '\t': out.append("\\t"); break;
  1301. case '"':
  1302. if (isCpp)
  1303. out.append("\\");
  1304. out.append(c);
  1305. break;
  1306. case '\'':
  1307. if (!isCpp)
  1308. out.append("\\");
  1309. out.append(c);
  1310. break;
  1311. case '\\': out.append("\\\\"); break;
  1312. case '?':
  1313. if (isCpp)
  1314. {
  1315. //stop trigraphs being generated.... quote the second ?
  1316. out.append(c);
  1317. if ((len!=1) && (*src == '?'))
  1318. {
  1319. out.append('\\');
  1320. allowBreak = false;
  1321. }
  1322. }
  1323. else
  1324. out.append(c);
  1325. break;
  1326. default:
  1327. if (isUtf8 || ((c >= ' ') && (c <= 126)))
  1328. out.append(c);
  1329. else
  1330. out.appendf("\\%03o", c);
  1331. break;
  1332. }
  1333. if (addBreak && (insertBreak || (allowBreak && src-startLine >= maxBreakPos)))
  1334. {
  1335. out.append("\"").newline().append("\t\t\"");
  1336. startLine = src;
  1337. }
  1338. }
  1339. return out;
  1340. }
  1341. StringBuffer & appendStringAsCPP(StringBuffer &out, unsigned len, const char * src, bool addBreak)
  1342. {
  1343. return appendStringExpandControl(out, len, src, addBreak, true, false);
  1344. }
  1345. StringBuffer & appendStringAsECL(StringBuffer &out, unsigned len, const char * src)
  1346. {
  1347. return appendStringExpandControl(out, len, src, false, false, false);
  1348. }
  1349. StringBuffer & appendUtf8AsECL(StringBuffer &out, unsigned len, const char * src)
  1350. {
  1351. return appendStringExpandControl(out, len, src, false, false, true);
  1352. }
  1353. StringBuffer & appendStringAsQuotedCPP(StringBuffer &out, unsigned len, const char * src, bool addBreak)
  1354. {
  1355. out.ensureCapacity(len+2);
  1356. out.append('\"');
  1357. appendStringAsCPP(out, len, src, addBreak);
  1358. return out.append('\"');
  1359. }
  1360. StringBuffer & appendStringAsQuotedECL(StringBuffer &out, unsigned len, const char * src)
  1361. {
  1362. out.ensureCapacity(len+2);
  1363. out.append('\'');
  1364. appendStringAsECL(out, len, src);
  1365. return out.append('\'');
  1366. }
  1367. void extractItem(StringBuffer & res, const char * src, const char * sep, int whichItem, bool caps)
  1368. {
  1369. bool isSeparator[256];
  1370. memset(isSeparator,0,sizeof(isSeparator));
  1371. unsigned char * finger = (unsigned char *)sep;
  1372. while (*finger !=0)
  1373. isSeparator[*finger++] = true;
  1374. isSeparator[0]=true;
  1375. finger = (unsigned char *)src;
  1376. unsigned char next;
  1377. for (;;)
  1378. {
  1379. while (isSeparator[(next = *finger)])
  1380. {
  1381. if (next == 0) return;
  1382. finger++;
  1383. }
  1384. if (whichItem == 0)
  1385. {
  1386. while (!isSeparator[(next = *finger)])
  1387. {
  1388. if (caps)
  1389. next = toupper(next);
  1390. res.append(next);
  1391. finger++;
  1392. }
  1393. return;
  1394. }
  1395. while (!isSeparator[*finger])
  1396. finger++;
  1397. whichItem--;
  1398. }
  1399. }
  1400. int utf8CharLen(unsigned char ch)
  1401. {
  1402. //return 1 if this is an ascii character,
  1403. //or 0 if its not a valid utf-8 character
  1404. if (ch < 128)
  1405. return 1;
  1406. if (ch < 192)
  1407. return 0;
  1408. unsigned char len = 1;
  1409. for (unsigned char lead = ch << 1; (lead & 0x80); lead <<=1)
  1410. len++;
  1411. return len;
  1412. }
  1413. int utf8CharLen(const unsigned char *ch, unsigned maxsize)
  1414. {
  1415. //return 1 if this is an ascii character,
  1416. //or 0 if its not a valid utf-8 character
  1417. if (*ch < 128)
  1418. return 1;
  1419. unsigned char len = utf8CharLen(*ch);
  1420. if (len>maxsize)
  1421. return 0;
  1422. for (unsigned pos = 1; pos < len; pos++)
  1423. if ((ch[pos] < 128) || (ch[pos] >= 192))
  1424. return 0; //its not a valid utf-8 character after all
  1425. return len;
  1426. }
  1427. const char *encodeXML(const char *x, StringBuffer &ret, unsigned flags, unsigned len, bool utf8)
  1428. {
  1429. while (len)
  1430. {
  1431. switch(*x)
  1432. {
  1433. case '&':
  1434. ret.append("&amp;");
  1435. break;
  1436. case '<':
  1437. ret.append("&lt;");
  1438. break;
  1439. case '>':
  1440. ret.append("&gt;");
  1441. break;
  1442. case '\"':
  1443. ret.append("&quot;");
  1444. break;
  1445. case '\'':
  1446. ret.append("&apos;");
  1447. break;
  1448. case ' ':
  1449. ret.append(flags & ENCODE_SPACES?"&#32;":" ");
  1450. break;
  1451. case '\n':
  1452. ret.append(flags & ENCODE_NEWLINES?"&#10;":"\n");
  1453. break;
  1454. case '\r':
  1455. ret.append(flags & ENCODE_NEWLINES?"&#13;":"\r");
  1456. break;
  1457. case '\t':
  1458. ret.append(flags & ENCODE_SPACES?"&#9;":"\t");
  1459. break;
  1460. case '\0':
  1461. if (len == (unsigned) -1)
  1462. return x;
  1463. ret.append("&#xe000;"); // hack!!! Characters below 0x20 are not legal in strict xml, even encoded.
  1464. break;
  1465. default:
  1466. if (*x >= ' ' && ((byte)*x) < 128)
  1467. ret.append(*x);
  1468. else if (*x < ' ' && *x > 0)
  1469. ret.append("&#xe0").appendhex(*x, true).append(';'); // HACK
  1470. else if (utf8)
  1471. {
  1472. unsigned chlen = utf8CharLen((const unsigned char *)x);
  1473. if (chlen==0)
  1474. ret.append("&#").append((unsigned int)*(unsigned char *) x).append(';');
  1475. else
  1476. {
  1477. ret.append(*x);
  1478. while(--chlen)
  1479. {
  1480. if (len != (unsigned) -1)
  1481. len--;
  1482. ret.append(*(++x));
  1483. }
  1484. }
  1485. }
  1486. else
  1487. ret.append("&#").append((unsigned int)*(unsigned char *) x).append(';');
  1488. break;
  1489. }
  1490. if (len != (unsigned) -1)
  1491. len--;
  1492. ++x;
  1493. }
  1494. return x;
  1495. }
  1496. const char *encodeXML(const char *x, IIOStream &out, unsigned flags, unsigned len, bool utf8)
  1497. {
  1498. while (len)
  1499. {
  1500. switch(*x)
  1501. {
  1502. case '&':
  1503. writeStringToStream(out, "&amp;");
  1504. break;
  1505. case '<':
  1506. writeStringToStream(out, "&lt;");
  1507. break;
  1508. case '>':
  1509. writeStringToStream(out, "&gt;");
  1510. break;
  1511. case '\"':
  1512. writeStringToStream(out, "&quot;");
  1513. break;
  1514. case '\'':
  1515. writeStringToStream(out, "&apos;");
  1516. break;
  1517. case ' ':
  1518. writeStringToStream(out, flags & ENCODE_SPACES?"&#32;":" ");
  1519. break;
  1520. case '\n':
  1521. writeStringToStream(out, flags & ENCODE_NEWLINES?"&#10;":"\n");
  1522. break;
  1523. case '\r':
  1524. writeStringToStream(out, flags & ENCODE_NEWLINES?"&#13;":"\r");
  1525. break;
  1526. case '\t':
  1527. writeStringToStream(out, flags & ENCODE_SPACES?"&#9;":"\t");
  1528. break;
  1529. case '\0':
  1530. if (len == (unsigned) -1)
  1531. return x;
  1532. writeStringToStream(out, "&#xe000;"); // hack!!! Characters below 0x20 are not legal in strict xml, even encoded.
  1533. break;
  1534. default:
  1535. if (*x >= ' ' && ((byte)*x) < 128)
  1536. writeCharToStream(out, *x);
  1537. else if (*x < ' ' && *x > 0)
  1538. {
  1539. writeStringToStream(out, "&#xe0");
  1540. unsigned char c = *(unsigned char *)x;
  1541. writeCharToStream(out, hex(c>>4, true));
  1542. writeCharToStream(out, hex(c&0xF, true));
  1543. writeCharToStream(out, ';'); // HACK
  1544. }
  1545. else if (utf8)
  1546. {
  1547. int chlen = utf8CharLen((const unsigned char *)x);
  1548. if (chlen==0)
  1549. {
  1550. writeStringToStream(out, "&#");
  1551. char tmp[12];
  1552. unsigned written = numtostr(tmp, *(unsigned char *)x);
  1553. out.write(written, tmp);
  1554. writeCharToStream(out, ';');
  1555. }
  1556. else
  1557. {
  1558. writeCharToStream(out, *x);
  1559. while(--chlen)
  1560. {
  1561. if (len != (unsigned) -1)
  1562. len--;
  1563. writeCharToStream(out, *(++x));
  1564. }
  1565. }
  1566. }
  1567. else
  1568. {
  1569. writeStringToStream(out, "&#");
  1570. char tmp[12];
  1571. unsigned written = numtostr(tmp, *(unsigned char *)x);
  1572. out.write(written, tmp);
  1573. writeCharToStream(out, ';');
  1574. }
  1575. break;
  1576. }
  1577. if (len != (unsigned) -1)
  1578. len--;
  1579. ++x;
  1580. }
  1581. return x;
  1582. }
  1583. static void writeUtf8(unsigned c, StringBuffer &out)
  1584. {
  1585. if (c < 0x80)
  1586. out.append((char)c);
  1587. else if (c < 0x800)
  1588. {
  1589. out.append((char)(0xC0 | (c>>6)));
  1590. out.append((char)(0x80 | (c & 0x3F)));
  1591. }
  1592. else if (c < 0x10000)
  1593. {
  1594. out.append((char) (0xE0 | (c>>12)));
  1595. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1596. out.append((char) (0x80 | (c & 0x3F)));
  1597. }
  1598. else if (c < 0x200000)
  1599. {
  1600. out.append((char) (0xF0 | (c>>18)));
  1601. out.append((char) (0x80 | (c>>12 & 0x3F)));
  1602. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1603. out.append((char) (0x80 | (c & 0x3F)));
  1604. }
  1605. else if (c < 0x4000000)
  1606. {
  1607. out.append((char) (0xF8 | (c>>24)));
  1608. out.append((char) (0x80 | (c>>18 & 0x3F)));
  1609. out.append((char) (0x80 | (c>>12 & 0x3F)));
  1610. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1611. out.append((char) (0x80 | (c & 0x3F)));
  1612. }
  1613. else if (c < 0x80000000)
  1614. {
  1615. out.append((char) (0xFC | (c>>30)));
  1616. out.append((char) (0x80 | (c>>24 & 0x3F)));
  1617. out.append((char) (0x80 | (c>>18 & 0x3F)));
  1618. out.append((char) (0x80 | (c>>12 & 0x3F)));
  1619. out.append((char) (0x80 | (c>>6 & 0x3F)));
  1620. out.append((char) (0x80 | (c & 0x3F)));
  1621. }
  1622. else
  1623. assertex(false);
  1624. }
  1625. #define JSONSTRICT
  1626. const char *decodeJSON(const char *j, StringBuffer &ret, unsigned len, const char **errMark)
  1627. {
  1628. if (!j)
  1629. return j;
  1630. if ((unsigned)-1 == len)
  1631. len = (unsigned)strlen(j);
  1632. try
  1633. {
  1634. for (const char *end = j+len; j<end && *j; j++)
  1635. {
  1636. if (*j!='\\')
  1637. ret.append(*j);
  1638. else
  1639. {
  1640. switch (*++j)
  1641. {
  1642. case 'u':
  1643. {
  1644. j++;
  1645. if (end-j>=4)
  1646. {
  1647. char *endptr;
  1648. StringAttr s(j, 4);
  1649. unsigned val = strtoul(s.get(), &endptr, 16);
  1650. if (endptr && !*endptr)
  1651. {
  1652. writeUtf8(val, ret);
  1653. j+=3;
  1654. break;
  1655. }
  1656. }
  1657. #ifdef JSONSTRICT
  1658. throw MakeStringException(-1, "invalid json \\u escaped sequence");
  1659. #endif
  1660. ret.append(*j);
  1661. break;
  1662. }
  1663. case '\"':
  1664. case '\\':
  1665. case '/':
  1666. ret.append(*j);
  1667. break;
  1668. case 'b':
  1669. ret.append('\b');
  1670. break;
  1671. case 'f':
  1672. ret.append('\f');
  1673. break;
  1674. case 'n':
  1675. ret.append('\n');
  1676. continue;
  1677. case 'r':
  1678. ret.append('\r');
  1679. break;
  1680. case 't':
  1681. ret.append('\t');
  1682. break;
  1683. default:
  1684. {
  1685. #ifdef JSONSTRICT
  1686. throw MakeStringException(-1, "invalid json escaped sequence");
  1687. #endif
  1688. ret.append('\\');
  1689. ret.append(*j);
  1690. break;
  1691. }
  1692. }
  1693. }
  1694. }
  1695. }
  1696. catch (IException *)
  1697. {
  1698. if (errMark) *errMark = j;
  1699. throw;
  1700. }
  1701. return j;
  1702. }
  1703. void decodeXML(ISimpleReadStream &in, StringBuffer &out, unsigned len)
  1704. {
  1705. // TODO
  1706. UNIMPLEMENTED;
  1707. }
  1708. const char *decodeXML(const char *x, StringBuffer &ret, const char **errMark, IEntityHelper *entityHelper, bool strict)
  1709. {
  1710. if (!x)
  1711. return x;
  1712. try
  1713. {
  1714. while (*x)
  1715. {
  1716. if ('&' == *x)
  1717. {
  1718. switch (x[1])
  1719. {
  1720. case 'a':
  1721. switch (x[2])
  1722. {
  1723. case 'm':
  1724. {
  1725. if ('p' == x[3] && ';' == x[4])
  1726. {
  1727. x += 5;
  1728. ret.append('&');
  1729. continue;
  1730. }
  1731. break;
  1732. }
  1733. case 'p':
  1734. {
  1735. if ('o' == x[3] && 's' == x[4] && ';' == x[5])
  1736. {
  1737. x += 6;
  1738. ret.append('\'');
  1739. continue;
  1740. }
  1741. break;
  1742. }
  1743. }
  1744. break;
  1745. case 'l':
  1746. if ('t' == x[2] && ';' == x[3])
  1747. {
  1748. x += 4;
  1749. ret.append('<');
  1750. continue;
  1751. }
  1752. break;
  1753. case 'g':
  1754. if ('t' == x[2] && ';' == x[3])
  1755. {
  1756. x += 4;
  1757. ret.append('>');
  1758. continue;
  1759. }
  1760. break;
  1761. case 'q':
  1762. if ('u' == x[2] && 'o' == x[3] && 't' == x[4] && ';' == x[5])
  1763. {
  1764. x += 6;
  1765. ret.append('"');
  1766. continue;
  1767. }
  1768. break;
  1769. case 'n':
  1770. if ('b' == x[2] && 's' == x[3] && 'p' == x[4] && ';' == x[5])
  1771. {
  1772. x += 6;
  1773. writeUtf8(0xa0, ret);
  1774. continue;
  1775. }
  1776. break;
  1777. case '#':
  1778. {
  1779. const char *numstart = x+2;
  1780. int base = 10;
  1781. if (*numstart == 'x')
  1782. {
  1783. base = 16;
  1784. numstart++;
  1785. }
  1786. char *numend;
  1787. unsigned val = strtoul(numstart, &numend, base);
  1788. if (numstart==numend || *numend != ';')
  1789. {
  1790. if (strict)
  1791. throw MakeStringException(-1, "invalid escaped sequence");
  1792. }
  1793. else // always convert to utf-8. Should potentially throw error if not marked as utf-8 encoded doc and out of ascii range.
  1794. {
  1795. writeUtf8(val, ret);
  1796. x = numend+1;
  1797. continue;
  1798. }
  1799. break;
  1800. }
  1801. case ';':
  1802. case '\0':
  1803. if (strict)
  1804. throw MakeStringException(-1, "invalid escaped sequence");
  1805. break;
  1806. default:
  1807. if (entityHelper)
  1808. {
  1809. const char *start=x+1;
  1810. const char *finger=start;
  1811. while (*finger && *finger != ';')
  1812. ++finger;
  1813. if (*finger == ';')
  1814. {
  1815. StringBuffer entity(finger-start, start);
  1816. if (entityHelper->find(entity, ret))
  1817. {
  1818. x = finger + 1;
  1819. continue;
  1820. }
  1821. }
  1822. }
  1823. if (strict)
  1824. throw MakeStringException(-1, "invalid escaped sequence");
  1825. break;
  1826. }
  1827. }
  1828. ret.append(*x);
  1829. ++x;
  1830. }
  1831. }
  1832. catch (IException *)
  1833. {
  1834. if (errMark) *errMark = x;
  1835. throw;
  1836. }
  1837. return x;
  1838. }
  1839. StringBuffer & appendXMLOpenTag(StringBuffer &xml, const char *tag, const char *prefix, bool complete, bool close, const char *uri)
  1840. {
  1841. if (!tag || !*tag)
  1842. return xml;
  1843. xml.append('<');
  1844. appendXMLTagName(xml, tag, prefix);
  1845. if (uri && *uri)
  1846. {
  1847. xml.append(" xmlns");
  1848. if (prefix && *prefix)
  1849. xml.append(':').append(prefix);
  1850. xml.append("=\"").append(uri).append('\"');
  1851. }
  1852. if (complete)
  1853. {
  1854. if (close)
  1855. xml.append('/');
  1856. xml.append('>');
  1857. }
  1858. return xml;
  1859. }
  1860. jlib_decl StringBuffer &appendJSONName(StringBuffer &s, const char *name)
  1861. {
  1862. if (!name || !*name)
  1863. return s;
  1864. delimitJSON(s);
  1865. return encodeJSON(s.append('"'), name).append("\": ");
  1866. }
  1867. jlib_decl StringBuffer &appendfJSONName(StringBuffer &s, const char *format, ...)
  1868. {
  1869. va_list args;
  1870. va_start(args, format);
  1871. StringBuffer vs;
  1872. vs.valist_appendf(format, args);
  1873. va_end(args);
  1874. return appendJSONName(s, vs);
  1875. }
  1876. static char hexchar[] = "0123456789ABCDEF";
  1877. jlib_decl StringBuffer &appendJSONDataValue(StringBuffer& s, const char *name, unsigned len, const void *_value)
  1878. {
  1879. appendJSONNameOrDelimit(s, name);
  1880. s.append('"');
  1881. const unsigned char *value = (const unsigned char *) _value;
  1882. for (unsigned int i = 0; i < len; i++)
  1883. s.append(hexchar[value[i] >> 4]).append(hexchar[value[i] & 0x0f]);
  1884. return s.append('"');
  1885. }
  1886. StringBuffer &appendJSONRealValue(StringBuffer& s, const char *name, double value)
  1887. {
  1888. appendJSONNameOrDelimit(s, name);
  1889. bool quoted = j_isnan(value) || j_isinf(value);
  1890. if (quoted)
  1891. s.append('"');
  1892. s.append(value);
  1893. if (quoted)
  1894. s.append('"');
  1895. return s;
  1896. }
  1897. inline StringBuffer &encodeJSONChar(StringBuffer &s, const char *&ch, unsigned &remaining)
  1898. {
  1899. byte next = *ch;
  1900. switch (next)
  1901. {
  1902. case '\b':
  1903. s.append("\\b");
  1904. break;
  1905. case '\f':
  1906. s.append("\\f");
  1907. break;
  1908. case '\n':
  1909. s.append("\\n");
  1910. break;
  1911. case '\r':
  1912. s.append("\\r");
  1913. break;
  1914. case '\t':
  1915. s.append("\\t");
  1916. break;
  1917. case '\"':
  1918. case '\\':
  1919. case '/':
  1920. s.append('\\');
  1921. s.append(next);
  1922. break;
  1923. case '\0':
  1924. s.append("\\u0000");
  1925. break;
  1926. case '\x7f':
  1927. s.append("\\u007f");
  1928. break;
  1929. default:
  1930. if (next >= ' ' && next < 128)
  1931. s.append(next);
  1932. else if (next < ' ')
  1933. s.append("\\u00").appendhex(next, true);
  1934. else //json is always supposed to be utf8 (or other unicode formats)
  1935. {
  1936. unsigned chlen = utf8CharLen((const unsigned char *)ch, remaining);
  1937. if (chlen==0)
  1938. s.append("\\u00").appendhex(next, true);
  1939. else
  1940. {
  1941. s.append(chlen, ch);
  1942. ch += (chlen-1);
  1943. remaining -= (chlen-1);
  1944. }
  1945. }
  1946. break;
  1947. }
  1948. ch++;
  1949. remaining--;
  1950. return s;
  1951. }
  1952. StringBuffer &encodeJSON(StringBuffer &s, unsigned size, const char *value)
  1953. {
  1954. if (!value)
  1955. return s;
  1956. while (size)
  1957. encodeJSONChar(s, value, size);
  1958. return s;
  1959. }
  1960. StringBuffer &encodeJSON(StringBuffer &s, const char *value)
  1961. {
  1962. if (!value)
  1963. return s;
  1964. return encodeJSON(s, strlen(value), value);
  1965. }
  1966. void decodeCppEscapeSequence(StringBuffer & out, const char * in, bool errorIfInvalid)
  1967. {
  1968. out.ensureCapacity((size32_t)strlen(in));
  1969. while (*in)
  1970. {
  1971. char c = *in++;
  1972. if (c == '\\')
  1973. {
  1974. char next = *in;
  1975. if (next)
  1976. {
  1977. in++;
  1978. switch (next)
  1979. {
  1980. case 'a': c = '\a'; break;
  1981. case 'b': c = '\b'; break;
  1982. case 'f': c = '\f'; break;
  1983. case 'n': c = '\n'; break;
  1984. case 'r': c = '\r'; break;
  1985. case 't': c = '\t'; break;
  1986. case 'v': c = '\v'; break;
  1987. case '\\':
  1988. case '\'':
  1989. case '?':
  1990. case '\"': break;
  1991. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
  1992. {
  1993. c = next - '0';
  1994. if (*in >= '0' && *in <= '7')
  1995. {
  1996. c = c << 3 | (*in++-'0');
  1997. if (*in >= '0' && *in <= '7')
  1998. c = c << 3 | (*in++-'0');
  1999. }
  2000. break;
  2001. }
  2002. case 'x':
  2003. c = 0;
  2004. while (isxdigit(*in))
  2005. {
  2006. next = *in++;
  2007. c = c << 4;
  2008. if (next >= '0' && next <= '9') c |= (next - '0');
  2009. else if (next >= 'A' && next <= 'F') c |= (next - 'A' + 10);
  2010. else if (next >= 'a' && next <= 'f') c |= (next - 'a' + 10);
  2011. }
  2012. break;
  2013. default:
  2014. if (errorIfInvalid)
  2015. throw MakeStringException(1, "unrecognised character escape sequence '\\%c'", next);
  2016. in--; // keep it as is.
  2017. break;
  2018. }
  2019. }
  2020. }
  2021. out.append(c);
  2022. }
  2023. }
  2024. bool isPrintable(unsigned len, const char * src)
  2025. {
  2026. while (len--)
  2027. {
  2028. if (!isprint(*((unsigned char *)src)))
  2029. return false;
  2030. src++;
  2031. }
  2032. return true;
  2033. }
  2034. //make this as fast as possible...
  2035. StringBuffer & appendStringAsSQL(StringBuffer & out, unsigned len, const char * src)
  2036. {
  2037. if (!isPrintable(len, src))
  2038. {
  2039. out.append("X'");
  2040. appendDataAsHex(out, len, src);
  2041. return out.append('\'');
  2042. }
  2043. out.ensureCapacity(2 + len);
  2044. out.append('\'');
  2045. for (;;)
  2046. {
  2047. char * next = (char *)memchr(src, '\'', len);
  2048. if (!next)
  2049. break;
  2050. unsigned chunk=(size32_t)(next-src)+1;
  2051. out.append(chunk, src).append('\'');
  2052. len -= chunk;
  2053. src += chunk;
  2054. }
  2055. return out.append(len, src).append('\'');
  2056. }
  2057. static const char * hexText = "0123456789ABCDEF";
  2058. StringBuffer & appendDataAsHex(StringBuffer &out, unsigned len, const void * data)
  2059. {
  2060. char * target = (char *)out.reserve(len*2);
  2061. unsigned char * start = (unsigned char *)data;
  2062. for (unsigned count=len; count> 0; --count)
  2063. {
  2064. unsigned next = *start++;
  2065. *target++ = hexText[next >>4];
  2066. *target++ = hexText[next & 15];
  2067. }
  2068. return out;
  2069. }
  2070. bool strToBool(size_t len, const char * text)
  2071. {
  2072. switch (len)
  2073. {
  2074. case 4:
  2075. if (memicmp(text, "true", 4) == 0)
  2076. return true;
  2077. break;
  2078. case 3:
  2079. if (memicmp(text, "yes", 3) == 0)
  2080. return true;
  2081. break;
  2082. case 2:
  2083. if (memicmp(text, "on", 2) == 0)
  2084. return true;
  2085. break;
  2086. case 1:
  2087. if ((memicmp(text, "t", 1) == 0) || (memicmp(text, "y", 1) == 0))
  2088. return true;
  2089. break;
  2090. }
  2091. while (len && isspace(*text))
  2092. {
  2093. len--;
  2094. text++;
  2095. }
  2096. while (len-- && isdigit(*text))
  2097. {
  2098. if (*text++ != '0') return true;
  2099. }
  2100. return false;
  2101. }
  2102. bool strToBool(const char * text)
  2103. {
  2104. return strToBool(strlen(text), text);
  2105. }
  2106. bool clipStrToBool(size_t len, const char * text)
  2107. {
  2108. while (len && *text==' ')
  2109. {
  2110. len--;
  2111. text++;
  2112. }
  2113. while (len && text[len-1]== ' ')
  2114. len--;
  2115. return strToBool(len, text);
  2116. }
  2117. bool clipStrToBool(const char * text)
  2118. {
  2119. return clipStrToBool(strlen(text), text);
  2120. }
  2121. StringBuffer & ncnameEscape(char const * in, StringBuffer & out)
  2122. {
  2123. if(!isalpha(*in))
  2124. {
  2125. out.appendf("_%02X", static_cast<unsigned char>(*in));
  2126. in++;
  2127. }
  2128. char const * finger = in;
  2129. while(*finger)
  2130. {
  2131. if(!isalnum(*finger))
  2132. {
  2133. if(finger>in)
  2134. out.append((size32_t)(finger-in), in);
  2135. out.appendf("_%02X", static_cast<unsigned char>(*finger));
  2136. in = ++finger;
  2137. }
  2138. else
  2139. {
  2140. finger++;
  2141. }
  2142. }
  2143. if(finger>in)
  2144. out.append((size32_t)(finger-in), in);
  2145. return out;
  2146. }
  2147. StringBuffer & ncnameUnescape(char const * in, StringBuffer & out)
  2148. {
  2149. char const * finger = in;
  2150. while(*finger)
  2151. {
  2152. if(*finger == '_')
  2153. {
  2154. if(finger>in)
  2155. out.append((size32_t)(finger-in), in);
  2156. unsigned char chr = 16 * hex2num(finger[1]) + hex2num(finger[2]);
  2157. out.append(static_cast<char>(chr));
  2158. in = (finger+=3);
  2159. }
  2160. else
  2161. {
  2162. finger++;
  2163. }
  2164. }
  2165. if(finger>in)
  2166. out.append((size32_t)(finger-in), in);
  2167. return out;
  2168. }
  2169. bool startsWith(const char* src, const char* dst)
  2170. {
  2171. while (*dst && *dst == *src) { src++; dst++; }
  2172. return *dst==0;
  2173. }
  2174. bool startsWithIgnoreCase(const char* src, const char* dst)
  2175. {
  2176. while (*dst && tolower(*dst) == tolower(*src)) { src++; dst++; }
  2177. return *dst==0;
  2178. }
  2179. bool endsWith(const char* src, const char* dst)
  2180. {
  2181. size_t srcLen = strlen(src);
  2182. size_t dstLen = strlen(dst);
  2183. if (dstLen<=srcLen)
  2184. return memcmp(dst, src+srcLen-dstLen, dstLen)==0;
  2185. return false;
  2186. }
  2187. bool endsWithIgnoreCase(const char* src, const char* dst)
  2188. {
  2189. size_t srcLen = strlen(src);
  2190. size_t dstLen = strlen(dst);
  2191. if (dstLen<=srcLen)
  2192. return memicmp(dst, src+srcLen-dstLen, dstLen)==0;
  2193. return false;
  2194. }
  2195. char *j_strtok_r(char *str, const char *delim, char **saveptr)
  2196. {
  2197. if (!str)
  2198. str = *saveptr;
  2199. char c;
  2200. for (;;) {
  2201. c = *str;
  2202. if (!c) {
  2203. *saveptr = str;
  2204. return NULL;
  2205. }
  2206. if (!strchr(delim,c))
  2207. break;
  2208. str++;
  2209. }
  2210. char *ret=str;
  2211. do {
  2212. c = *(++str);
  2213. } while (c&&!strchr(delim,c));
  2214. if (c)
  2215. *(str++) = 0;
  2216. *saveptr = str;
  2217. return ret;
  2218. }
  2219. int j_memicmp (const void *s1, const void *s2, size32_t len)
  2220. {
  2221. const byte *b1 = (const byte *)s1;
  2222. const byte *b2 = (const byte *)s2;
  2223. int ret = 0;
  2224. while (len&&((ret = tolower(*b1)-tolower(*b2)) == 0)) {
  2225. b1++;
  2226. b2++;
  2227. len--;
  2228. }
  2229. return ret;
  2230. }
  2231. size32_t memcount(size32_t len, const char * str, char search)
  2232. {
  2233. size32_t count = 0;
  2234. for (size32_t i=0; i < len; i++)
  2235. {
  2236. if (str[i] == search)
  2237. count++;
  2238. }
  2239. return count;
  2240. }
  2241. StringBuffer & elideString(StringBuffer & s, unsigned maxLength)
  2242. {
  2243. if (s.length() > maxLength)
  2244. {
  2245. s.setLength(maxLength);
  2246. s.append("...");
  2247. }
  2248. return s;
  2249. }
  2250. const char * nullText(const char * text)
  2251. {
  2252. if (text) return text;
  2253. return "(null)";
  2254. }
  2255. StringBuffer& StringBuffer::operator=(StringBuffer&& value)
  2256. {
  2257. swapWith(value);
  2258. return *this;
  2259. }