jflz.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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. /*
  14. FastLZ - lightning-fast lossless compression library
  15. Copyright (C) 2007 Ariya Hidayat (ariya@kde.org)
  16. Copyright (C) 2006 Ariya Hidayat (ariya@kde.org)
  17. Copyright (C) 2005 Ariya Hidayat (ariya@kde.org)
  18. Permission is hereby granted, free of charge, to any person obtaining a copy
  19. of this software and associated documentation files (the "Software"), to deal
  20. in the Software without restriction, including without limitation the rights
  21. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  22. copies of the Software, and to permit persons to whom the Software is
  23. furnished to do so, subject to the following conditions:
  24. The above copyright notice and this permission notice shall be included in
  25. all copies or substantial portions of the Software.
  26. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  27. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  28. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  29. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  30. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  31. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  32. THE SOFTWARE.
  33. */
  34. #if !defined(FASTLZ__COMPRESSOR) && !defined(FASTLZ_DECOMPRESSOR)
  35. // adapted for jlib
  36. #include "platform.h"
  37. #include "jflz.hpp"
  38. #include "jcrc.hpp"
  39. /*
  40. * Always check for bound when decompressing.
  41. * Generally it is best to leave it defined.
  42. */
  43. #define FASTLZ_SAFE
  44. /*
  45. * Give hints to the compiler for branch prediction optimization.
  46. */
  47. #if defined(__GNUC__) && (__GNUC__ > 2)
  48. #define FASTLZ_EXPECT_CONDITIONAL(c) (__builtin_expect((c), 1))
  49. #define FASTLZ_UNEXPECT_CONDITIONAL(c) (__builtin_expect((c), 0))
  50. #else
  51. #define FASTLZ_EXPECT_CONDITIONAL(c) (c)
  52. #define FASTLZ_UNEXPECT_CONDITIONAL(c) (c)
  53. #endif
  54. /*
  55. * Use inlined functions for supported systems.
  56. */
  57. #if defined(__GNUC__) || defined(__DMC__) || defined(__POCC__) || defined(__WATCOMC__) || defined(__SUNPRO_C)
  58. #define FASTLZ_INLINE inline
  59. #elif defined(__BORLANDC__) || defined(_MSC_VER) || defined(__LCC__)
  60. #define FASTLZ_INLINE __inline
  61. #else
  62. #define FASTLZ_INLINE
  63. #endif
  64. /*
  65. * Prevent accessing more than 8-bit at once, except on x86 architectures.
  66. */
  67. #if !defined(FASTLZ_STRICT_ALIGN)
  68. #define FASTLZ_STRICT_ALIGN
  69. #if defined(__i386__) || defined(__386) /* GNU C, Sun Studio */
  70. #undef FASTLZ_STRICT_ALIGN
  71. #elif defined(__i486__) || defined(__i586__) || defined(__i686__) /* GNU C */
  72. #undef FASTLZ_STRICT_ALIGN
  73. #elif defined(_M_IX86) /* Intel, MSVC */
  74. #undef FASTLZ_STRICT_ALIGN
  75. #elif defined(__386)
  76. #undef FASTLZ_STRICT_ALIGN
  77. #elif defined(_X86_) /* MinGW */
  78. #undef FASTLZ_STRICT_ALIGN
  79. #elif defined(__I86__) /* Digital Mars */
  80. #undef FASTLZ_STRICT_ALIGN
  81. #endif
  82. #endif
  83. /*
  84. * FIXME: use preprocessor magic to set this on different platforms!
  85. */
  86. typedef byte flzuint8;
  87. typedef unsigned short flzuint16;
  88. typedef unsigned int flzuint32;
  89. /* prototypes */
  90. //int fastlz_compress(const void* input, int length, void* output);
  91. //int fastlz_compress_level(int level, const void* input, int length, void* output);
  92. //int fastlz_decompress(const void* input, int length, void* output, int maxout);
  93. #define MAX_COPY 32
  94. #define MAX_LEN 264 /* 256 + 8 */
  95. #define MAX_DISTANCE 8192
  96. #if !defined(FASTLZ_STRICT_ALIGN)
  97. #define FASTLZ_READU16(p) *((const flzuint16*)(p))
  98. #else
  99. #define FASTLZ_READU16(p) ((p)[0] | (p)[1]<<8)
  100. #endif
  101. #define HASH_LOG 13
  102. #define HASH_SIZE (1<< HASH_LOG)
  103. #define HASH_MASK (HASH_SIZE-1)
  104. #define HASH_FUNCTION(v,p) { v = FASTLZ_READU16(p); v ^= FASTLZ_READU16(p+1)^(v>>(16-HASH_LOG));v &= HASH_MASK; }
  105. typedef const flzuint8* HTAB_T[HASH_SIZE];
  106. #undef FASTLZ_LEVEL
  107. #define FASTLZ_LEVEL 1
  108. #undef FASTLZ_COMPRESSOR
  109. #undef FASTLZ_DECOMPRESSOR
  110. #define FASTLZ_COMPRESSOR fastlz1_compress
  111. #define FASTLZ_DECOMPRESSOR fastlz1_decompress
  112. static FASTLZ_INLINE int FASTLZ_COMPRESSOR(const void* input, int length, void* output, HTAB_T &htab);
  113. static FASTLZ_INLINE int FASTLZ_DECOMPRESSOR(const void* input, int length, void* output, int maxout);
  114. #include "jflz.cpp"
  115. #undef FASTLZ_LEVEL
  116. #define FASTLZ_LEVEL 2
  117. #undef MAX_DISTANCE
  118. #define MAX_DISTANCE 8191
  119. #define MAX_FARDISTANCE (65535+MAX_DISTANCE-1)
  120. #undef FASTLZ_COMPRESSOR
  121. #undef FASTLZ_DECOMPRESSOR
  122. #define FASTLZ_COMPRESSOR fastlz2_compress
  123. #define FASTLZ_DECOMPRESSOR fastlz2_decompress
  124. static FASTLZ_INLINE int FASTLZ_COMPRESSOR(const void* input, int length, void* output);
  125. static FASTLZ_INLINE int FASTLZ_DECOMPRESSOR(const void* input, int length, void* output, int maxout);
  126. #include "jflz.cpp"
  127. #define FASTLZ__JLIBCOMPRESSOR 1
  128. inline size32_t fastlz_compress(const void* input, size32_t length, void* output, HTAB_T &htab)
  129. {
  130. /* for short block, choose fastlz1 */
  131. if(length < 65536)
  132. return fastlz1_compress(input, length, output, htab);
  133. /* else... */
  134. return fastlz2_compress(input, length, output, htab);
  135. }
  136. size32_t fastlz_compress(const void* input, size32_t length, void* output)
  137. {
  138. MemoryAttr ma;
  139. HTAB_T *ht = (HTAB_T *)ma.allocate(sizeof(HTAB_T)); // HTAB_T too big for stack really
  140. return fastlz_compress(input,length,output,*ht);
  141. }
  142. size32_t fastlz_decompress(const void* input, size32_t length, void* output, size32_t maxout)
  143. {
  144. /* magic identifier for compression level */
  145. int level = ((*(const flzuint8*)input) >> 5) + 1;
  146. if(level == 1)
  147. return fastlz1_decompress(input, length, output, maxout);
  148. if(level == 2)
  149. return fastlz2_decompress(input, length, output, maxout);
  150. /* unknown level, trigger error */
  151. return 0;
  152. }
  153. int fastlz_compress_level(int level, const void* input, size32_t length, void* output)
  154. {
  155. MemoryAttr ma;
  156. HTAB_T *ht = (HTAB_T *)ma.allocate(sizeof(HTAB_T)); // HTAB_T too big for stack really
  157. if(level == 1)
  158. return fastlz1_compress(input, length, output, *ht);
  159. if(level == 2)
  160. return fastlz2_compress(input, length, output, *ht);
  161. return 0;
  162. }
  163. #else /* !defined(FASTLZ_COMPRESSOR) && !defined(FASTLZ_DECOMPRESSOR) */
  164. static FASTLZ_INLINE int FASTLZ_COMPRESSOR(const void* input, int length, void* output, HTAB_T &htab)
  165. {
  166. const flzuint8* ip = (const flzuint8*) input;
  167. const flzuint8* ip_bound = ip + length - 2;
  168. const flzuint8* ip_limit = ip + length - 12;
  169. flzuint8* op = (flzuint8*) output;
  170. const flzuint8** hslot;
  171. flzuint32 hval;
  172. flzuint32 copy;
  173. /* sanity check */
  174. if(FASTLZ_UNEXPECT_CONDITIONAL(length < 4))
  175. {
  176. if(length)
  177. {
  178. /* create literal copy only */
  179. *op++ = length-1;
  180. ip_bound++;
  181. while(ip <= ip_bound)
  182. *op++ = *ip++;
  183. return length+1;
  184. }
  185. else
  186. return 0;
  187. }
  188. /* initializes hash table */
  189. for (hslot = htab; hslot < htab + HASH_SIZE; hslot++)
  190. *hslot = ip;
  191. /* we start with literal copy */
  192. copy = 2;
  193. *op++ = MAX_COPY-1;
  194. *op++ = *ip++;
  195. *op++ = *ip++;
  196. /* main loop */
  197. while(FASTLZ_EXPECT_CONDITIONAL(ip < ip_limit))
  198. {
  199. const flzuint8* ref;
  200. flzuint32 distance;
  201. /* minimum match length */
  202. flzuint32 len = 3;
  203. /* comparison starting-point */
  204. const flzuint8* anchor = ip;
  205. /* check for a run */
  206. #if FASTLZ_LEVEL==2
  207. if(ip[0] == ip[-1] && FASTLZ_READU16(ip-1)==FASTLZ_READU16(ip+1))
  208. {
  209. distance = 1;
  210. ip += 3;
  211. ref = anchor - 1 + 3;
  212. goto match;
  213. }
  214. #endif
  215. /* find potential match */
  216. HASH_FUNCTION(hval,ip);
  217. hslot = htab + hval;
  218. ref = htab[hval];
  219. /* calculate distance to the match */
  220. distance = anchor - ref;
  221. /* update hash table */
  222. *hslot = anchor;
  223. /* is this a match? check the first 3 bytes */
  224. if(distance==0 ||
  225. #if FASTLZ_LEVEL==1
  226. (distance >= MAX_DISTANCE) ||
  227. #else
  228. (distance >= MAX_FARDISTANCE) ||
  229. #endif
  230. *ref++ != *ip++ || *ref++!=*ip++ || *ref++!=*ip++)
  231. goto literal;
  232. #if FASTLZ_LEVEL==2
  233. /* far, needs at least 5-byte match */
  234. if(distance >= MAX_DISTANCE)
  235. {
  236. if(*ip++ != *ref++ || *ip++!= *ref++)
  237. goto literal;
  238. len += 2;
  239. }
  240. match:
  241. #endif
  242. /* last matched byte */
  243. ip = anchor + len;
  244. /* distance is biased */
  245. distance--;
  246. if(!distance)
  247. {
  248. /* zero distance means a run */
  249. flzuint8 x = ip[-1];
  250. while(ip < ip_bound)
  251. if(*ref++ != x) break; else ip++;
  252. }
  253. else
  254. for(;;)
  255. {
  256. /* safe because the outer check against ip limit */
  257. if(*ref++ != *ip++) break;
  258. if(*ref++ != *ip++) break;
  259. if(*ref++ != *ip++) break;
  260. if(*ref++ != *ip++) break;
  261. if(*ref++ != *ip++) break;
  262. if(*ref++ != *ip++) break;
  263. if(*ref++ != *ip++) break;
  264. if(*ref++ != *ip++) break;
  265. while(ip < ip_bound)
  266. if(*ref++ != *ip++) break;
  267. break;
  268. }
  269. /* if we have copied something, adjust the copy count */
  270. if(copy)
  271. /* copy is biased, '0' means 1 byte copy */
  272. *(op-copy-1) = copy-1;
  273. else
  274. /* back, to overwrite the copy count */
  275. op--;
  276. /* reset literal counter */
  277. copy = 0;
  278. /* length is biased, '1' means a match of 3 bytes */
  279. ip -= 3;
  280. len = ip - anchor;
  281. /* encode the match */
  282. #if FASTLZ_LEVEL==2
  283. if(distance < MAX_DISTANCE)
  284. {
  285. if(len < 7)
  286. {
  287. *op++ = (len << 5) + (distance >> 8);
  288. *op++ = (distance & 255);
  289. }
  290. else
  291. {
  292. *op++ = (7 << 5) + (distance >> 8);
  293. for(len-=7; len >= 255; len-= 255)
  294. *op++ = 255;
  295. *op++ = len;
  296. *op++ = (distance & 255);
  297. }
  298. }
  299. else
  300. {
  301. /* far away, but not yet in the another galaxy... */
  302. if(len < 7)
  303. {
  304. distance -= MAX_DISTANCE;
  305. *op++ = (len << 5) + 31;
  306. *op++ = 255;
  307. *op++ = distance >> 8;
  308. *op++ = distance & 255;
  309. }
  310. else
  311. {
  312. distance -= MAX_DISTANCE;
  313. *op++ = (7 << 5) + 31;
  314. for(len-=7; len >= 255; len-= 255)
  315. *op++ = 255;
  316. *op++ = len;
  317. *op++ = 255;
  318. *op++ = distance >> 8;
  319. *op++ = distance & 255;
  320. }
  321. }
  322. #else
  323. if(FASTLZ_UNEXPECT_CONDITIONAL(len > MAX_LEN-2))
  324. while(len > MAX_LEN-2)
  325. {
  326. *op++ = (7 << 5) + (distance >> 8);
  327. *op++ = MAX_LEN - 2 - 7 -2;
  328. *op++ = (distance & 255);
  329. len -= MAX_LEN-2;
  330. }
  331. if(len < 7)
  332. {
  333. *op++ = (len << 5) + (distance >> 8);
  334. *op++ = (distance & 255);
  335. }
  336. else
  337. {
  338. *op++ = (7 << 5) + (distance >> 8);
  339. *op++ = len - 7;
  340. *op++ = (distance & 255);
  341. }
  342. #endif
  343. /* update the hash at match boundary */
  344. HASH_FUNCTION(hval,ip);
  345. htab[hval] = ip++;
  346. HASH_FUNCTION(hval,ip);
  347. htab[hval] = ip++;
  348. /* assuming literal copy */
  349. *op++ = MAX_COPY-1;
  350. continue;
  351. literal:
  352. *op++ = *anchor++;
  353. ip = anchor;
  354. copy++;
  355. if(FASTLZ_UNEXPECT_CONDITIONAL(copy == MAX_COPY))
  356. {
  357. copy = 0;
  358. *op++ = MAX_COPY-1;
  359. }
  360. }
  361. /* left-over as literal copy */
  362. ip_bound++;
  363. while(ip <= ip_bound)
  364. {
  365. *op++ = *ip++;
  366. copy++;
  367. if(copy == MAX_COPY)
  368. {
  369. copy = 0;
  370. *op++ = MAX_COPY-1;
  371. }
  372. }
  373. /* if we have copied something, adjust the copy length */
  374. if(copy)
  375. *(op-copy-1) = copy-1;
  376. else
  377. op--;
  378. #if FASTLZ_LEVEL==2
  379. /* marker for fastlz2 */
  380. *(flzuint8*)output |= (1 << 5);
  381. #endif
  382. return op - (flzuint8*)output;
  383. }
  384. static FASTLZ_INLINE int FASTLZ_DECOMPRESSOR(const void* input, int length, void* output, int maxout)
  385. {
  386. const flzuint8* ip = (const flzuint8*) input;
  387. const flzuint8* ip_limit = ip + length;
  388. flzuint8* op = (flzuint8*) output;
  389. flzuint8* op_limit = op + maxout;
  390. flzuint32 ctrl = (*ip++) & 31;
  391. int loopidx = 1;
  392. do
  393. {
  394. const flzuint8* ref = op;
  395. flzuint32 len = ctrl >> 5;
  396. flzuint32 ofs = (ctrl & 31) << 8;
  397. if(ctrl >= 32)
  398. {
  399. #if FASTLZ_LEVEL==2
  400. flzuint8 code;
  401. #endif
  402. len--;
  403. ref -= ofs;
  404. if (len == 7-1)
  405. #if FASTLZ_LEVEL==1
  406. len += *ip++;
  407. ref -= *ip++;
  408. #else
  409. do
  410. {
  411. code = *ip++;
  412. len += code;
  413. } while (code==255);
  414. code = *ip++;
  415. ref -= code;
  416. /* match from 16-bit distance */
  417. if(FASTLZ_UNEXPECT_CONDITIONAL(code==255))
  418. if(FASTLZ_EXPECT_CONDITIONAL(ofs==(31 << 8)))
  419. {
  420. ofs = (*ip++) << 8;
  421. ofs += *ip++;
  422. ref = op - ofs - MAX_DISTANCE;
  423. }
  424. #endif
  425. #ifdef FASTLZ_SAFE
  426. if (FASTLZ_UNEXPECT_CONDITIONAL(op + len + 3 > op_limit))
  427. return 0;
  428. if (FASTLZ_UNEXPECT_CONDITIONAL(ref-1 < (flzuint8 *)output))
  429. return 0;
  430. #endif
  431. if(FASTLZ_EXPECT_CONDITIONAL(ip < ip_limit))
  432. ctrl = *ip++;
  433. else
  434. loopidx = 0;
  435. if(ref == op)
  436. {
  437. /* optimize copy for a run */
  438. flzuint8 b = ref[-1];
  439. *op++ = b;
  440. *op++ = b;
  441. *op++ = b;
  442. for(; len; --len)
  443. *op++ = b;
  444. }
  445. else
  446. {
  447. #if !defined(FASTLZ_STRICT_ALIGN)
  448. const flzuint16* p;
  449. flzuint16* q;
  450. #endif
  451. /* copy from reference */
  452. ref--;
  453. *op++ = *ref++;
  454. *op++ = *ref++;
  455. *op++ = *ref++;
  456. #if !defined(FASTLZ_STRICT_ALIGN)
  457. /* copy a byte, so that now it's word aligned */
  458. if(len & 1)
  459. {
  460. *op++ = *ref++;
  461. len--;
  462. }
  463. /* copy 16-bit at once */
  464. q = (flzuint16*) op;
  465. op += len;
  466. p = (const flzuint16*) ref;
  467. for(len>>=1; len > 4; len-=4)
  468. {
  469. *q++ = *p++;
  470. *q++ = *p++;
  471. *q++ = *p++;
  472. *q++ = *p++;
  473. }
  474. for(; len; --len)
  475. *q++ = *p++;
  476. #else
  477. for(; len; --len)
  478. *op++ = *ref++;
  479. #endif
  480. }
  481. }
  482. else
  483. {
  484. ctrl++;
  485. #ifdef FASTLZ_SAFE
  486. if (FASTLZ_UNEXPECT_CONDITIONAL(op + ctrl > op_limit))
  487. return 0;
  488. if (FASTLZ_UNEXPECT_CONDITIONAL(ip + ctrl > ip_limit))
  489. return 0;
  490. #endif
  491. *op++ = *ip++;
  492. for(--ctrl; ctrl; ctrl--)
  493. *op++ = *ip++;
  494. loopidx = FASTLZ_EXPECT_CONDITIONAL(ip < ip_limit);
  495. if(loopidx)
  496. ctrl = *ip++;
  497. }
  498. }
  499. while(FASTLZ_EXPECT_CONDITIONAL(loopidx));
  500. return op - (flzuint8*)output;
  501. }
  502. #undef FASTLZ__JLIBCOMPRESSOR // avoid being compiled twice!!
  503. #endif /* !defined(FASTLZ_COMPRESSOR) && !defined(FASTLZ_DECOMPRESSOR) */
  504. #if defined(FASTLZ__JLIBCOMPRESSOR)
  505. #define COMMITTED ((size32_t)-1)
  506. /* Format:
  507. size32_t totalexpsize;
  508. { size32_t subcmpsize; bytes subcmpdata; }
  509. size32_t trailsize; bytes traildata; // unexpanded
  510. */
  511. class jlib_decl CFastLZCompressor : public CInterface, public ICompressor
  512. {
  513. HTAB_T ht;
  514. size32_t blksz;
  515. size32_t bufalloc;
  516. MemoryBuffer inma; // equals blksize len
  517. MemoryBuffer *outBufMb; // used when dynamic output buffer (when open() used)
  518. size32_t outBufStart;
  519. byte *inbuf;
  520. size32_t inmax; // remaining
  521. size32_t inlen;
  522. size32_t inlenblk; // set to COMMITTED when so
  523. bool trailing;
  524. byte *outbuf;
  525. size32_t outlen;
  526. size32_t wrmax;
  527. size32_t dynamicOutSz;
  528. inline void setinmax()
  529. {
  530. inmax = blksz-outlen-sizeof(size32_t);
  531. if (inmax<256)
  532. trailing = true; // too small to bother compressing
  533. else {
  534. trailing = false;
  535. size32_t slack = inmax/17;
  536. if (slack<66)
  537. slack = 66;
  538. inmax -= slack+sizeof(size32_t);
  539. }
  540. }
  541. inline void flushcommitted()
  542. {
  543. // only does non trailing
  544. if (trailing)
  545. return;
  546. size32_t toflush = (inlenblk==COMMITTED)?inlen:inlenblk;
  547. if (toflush == 0)
  548. return;
  549. size32_t outSzRequired = outlen+sizeof(size32_t)*2+toflush+fastlzSlack(toflush);
  550. if (!dynamicOutSz)
  551. assertex(outSzRequired<=blksz);
  552. else
  553. {
  554. if (outSzRequired>dynamicOutSz)
  555. {
  556. verifyex(outBufMb->ensureCapacity(outBufStart+outSzRequired));
  557. dynamicOutSz = outBufMb->capacity();
  558. outbuf = ((byte *)outBufMb->bufferBase()+outBufStart);
  559. }
  560. }
  561. size32_t *cmpsize = (size32_t *)(outbuf+outlen);
  562. byte *out = (byte *)(cmpsize+1);
  563. *cmpsize = (size32_t)fastlz_compress(inbuf, (int)toflush, out, ht);
  564. if (*cmpsize<toflush)
  565. {
  566. *(size32_t *)outbuf += toflush;
  567. outlen += *cmpsize+sizeof(size32_t);
  568. if (inlenblk==COMMITTED)
  569. inlen = 0;
  570. else
  571. {
  572. inlen -= inlenblk;
  573. memmove(inbuf,inbuf+toflush,inlen);
  574. }
  575. setinmax();
  576. return;
  577. }
  578. trailing = true;
  579. }
  580. void initCommon()
  581. {
  582. blksz = inma.capacity();
  583. *(size32_t *)outbuf = 0;
  584. outlen = sizeof(size32_t);
  585. inlen = 0;
  586. inlenblk = COMMITTED;
  587. setinmax();
  588. }
  589. public:
  590. IMPLEMENT_IINTERFACE;
  591. CFastLZCompressor()
  592. {
  593. outlen = 0;
  594. outbuf = NULL; // only set on close
  595. bufalloc = 0;
  596. wrmax = 0; // set at open
  597. dynamicOutSz = 0;
  598. outBufMb = NULL;
  599. outBufStart = 0;
  600. inbuf = NULL;
  601. }
  602. virtual ~CFastLZCompressor()
  603. {
  604. if (bufalloc)
  605. free(outbuf);
  606. }
  607. virtual void open(void *buf,size32_t max)
  608. {
  609. if (max<1024)
  610. throw MakeStringException(-1,"CFastLZCompressor::open - block size (%d) not large enough", blksz);
  611. wrmax = max;
  612. if (buf)
  613. {
  614. if (bufalloc)
  615. free(outbuf);
  616. bufalloc = 0;
  617. outbuf = (byte *)buf;
  618. }
  619. else if (max>bufalloc)
  620. {
  621. if (bufalloc)
  622. free(outbuf);
  623. bufalloc = max;
  624. outbuf = (byte *)malloc(bufalloc);
  625. }
  626. outBufMb = NULL;
  627. outBufStart = 0;
  628. dynamicOutSz = 0;
  629. inbuf = (byte *)inma.ensureCapacity(max);
  630. initCommon();
  631. }
  632. virtual void open(MemoryBuffer &mb, size32_t initialSize)
  633. {
  634. if (!initialSize)
  635. initialSize = 0x100000; // 1MB
  636. if (initialSize<1024)
  637. throw MakeStringException(-1,"CFastLZCompressor::open - block size (%d) not large enough", initialSize);
  638. wrmax = initialSize;
  639. if (bufalloc)
  640. {
  641. free(outbuf);
  642. bufalloc = 0;
  643. }
  644. inbuf = (byte *)inma.ensureCapacity(initialSize);
  645. outBufMb = &mb;
  646. outBufStart = mb.length();
  647. outbuf = (byte *)outBufMb->ensureCapacity(initialSize);
  648. dynamicOutSz = outBufMb->capacity();
  649. initCommon();
  650. }
  651. virtual void close()
  652. {
  653. if (inlenblk!=COMMITTED) {
  654. inlen = inlenblk; // transaction failed
  655. inlenblk = COMMITTED;
  656. }
  657. flushcommitted();
  658. size32_t totlen = outlen+sizeof(size32_t)+inlen;
  659. assertex(blksz>=totlen);
  660. size32_t *tsize = (size32_t *)(outbuf+outlen);
  661. *tsize = inlen;
  662. memcpy(tsize+1,inbuf,inlen);
  663. outlen = totlen;
  664. *(size32_t *)outbuf += inlen;
  665. inbuf = NULL;
  666. if (outBufMb)
  667. {
  668. outBufMb->setWritePos(outBufStart+outlen);
  669. outBufMb = NULL;
  670. }
  671. }
  672. size32_t write(const void *buf,size32_t len)
  673. {
  674. // no more than wrmax per write (unless dynamically sizing)
  675. size32_t lenb = wrmax;
  676. byte *b = (byte *)buf;
  677. size32_t written = 0;
  678. while (len)
  679. {
  680. if (len < lenb)
  681. lenb = len;
  682. if (lenb+inlen>inmax)
  683. {
  684. if (trailing)
  685. return written;
  686. flushcommitted();
  687. if (lenb+inlen>inmax)
  688. {
  689. if (outBufMb) // sizing input buffer, but outBufMb!=NULL is condition of whether in use or not
  690. {
  691. blksz += len > 0x100000 ? len : 0x100000;
  692. verifyex(inma.ensureCapacity(blksz));
  693. blksz = inma.capacity();
  694. inbuf = (byte *)inma.bufferBase();
  695. wrmax = blksz;
  696. setinmax();
  697. }
  698. lenb = inmax-inlen;
  699. if (len < lenb)
  700. lenb = len;
  701. }
  702. }
  703. if (lenb == 0)
  704. return written;
  705. memcpy(inbuf+inlen,b,lenb);
  706. b += lenb;
  707. inlen += lenb;
  708. len -= lenb;
  709. written += lenb;
  710. }
  711. return written;
  712. }
  713. void * bufptr()
  714. {
  715. assertex(!inbuf); // i.e. closed
  716. return outbuf;
  717. }
  718. size32_t buflen()
  719. {
  720. assertex(!inbuf); // i.e. closed
  721. return outlen;
  722. }
  723. void startblock()
  724. {
  725. inlenblk = inlen;
  726. }
  727. void commitblock()
  728. {
  729. inlenblk = COMMITTED;
  730. }
  731. };
  732. class jlib_decl CFastLZExpander : public CInterface, public IExpander
  733. {
  734. byte *outbuf;
  735. size32_t outlen;
  736. size32_t bufalloc;
  737. const size32_t *in;
  738. public:
  739. IMPLEMENT_IINTERFACE;
  740. CFastLZExpander()
  741. {
  742. outbuf = NULL;
  743. outlen = 0;
  744. bufalloc = 0;
  745. }
  746. ~CFastLZExpander()
  747. {
  748. if (bufalloc)
  749. free(outbuf);
  750. }
  751. virtual size32_t init(const void *blk)
  752. {
  753. const size32_t *expsz = (const size32_t *)blk;
  754. outlen = *expsz;
  755. in = (expsz+1);
  756. return outlen;
  757. }
  758. virtual void expand(void *buf)
  759. {
  760. if (!outlen)
  761. return;
  762. if (buf) {
  763. if (bufalloc)
  764. free(outbuf);
  765. bufalloc = 0;
  766. outbuf = (unsigned char *)buf;
  767. }
  768. else if (outlen>bufalloc) {
  769. if (bufalloc)
  770. free(outbuf);
  771. bufalloc = outlen;
  772. outbuf = (unsigned char *)malloc(bufalloc);
  773. if (!outbuf)
  774. throw MakeStringException(MSGAUD_operator,0, "Out of memory in FastLZExpander::expand, requesting %d bytes", bufalloc);
  775. }
  776. size32_t done = 0;
  777. loop {
  778. const size32_t szchunk = *in;
  779. in++;
  780. if (szchunk+done<outlen) {
  781. size32_t written = fastlz_decompress(in,szchunk,(byte *)buf+done,outlen-done);
  782. done += written;
  783. if (!written||(done>outlen))
  784. throw MakeStringException(0, "FastLZExpander - corrupt data(1) %d %d",written,szchunk);
  785. }
  786. else {
  787. if (szchunk+done!=outlen)
  788. throw MakeStringException(0, "FastLZExpander - corrupt data(2) %d %d",szchunk,outlen);
  789. memcpy((byte *)buf+done,in,szchunk);
  790. break;
  791. }
  792. in = (const size32_t *)(((const byte *)in)+szchunk);
  793. }
  794. }
  795. virtual void *bufptr() { return outbuf;}
  796. virtual size32_t buflen() { return outlen;}
  797. };
  798. void fastLZCompressToBuffer(MemoryBuffer & out, size32_t len, const void * src)
  799. {
  800. size32_t outbase = out.length();
  801. size32_t *sz = (size32_t *)out.reserve(len+fastlzSlack(len)+sizeof(size32_t)*2);
  802. *sz = len;
  803. sz++;
  804. *sz = (len>16)?fastlz_compress(src, (int)len, sz+1):16;
  805. if (*sz>=len) {
  806. *sz = len;
  807. memcpy(sz+1,src,len);
  808. }
  809. out.setLength(outbase+*sz+sizeof(size32_t)*2);
  810. }
  811. void fastLZDecompressToBuffer(MemoryBuffer & out, const void * src)
  812. {
  813. size32_t *sz = (size32_t *)src;
  814. size32_t expsz = *(sz++);
  815. size32_t cmpsz = *(sz++);
  816. void *o = out.reserve(expsz);
  817. if (cmpsz!=expsz) {
  818. size32_t written = fastlz_decompress(sz,cmpsz,o,expsz);
  819. if (written!=expsz)
  820. throw MakeStringException(0, "fastLZDecompressToBuffer - corrupt data(1) %d %d",written,expsz);
  821. }
  822. else
  823. memcpy(o,sz,expsz);
  824. }
  825. void fastLZDecompressToBuffer(MemoryBuffer & out, MemoryBuffer & in)
  826. {
  827. size32_t expsz;
  828. size32_t cmpsz;
  829. in.read(expsz).read(cmpsz);
  830. void *o = out.reserve(expsz);
  831. if (cmpsz!=expsz) {
  832. size32_t written = fastlz_decompress(in.readDirect(cmpsz),cmpsz,o,expsz);
  833. if (written!=expsz)
  834. throw MakeStringException(0, "fastLZDecompressToBuffer - corrupt data(3) %d %d",written,expsz);
  835. }
  836. else
  837. memcpy(o,in.readDirect(cmpsz),expsz);
  838. }
  839. void fastLZDecompressToAttr(MemoryAttr & out, const void * src)
  840. {
  841. size32_t *sz = (size32_t *)src;
  842. size32_t expsz = *(sz++);
  843. size32_t cmpsz = *(sz++);
  844. void *o = out.allocate(expsz);
  845. if (cmpsz!=expsz) {
  846. size32_t written = fastlz_decompress(sz,cmpsz,o,expsz);
  847. if (written!=expsz)
  848. throw MakeStringException(0, "fastLZDecompressToBuffer - corrupt data(2) %d %d",written,expsz);
  849. }
  850. else
  851. memcpy(o,sz,expsz);
  852. }
  853. void fastLZDecompressToBuffer(MemoryAttr & out, MemoryBuffer & in)
  854. {
  855. size32_t expsz;
  856. size32_t cmpsz;
  857. in.read(expsz).read(cmpsz);
  858. void *o = out.allocate(expsz);
  859. if (cmpsz!=expsz) {
  860. size32_t written = fastlz_decompress(in.readDirect(cmpsz),cmpsz,o,expsz);
  861. if (written!=expsz)
  862. throw MakeStringException(0, "fastLZDecompressToBuffer - corrupt data(4) %d %d",written,expsz);
  863. }
  864. else
  865. memcpy(o,in.readDirect(cmpsz),expsz);
  866. }
  867. ICompressor *createFastLZCompressor()
  868. {
  869. return new CFastLZCompressor;
  870. }
  871. IExpander *createFastLZExpander()
  872. {
  873. return new CFastLZExpander;
  874. }
  875. #define FLZ_BUFFER_SIZE (0x100000)
  876. #define FLZCOMPRESSEDFILEFLAG (I64C(0xc3518de42f15da57))
  877. struct FlzCompressedFileTrailer
  878. {
  879. offset_t zfill1; // must be first
  880. offset_t expandedSize;
  881. __int64 compressedType;
  882. unsigned zfill2; // must be last
  883. };
  884. class CFastLZStream : public CInterface, implements IFileIOStream
  885. {
  886. Linked<IFileIO> baseio;
  887. offset_t expOffset; // expanded offset
  888. offset_t cmpOffset; // compressed offset in file
  889. bool reading;
  890. MemoryAttr ma;
  891. size32_t bufsize;
  892. size32_t bufpos; // reading only
  893. offset_t expSize;
  894. bool load()
  895. {
  896. bufpos = 0;
  897. bufsize = 0;
  898. if (expOffset==expSize)
  899. return false;
  900. size32_t sz[2];
  901. if (baseio->read(cmpOffset,sizeof(size32_t)*2,&sz)!=sizeof(size32_t)*2)
  902. return false;
  903. bufsize = sz[0];
  904. if (!bufsize)
  905. return false;
  906. cmpOffset += sizeof(size32_t)*2;
  907. if (ma.length()<bufsize)
  908. ma.allocate(bufsize);
  909. MemoryAttr cmpma;
  910. byte *cmpbuf = (byte *)cmpma.allocate(sz[1]);
  911. if (baseio->read(cmpOffset,sz[1],cmpbuf)!=sz[1])
  912. throw MakeStringException(-1,"CFastLZStream: file corrupt.1");
  913. if (fastlz_decompress(cmpbuf,sz[1],ma.bufferBase(),bufsize)!=bufsize)
  914. throw MakeStringException(-1,"CFastLZStream: file corrupt.2");
  915. cmpOffset += sz[1];
  916. return true;
  917. }
  918. void save()
  919. {
  920. if (bufsize) {
  921. MemoryAttr dstma;
  922. byte *dst = (byte *)dstma.allocate(sizeof(size32_t)*2+bufsize+fastlzSlack(bufsize));
  923. size32_t sz = fastlz_compress(ma.get(),bufsize,sizeof(size32_t)*2+dst);
  924. memcpy(dst,&bufsize,sizeof(size32_t));
  925. memcpy(dst+sizeof(size32_t),&sz,sizeof(size32_t));
  926. baseio->write(cmpOffset,sz+sizeof(size32_t)*2,dst);
  927. cmpOffset += sz+sizeof(size32_t)*2;
  928. }
  929. bufsize = 0;
  930. }
  931. public:
  932. IMPLEMENT_IINTERFACE;
  933. CFastLZStream()
  934. {
  935. expOffset = 0;
  936. cmpOffset = 0;
  937. reading = true;
  938. bufpos = 0;
  939. bufsize = 0;
  940. }
  941. ~CFastLZStream()
  942. {
  943. flush();
  944. }
  945. bool attach(IFileIO *_baseio)
  946. {
  947. baseio.set(_baseio);
  948. expOffset = 0;
  949. cmpOffset = 0;
  950. reading = true;
  951. bufpos = 0;
  952. bufsize = 0;
  953. FlzCompressedFileTrailer trailer;
  954. offset_t filesize = baseio->size();
  955. if (filesize<sizeof(trailer))
  956. return false;
  957. baseio->read(filesize-sizeof(trailer),sizeof(trailer),&trailer);
  958. expSize = trailer.expandedSize;
  959. return trailer.compressedType==FLZCOMPRESSEDFILEFLAG;
  960. }
  961. void create(IFileIO *_baseio)
  962. {
  963. baseio.set(_baseio);
  964. expOffset = 0;
  965. cmpOffset = 0;
  966. reading = false;
  967. bufpos = 0;
  968. bufsize = 0;
  969. ma.allocate(FLZ_BUFFER_SIZE);
  970. expSize = (offset_t)-1;
  971. }
  972. void seek(offset_t pos, IFSmode origin)
  973. {
  974. if ((origin==IFScurrent)&&(pos==0))
  975. return;
  976. if ((origin==IFSbegin)||(pos!=0))
  977. throw MakeStringException(-1,"CFastLZStream seek not supported");
  978. expOffset = 0;
  979. bufpos = 0;
  980. bufsize = 0;
  981. }
  982. offset_t size()
  983. {
  984. return (expSize==(offset_t)-1)?0:expSize;
  985. }
  986. offset_t tell()
  987. {
  988. return expOffset;
  989. }
  990. size32_t read(size32_t len, void * data)
  991. {
  992. if (!reading)
  993. throw MakeStringException(-1,"CFastLZStream read to stream being written");
  994. size32_t ret=0;
  995. while (len) {
  996. size32_t cpy = bufsize-bufpos;
  997. if (!cpy) {
  998. if (!load())
  999. break;
  1000. cpy = bufsize-bufpos;
  1001. }
  1002. if (cpy>len)
  1003. cpy = len;
  1004. memcpy(data,(const byte *)ma.get()+bufpos,cpy);
  1005. bufpos += cpy;
  1006. len -= cpy;
  1007. ret += cpy;
  1008. }
  1009. expOffset += ret;
  1010. return ret;
  1011. }
  1012. size32_t write(size32_t len, const void * data)
  1013. {
  1014. if (reading)
  1015. throw MakeStringException(-1,"CFastLZStream write to stream being read");
  1016. size32_t ret = len;
  1017. while (len+bufsize>FLZ_BUFFER_SIZE) {
  1018. size32_t cpy = FLZ_BUFFER_SIZE-bufsize;
  1019. memcpy((byte *)ma.bufferBase()+bufsize,data,cpy);
  1020. data = (const byte *)data+cpy;
  1021. len -= cpy;
  1022. bufsize = FLZ_BUFFER_SIZE;
  1023. save();
  1024. }
  1025. memcpy((byte *)ma.bufferBase()+bufsize,data,len);
  1026. bufsize += len;
  1027. expOffset += len;
  1028. return ret;
  1029. }
  1030. void flush()
  1031. {
  1032. if (!reading&&(expSize!=expOffset)) {
  1033. save();
  1034. FlzCompressedFileTrailer trailer;
  1035. memset(&trailer,0,sizeof(trailer));
  1036. trailer.compressedType = FLZCOMPRESSEDFILEFLAG;
  1037. trailer.expandedSize = expOffset;
  1038. baseio->write(cmpOffset,sizeof(trailer),&trailer);
  1039. expSize = expOffset;
  1040. }
  1041. }
  1042. };
  1043. IFileIOStream *createFastLZStreamRead(IFileIO *base)
  1044. {
  1045. Owned<CFastLZStream> strm = new CFastLZStream();
  1046. if (strm->attach(base))
  1047. return strm.getClear();
  1048. return NULL;
  1049. }
  1050. IFileIOStream *createFastLZStreamWrite(IFileIO *base)
  1051. {
  1052. Owned<CFastLZStream> strm = new CFastLZStream();
  1053. strm->create(base);
  1054. return strm.getClear();
  1055. }
  1056. #endif