import 'dart:typed_data'; import '../utils/Converter.dart'; import 'Stream.dart'; import 'Tag.dart'; import 'impl/CompoundTag.dart'; class NbtIo { static ByteLayer _io = ByteLayer(); // Handle various helper functions here! static Future _read(String file) async { _io = ByteLayer(); await _io.readFromFile(file); } // This function will read the file and check if it is infact gzipped static Future read(String file) async { await _read(file); if (_io.readByte() == TagType.Compound.byte) { _io.resetPosition(); return Tag.readNamedTag(_io); } else { // Is likely gzip compressed return readCompressed(file); } } static Future readCompressed(String file) async { _io = ByteLayer(); await _io.readFromFile(file); await _io.decompress(); _io.resetPosition(); return Tag.readNamedTag(_io); } static Future write(String file, CompoundTag tag) async { _io = ByteLayer(); Tag.writeNamedTag(tag, _io); await _io.writeToFile(file); } static Future writeCompressed(String file, CompoundTag tag) async { _io = ByteLayer(); Tag.writeNamedTag(tag, _io); await _io.compress(); await _io.writeToFile(file); } static ByteLayer getStream() { return _io; } static Future writeBase64String(CompoundTag tag) async { _io = ByteLayer(); Tag.writeNamedTag(tag, _io); _io.compress(); return base64Encoder.encode(_io.bytes); } static Future readBase64String(String encoded) async { _io = ByteLayer(); List bytes = base64Encoder.decode(encoded); for (int byte in bytes) { _io.writeByte(byte); } _io.decompress(); _io.resetPosition(); return Tag.readNamedTag(_io); } /// Writes the NBT Data to stream in compressed mode static Future writeToStreamCompressed(CompoundTag tag) async { _io = ByteLayer(); Tag.writeNamedTag(tag, _io); _io.compress(); return _io.bytes; } static Future readFromStreamCompressed(Uint8List list) async { _io = ByteLayer(); try { _io.writeBytes(list); _io.resetPosition(); _io.decompress(); _io.resetPosition(); } catch (E) { print(E); } finally { return Tag.readNamedTag(_io); } } static Future writeToStream(CompoundTag tag) async { _io = ByteLayer(); Tag.writeNamedTag(tag, _io); return _io.bytes; } static Future readFromStream(Uint8List list) async { _io = ByteLayer(); try { _io.writeBytes(list); _io.resetPosition(); } catch (E) { print(E); } finally { if (_io.readByte() == TagType.Compound.byte) { _io.resetPosition(); return Tag.readNamedTag(_io); } else { _io.resetPosition(); _io.decompress(); _io.resetPosition(); return Tag.readNamedTag(_io); } } } }