NativeInput.hx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package python.io;
  2. import haxe.io.Eof;
  3. import haxe.io.Input;
  4. import python.lib.Builtin;
  5. import python.lib.io.RawIOBase;
  6. import python.lib.io.IOBase.SeekSet;
  7. class NativeInput extends Input{
  8. var stream:RawIOBase;
  9. public var canSeek(get_canSeek, null):Bool;
  10. public function new (stream:RawIOBase) {
  11. this.stream = stream;
  12. if (!stream.readable()) throw "Write-only stream";
  13. }
  14. private function get_canSeek():Bool
  15. {
  16. return stream.seekable();
  17. }
  18. override public function close():Void
  19. {
  20. stream.close();
  21. }
  22. public function tell() : Int
  23. {
  24. return stream.tell();
  25. }
  26. override public function readByte():Int
  27. {
  28. var ret = stream.read(1);
  29. if (ret.length == 0) throw new Eof();
  30. return ret.get(0);
  31. }
  32. public function seek( p : Int, pos : sys.io.FileSeek ) : Void
  33. {
  34. var pos = switch(pos)
  35. {
  36. case SeekBegin: SeekSet.SeekStart;
  37. case SeekCur: SeekSet.SeekCur;
  38. case SeekEnd: SeekSet.SeekEnd;
  39. };
  40. stream.seek(p, pos);
  41. }
  42. override public function readBytes(s:haxe.io.Bytes, pos:Int, len:Int):Int
  43. {
  44. if( pos < 0 || len < 0 || pos + len > s.length )
  45. throw haxe.io.Error.OutsideBounds;
  46. stream.seek(pos, python.lib.io.IOBase.SeekSet.SeekCur);
  47. var ba = Builtin.bytearray(len);
  48. var ret = stream.readinto(ba);
  49. s.blit(pos, haxe.io.Bytes.ofData(ba) ,0,len);
  50. if (ret == 0)
  51. throw new Eof();
  52. return ret;
  53. }
  54. /*
  55. public function eof() : Bool
  56. {
  57. return stream.Position == stream.Length;
  58. }
  59. */
  60. }