2
0

Compress.hx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (C)2005-2012 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package cpp.zip;
  23. class Compress {
  24. var s : Dynamic;
  25. public function new( level : Int ) {
  26. s = _deflate_init(level);
  27. }
  28. public function execute( src : haxe.io.Bytes, srcPos : Int, dst : haxe.io.Bytes, dstPos : Int ) : { done : Bool, read : Int, write : Int } {
  29. return _deflate_buffer(s,src.getData(),srcPos,dst.getData(),dstPos);
  30. }
  31. public function setFlushMode( f : Flush ) {
  32. _set_flush_mode(s,Std.string(f));
  33. }
  34. public function close() {
  35. _deflate_end(s);
  36. }
  37. public static function run( s : haxe.io.Bytes, level : Int ) : haxe.io.Bytes {
  38. var c = new Compress(level);
  39. c.setFlushMode(Flush.FINISH);
  40. var out = haxe.io.Bytes.alloc(_deflate_bound(c.s,s.length));
  41. var r = c.execute(s,0,out,0);
  42. c.close();
  43. if( !r.done || r.read != s.length )
  44. throw "Compression failed";
  45. return out.sub(0,r.write);
  46. }
  47. static var _deflate_init = cpp.Lib.load("zlib","deflate_init",1);
  48. static var _deflate_bound = cpp.Lib.load("zlib","deflate_bound",2);
  49. static var _deflate_buffer = cpp.Lib.load("zlib","deflate_buffer",5);
  50. static var _deflate_end = cpp.Lib.load("zlib","deflate_end",1);
  51. static var _set_flush_mode = cpp.Lib.load("zlib","set_flush_mode",2);
  52. }