Compress.hx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 haxe.zip;
  23. @:coreApi
  24. class Compress {
  25. var s : Dynamic;
  26. public function new( level : Int ) {
  27. s = _deflate_init(level);
  28. }
  29. public function execute( src : haxe.io.Bytes, srcPos : Int, dst : haxe.io.Bytes, dstPos : Int ) : { done : Bool, read : Int, write : Int } {
  30. return _deflate_buffer(s,src.getData(),srcPos,dst.getData(),dstPos);
  31. }
  32. public function setFlushMode( f : Flush ) {
  33. _set_flush_mode(s,Std.string(f));
  34. }
  35. public function close() {
  36. _deflate_end(s);
  37. }
  38. public static function run( s : haxe.io.Bytes, level : Int ) : haxe.io.Bytes {
  39. var c = new Compress(level);
  40. c.setFlushMode(Flush.FINISH);
  41. var out = haxe.io.Bytes.alloc(_deflate_bound(c.s,s.length));
  42. var r = c.execute(s,0,out,0);
  43. c.close();
  44. if( !r.done || r.read != s.length )
  45. throw "Compression failed";
  46. return out.sub(0,r.write);
  47. }
  48. static var _deflate_init = cpp.Lib.load("zlib","deflate_init",1);
  49. static var _deflate_bound = cpp.Lib.load("zlib","deflate_bound",2);
  50. static var _deflate_buffer = cpp.Lib.load("zlib","deflate_buffer",5);
  51. static var _deflate_end = cpp.Lib.load("zlib","deflate_end",1);
  52. static var _set_flush_mode = cpp.Lib.load("zlib","set_flush_mode",2);
  53. }