FileReadStream.hx 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package asys.io;
  2. import haxe.io.*;
  3. import haxe.io.Readable.ReadResult;
  4. typedef FileReadStreamOptions = {
  5. ?autoClose:Bool,
  6. ?start:Int,
  7. ?end:Int,
  8. ?highWaterMark:Int
  9. };
  10. class FileReadStream extends Readable {
  11. final file:File;
  12. var position:Int;
  13. final end:Int;
  14. var readInProgress:Bool = false;
  15. public function new(file:File, ?options:FileReadStreamOptions) {
  16. super();
  17. if (options == null)
  18. options = {};
  19. this.file = file;
  20. position = options.start != null ? options.start : 0;
  21. end = options.end != null ? options.end : 0xFFFFFFFF;
  22. }
  23. override function internalRead(remaining):ReadResult {
  24. if (readInProgress)
  25. return None;
  26. readInProgress = true;
  27. // TODO: check errors
  28. var chunk = Bytes.alloc(remaining);
  29. // TODO: check EOF for file as well
  30. var willEnd = (position + remaining) >= end;
  31. file.async.readBuffer(chunk, 0, remaining, position, (err, _) -> {
  32. readInProgress = false;
  33. if (err != null)
  34. errorSignal.emit(err);
  35. asyncRead([chunk], willEnd);
  36. });
  37. position += remaining;
  38. return None;
  39. }
  40. }