Implement NbtIO and some unit tests using the HelloWorld NBT

This commit is contained in:
zontreck 2024-05-05 23:30:27 -07:00
parent 3a3c5f5822
commit c867982482
4 changed files with 67 additions and 0 deletions

View file

@ -0,0 +1 @@
class InvalidNbtDataException implements Exception {}

48
lib/nbt/NbtIo.dart Normal file
View file

@ -0,0 +1,48 @@
import 'package:libac_flutter/nbt/Stream.dart';
import 'package:libac_flutter/nbt/Tag.dart';
import 'package:libac_flutter/nbt/impl/CompoundTag.dart';
class NbtIo {
static ByteLayer _io = ByteLayer();
// Handle various helper functions here!
static Future<void> _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<CompoundTag> read(String file) async {
await _read(file);
if (_io.readByte() == TagType.Compound.byte) {
_io.resetPosition();
return Tag.readNamedTag(_io) as CompoundTag;
} else {
// Is likely gzip compressed
return readCompressed(file);
}
}
static Future<CompoundTag> readCompressed(String file) async {
_io = ByteLayer();
await _io.readFromFile(file);
await _io.decompress();
_io.resetPosition();
return Tag.readNamedTag(_io) as CompoundTag;
}
static Future<void> write(String file) async {
await _io.writeToFile(file);
}
static Future<void> writeCompressed(String file) async {
await _io.compress();
await _io.writeToFile(file);
}
static ByteLayer getStream() {
return _io;
}
}

View file

@ -21,6 +21,7 @@ dev_dependencies:
# The following section is specific to Flutter packages.
flutter:
uses-material-design: true
# To add assets to your package, add an assets section, like this:
# assets:

17
test/nbt_test.dart Normal file
View file

@ -0,0 +1,17 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:libac_flutter/nbt/NbtIo.dart';
import 'package:libac_flutter/nbt/impl/CompoundTag.dart';
void main() {
test('read non-compressed helloworld NBT', () async {
print("READING : ${Directory.current.path}/test/hello_world.nbt");
CompoundTag tag =
await NbtIo.read("${Directory.current.path}/test/hello_world.nbt");
expect(tag.getKey(), "hello world");
expect(tag.contains("name"), true);
expect(tag.get("name")!.asString(), "Bananrama");
});
}