Last active
November 5, 2015 22:49
-
-
Save azenla/1852922857c997f32586 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library realdb.io; | |
import "dart:async"; | |
import "dart:io"; | |
import "dart:typed_data"; | |
abstract class ByteStream { | |
Future<int> read(); | |
Future<int> getPosition(); | |
Future skip(int count) async { | |
for (var i = 1; i <= count; i++) { | |
await read(); | |
} | |
} | |
Future close() async {} | |
} | |
class ByteDataStream extends ByteStream { | |
final ByteData data; | |
int _pos = -1; | |
ByteDataStream(this.data); | |
@override | |
Future<int> getPosition() async { | |
return _pos; | |
} | |
@override | |
Future<int> read() async { | |
_pos++; | |
return data.getUint8(_pos); | |
} | |
} | |
class FileByteStream extends ByteStream { | |
final RandomAccessFile file; | |
FileByteStream(this.file); | |
@override | |
Future<int> read() => file.readByte(); | |
@override | |
Future<int> getPosition() => file.position(); | |
@override | |
Future skip(int count) async => | |
file.setPosition((await file.position()) + count); | |
@override | |
Future close() async => await file.close(); | |
} | |
class ChunkedFileByteStream extends FileByteStream { | |
final int chunkSize; | |
int _pos = -1; | |
int _buffPos = -1; | |
Uint8List _buff; | |
ChunkedFileByteStream(this.chunkSize, RandomAccessFile file) : super(file) { | |
_buff = new Uint8List(chunkSize); | |
} | |
@override | |
Future<int> read() async { | |
_pos++; | |
if (_buffPos == -1 || _buffPos == chunkSize - 1) { | |
await file.readInto(_buff); | |
_buffPos = -1; | |
} | |
_buffPos++; | |
return _buff[_buffPos]; | |
} | |
@override | |
Future<int> getPosition() async { | |
return _pos; | |
} | |
@override | |
Future skip(int count) async { | |
await file.setPosition((await file.position()) + count); | |
_pos += count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment