Merge branch 'development'

This commit is contained in:
2020-04-29 12:37:31 +03:00
53 changed files with 942 additions and 454 deletions

3
.gitattributes vendored Normal file
View File

@@ -0,0 +1,3 @@
gradlew text eol=lf
gradlew.bat text eol=crlf
gradle/wrapper/gradle-wrapper.properties text eol=lf

3
.gitignore vendored
View File

@@ -9,7 +9,4 @@ out/
## GRADLE ##
.gradle/
build/
gradle/
gradlew
gradlew.bat
publish.gradle

125
README.MD
View File

@@ -1,16 +1,62 @@
# NBT Lib
![version: v1.0-RC](https://img.shields.io/badge/version-v1.0--RC-a0a.svg?style=flat)
![coverage: 81%](https://img.shields.io/badge/coverage-81%25-yellowgreen.svg?style=flat)
![version: v1.1-RC](https://img.shields.io/badge/version-v1.1--RC-a0a.svg?style=flat)
![coverage: 93%](https://img.shields.io/badge/coverage-93%25-darkgreen.svg?style=flat)
Библиотека для работы с NBT (Named Binary Tag) в отрыве от Minecraft.
Библиотека для работы с NBT (Named Binary Tag).
Начиная с версии `1.1-RC` разделена на две составляющие: теги и кодеки. Последние занимаются (де)сериализацией тегов.
## Примеры работы с NBT
**Создание тега типа String:**
```java
TagString tagString = new TagString();
tagString.setValue("hello!");
```
или в одну строчку
```java
TagString tagString = new TagString("hello!");
```
**Создание тега типа Compound:**
```java
TagCompound tagCompound = new TagCompound();
tagCompound.getValue().add(new TagLong("Seed", 1234567890));
```
## Сериализация NBT
Сериализация в бинарный формат Minecraft Vanilla выполняется библиотекой `nbt-vanilla-codec`.
Пример сериализации тега типа String в файл
```java
NbtOutputStream nbtOutputStream = new NbtOutputStream(new FileOutputStream("somefile.bin"));
nbtOutputStream.writeTag(new TagString("hello!"));
nbtOutputStream.close();
```
По такому же принципу происходит и десериализация
```java
NbtInputStream nbtInputStream = new NbtInputStream(new FileInputStream("somefile.bin"));
Tag tag = nbtInputStream.readTag();
nbtInputStream.close();
if (tag.getType() == TypeTag.STRING) {
TagString tagString = tag.asTagString();
}
```
## Подключение к проекту
### Maven
Добавляем сторонний репозитарий
```xml
<repositories>
<repository>
@@ -18,67 +64,34 @@
<url>https://dmx-mc-project.gitlab.io/maven-repository/</url>
</repository>
</repositories>
```
Добавляем dependency к себе в проект
```xml
<dependencies>
<dependency>
<groupId>mc-project</groupId>
<artifactId>nbt-lib</artifactId>
<version>1.0-RC</version>
<groupId>mc-project.nbt</groupId>
<artifactId>nbt</artifactId>
<version>1.1-RC</version>
</dependency>
<dependency>
<groupId>mc-project.nbt.codec</groupId>
<artifactId>nbt-vanilla-codec</artifactId>
<version>1.1-RC</version>
</dependency>
</dependencies>
```
### Gradle
Добавляем сторонний репозитарий
```groovy
repositories {
maven { url 'https://dmx-mc-project.gitlab.io/maven-repository/' }
maven {
name 'mc-project'
url 'https://dmx-mc-project.gitlab.io/maven-repository/'
}
}
dependencies {
implementation (group: 'mc-project.nbt', name: 'nbt', version: '1.1-RC')
implementation (group: 'mc-project.nbt.codec', name: 'nbt-vanilla-codec', version: '1.1-RC')
}
```
Добавляем dependency к себе в проект
```groovy
implementation (group: 'mc-project', name: 'nbt-lib', version: '1.0-RC')
```
## Использование
### Чтение
Для чтения NBT из потока (`InputStream`) используется класс `NbtInputStream`:
```java
NbtInputStream nbtInputStream = new NbtInputStream(inputStream);
Tag tag = nbtInputStream.readTag();
```
Если поток данных предполагается сжатым (GZip), то вторым параметром в конструкторе `NbtInputStream` указываем на это:
```java
NbtInputStream nbtInputStream = new NbtInputStream(inputStream, true);
Tag tag = nbtInputStream.readTag();
```
### Запись
Для записи NBT в поток (`OutputStream`) используется класс `NbtOutputStream`:
```java
NbtOutputStream nbtOutputStream = new NbtOutputStream(outputStream);
nbtOutputStream.writeTag(new TagString("Hello world"));
```
Если необходимо сжатие данных (GZip), то вторым параметром в конструкторе `NbtOutputStream` указываем на это:
```java
NbtOutputStream nbtOutputStream = new NbtOutputStream(outputStream, true);
nbtOutputStream.writeTag(new TagString("Hello world"));
```

View File

@@ -1,27 +1,40 @@
group = 'mc-project'
version = '1.0-RC'
/* Gradle 5.3 */
apply plugin: 'java'
apply plugin: 'jacoco'
repositories {
mavenLocal()
mavenCentral()
wrapper {
gradleVersion = '5.3'
distributionType = Wrapper.DistributionType.ALL
}
compileJava {
subprojects {
apply plugin: 'java'
apply plugin: 'jacoco'
def publishScript = file(rootProject.getProjectDir().getPath() + '/publish.gradle')
if (publishScript.exists()) {
apply from: publishScript.path
}
project.group = projectGroup
project.version = projectVersion
compileJava {
sourceCompatibility = 1.8
targetCompatibility = 1.8
options.encoding = 'UTF-8'
}
}
ext {
repositories {
mavenLocal()
mavenCentral()
}
ext {
slf4j_version = '1.7.25'
lombok_version = '1.18.2'
junit_version = '5.3.1'
}
}
dependencies {
dependencies {
/* LOGGER */
implementation (group: 'org.slf4j', name: 'slf4j-api', version: slf4j_version)
@@ -34,12 +47,13 @@ dependencies {
testImplementation (group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: junit_version)
testRuntimeOnly (group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: junit_version)
testImplementation (group: 'org.apache.commons', name: 'commons-lang3', version: '3.9')
}
}
test {
test {
useJUnitPlatform()
}
}
jacoco {
toolVersion = '0.8.3'
jacoco {
toolVersion = '0.8.5'
}
}

2
gradle.properties Normal file
View File

@@ -0,0 +1,2 @@
projectGroup=mc-project.nbt
projectVersion=1.1-RC

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Mon Apr 27 14:14:33 MSK 2020
distributionUrl=https\://services.gradle.org/distributions/gradle-5.3-all.zip
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

188
gradlew vendored Normal file
View File

@@ -0,0 +1,188 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

100
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -22,7 +22,7 @@ public enum TypeTag {
LONG_ARRAY(12, TagLongArray.class);
public static Tag getTagById(int id) {
TypeTag type = getTypeById(id);
TypeTag type = valueOfTypeId(id);
try {
return type.classTag.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
@@ -30,7 +30,7 @@ public enum TypeTag {
}
}
public static TypeTag getTypeById(int id) {
public static TypeTag valueOfTypeId(int id) {
for (TypeTag type : TypeTag.values()) {
if (type.id == id) {
return type;

View File

@@ -3,10 +3,6 @@ package mc.nbt.tag;
import lombok.Getter;
import lombok.Setter;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
public abstract class Tag {
@@ -16,10 +12,6 @@ public abstract class Tag {
public abstract TypeTag getType();
public abstract void readSelf(NbtInputStream nbtInputStream) throws IOException;
public abstract void writeSelf(NbtOutputStream nbtOutputStream) throws IOException;
public TagByte asTagByte() {
return (TagByte) this;
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagByte extends Tag {
public TypeTag getType() {
return TypeTag.BYTE;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readByte();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeByte(value);
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,16 +27,4 @@ public class TagByteArray extends Tag {
public TypeTag getType() {
return TypeTag.BYTE_ARRAY;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = new byte[nbtInputStream.readInt()];
nbtInputStream.read(value); //FIXME
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeInt(value.length);
nbtOutputStream.write(value);
}
}

View File

@@ -0,0 +1,32 @@
package mc.nbt.tag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import java.util.List;
@NoArgsConstructor
@ToString(callSuper = true)
public class TagCompound extends Tag {
@Getter
@Setter
private List<Tag> value;
public TagCompound(List<Tag> value) {
setValue(value);
}
public TagCompound(String name, List<Tag> value) {
this(value);
setName(name);
}
@Override
public TypeTag getType() {
return TypeTag.COMPOUND;
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagDouble extends Tag {
public TypeTag getType() {
return TypeTag.DOUBLE;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readDouble();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeDouble(value);
}
}

View File

@@ -1,11 +1,14 @@
package mc.nbt.tag;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
public class TagEnd extends Tag {
public static final TagEnd INSTANCE = new TagEnd();
TagEnd() {
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException();
@@ -20,14 +23,4 @@ public class TagEnd extends Tag {
public TypeTag getType() {
return TypeTag.END;
}
@lombok.Generated // Dirt hack for jacoco
@Override
public void readSelf(NbtInputStream nbtInputStream) {
}
@lombok.Generated // Dirt hack for jacoco
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) {
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagFloat extends Tag {
public TypeTag getType() {
return TypeTag.FLOAT;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readFloat();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeFloat(value);
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagInt extends Tag {
public TypeTag getType() {
return TypeTag.INT;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readInt();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeInt(value);
}
}

View File

@@ -0,0 +1,30 @@
package mc.nbt.tag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
@NoArgsConstructor
@ToString(callSuper = true)
public class TagIntArray extends Tag {
@Getter
@Setter
private int[] value;
public TagIntArray(int[] value) {
setValue(value);
}
public TagIntArray(String name, int[] value) {
this(value);
setName(name);
}
@Override
public TypeTag getType() {
return TypeTag.INT_ARRAY;
}
}

View File

@@ -5,11 +5,7 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -52,30 +48,4 @@ public class TagList extends Tag {
public TypeTag getType() {
return TypeTag.LIST;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
typeList = TypeTag.getTypeById(nbtInputStream.readByte());
int size = nbtInputStream.readInt();
if (size > 0) {
value = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
Tag tag = TypeTag.getTagById(typeList.getId());
tag.readSelf(nbtInputStream);
value.add(tag);
}
}
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeByte(typeList.getId());
nbtOutputStream.writeInt(value.size());
for (Tag tag : value) {
tag.writeSelf(nbtOutputStream);
}
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagLong extends Tag {
public TypeTag getType() {
return TypeTag.LONG;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readLong();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeLong(value);
}
}

View File

@@ -0,0 +1,30 @@
package mc.nbt.tag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
@NoArgsConstructor
@ToString(callSuper = true)
public class TagLongArray extends Tag {
@Getter
@Setter
private long[] value;
public TagLongArray(long[] value) {
setValue(value);
}
public TagLongArray(String name, long[] value) {
this(value);
setName(name);
}
@Override
public TypeTag getType() {
return TypeTag.LONG_ARRAY;
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagShort extends Tag {
public TypeTag getType() {
return TypeTag.SHORT;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readShort();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeShort(value);
}
}

View File

@@ -5,10 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
@@ -31,14 +27,4 @@ public class TagString extends Tag {
public TypeTag getType() {
return TypeTag.STRING;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
value = nbtInputStream.readString();
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeString(value);
}
}

View File

@@ -1,2 +1,4 @@
rootProject.name = 'nbt-lib'
include('nbt')
include('vanilla-codec')

View File

@@ -1,58 +0,0 @@
package mc.nbt.tag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@NoArgsConstructor
@ToString(callSuper = true)
public class TagCompound extends Tag {
@Getter
@Setter
private List<Tag> value;
public TagCompound(List<Tag> value) {
setValue(value);
}
public TagCompound(String name, List<Tag> value) {
this(value);
setName(name);
}
@Override
public TypeTag getType() {
return TypeTag.COMPOUND;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) {
value = new ArrayList<>();
while (true) {
Tag tag = nbtInputStream.readTag();
if (tag.getType() == TypeTag.END) {
break;
}
value.add(tag);
}
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
for (Tag tag : value) {
nbtOutputStream.writeTag(tag);
}
nbtOutputStream.writeTag(new TagEnd());
}
}

View File

@@ -1,52 +0,0 @@
package mc.nbt.tag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
public class TagIntArray extends Tag {
@Getter
@Setter
private int[] value;
public TagIntArray(int[] value) {
setValue(value);
}
public TagIntArray(String name, int[] value) {
this(value);
setName(name);
}
@Override
public TypeTag getType() {
return TypeTag.INT_ARRAY;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
int count = nbtInputStream.readInt();
value = new int[count];
for (int i = 0; i < count; i++) {
value[i] = nbtInputStream.readInt();
}
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeInt(value.length);
for (int item : value) {
nbtOutputStream.writeInt(item);
}
}
}

View File

@@ -1,52 +0,0 @@
package mc.nbt.tag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import mc.nbt.TypeTag;
import mc.nbt.io.NbtInputStream;
import mc.nbt.io.NbtOutputStream;
import java.io.IOException;
@NoArgsConstructor
@ToString(callSuper = true)
public class TagLongArray extends Tag {
@Getter
@Setter
private long[] value;
public TagLongArray(long[] value) {
setValue(value);
}
public TagLongArray(String name, long[] value) {
this(value);
setName(name);
}
@Override
public TypeTag getType() {
return TypeTag.LONG_ARRAY;
}
@Override
public void readSelf(NbtInputStream nbtInputStream) throws IOException {
int count = nbtInputStream.readInt();
value = new long[count];
for (int i = 0; i < count; i++) {
value[i] = nbtInputStream.readLong();
}
}
@Override
public void writeSelf(NbtOutputStream nbtOutputStream) throws IOException {
nbtOutputStream.writeInt(value.length);
for (long item : value) {
nbtOutputStream.writeLong(item);
}
}
}

View File

@@ -0,0 +1,3 @@
dependencies {
compile project(':nbt')
}

View File

@@ -0,0 +1,2 @@
projectGroup=mc-project.nbt.codec
projectName=nbt-vanilla-codec

View File

@@ -0,0 +1,13 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.Tag;
import java.io.IOException;
public interface Codec<T extends Tag> {
T decode(NbtInputStream in) throws IOException;
void encode(T tag, NbtOutputStream out) throws IOException;
}

View File

@@ -0,0 +1,36 @@
package mc.nbt.codec.vanilla;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import mc.nbt.TypeTag;
import java.util.stream.Stream;
@RequiredArgsConstructor
@Getter
public enum CodecEnum {
END(TypeTag.END, new TagEndCodec()),
BYTE(TypeTag.BYTE, new TagByteCodec()),
SHORT(TypeTag.SHORT, new TagShortCodec()),
INT(TypeTag.INT, new TagIntCodec()),
LONG(TypeTag.LONG, new TagLongCodec()),
FLOAT(TypeTag.FLOAT, new TagFloatCodec()),
DOUBLE(TypeTag.DOUBLE, new TagDoubleCodec()),
BYTE_ARRAY(TypeTag.BYTE_ARRAY, new TagByteArrayCodec()),
STRING(TypeTag.STRING, new TagStringCodec()),
LIST(TypeTag.LIST, new TagListCodec()),
COMPOUND(TypeTag.COMPOUND, new TagCompoundCodec()),
INT_ARRAY(TypeTag.INT_ARRAY, new TagIntArrayCodec()),
LONG_ARRAY(TypeTag.LONG_ARRAY, new TagLongArrayCodec());
public static CodecEnum valueOfTypeTag(TypeTag typeTag) {
return Stream.of(CodecEnum.values())
.filter(codecEnum -> codecEnum.getTypeTag() == typeTag)
.findFirst()
.orElseThrow(() -> new RuntimeException("Codec for " + typeTag.name() + " not found"));
}
private final TypeTag typeTag;
private final Codec codec;
}

View File

@@ -0,0 +1,23 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagByteArray;
import java.io.IOException;
class TagByteArrayCodec implements Codec<TagByteArray> {
@Override
public TagByteArray decode(NbtInputStream in) throws IOException {
byte[] value = new byte[in.readInt()];
in.read(value);
return new TagByteArray(value);
}
@Override
public void encode(TagByteArray tag, NbtOutputStream out) throws IOException {
out.writeInt(tag.getValue().length);
out.write(tag.getValue());
}
}

View File

@@ -0,0 +1,20 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagByte;
import java.io.IOException;
class TagByteCodec implements Codec<TagByte> {
@Override
public TagByte decode(NbtInputStream in) throws IOException {
return new TagByte(in.readByte());
}
@Override
public void encode(TagByte tag, NbtOutputStream out) throws IOException {
out.writeByte(tag.getValue());
}
}

View File

@@ -0,0 +1,42 @@
package mc.nbt.codec.vanilla;
import mc.nbt.TypeTag;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.Tag;
import mc.nbt.tag.TagCompound;
import mc.nbt.tag.TagEnd;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class TagCompoundCodec implements Codec<TagCompound> {
@Override
public TagCompound decode(NbtInputStream in) throws IOException {
List<Tag> tagList = new ArrayList<>();
while (true) {
Tag tag = in.readTag();
if (tag.getType() == TypeTag.END) {
break;
}
tagList.add(tag);
}
TagCompound tagCompound = new TagCompound();
tagCompound.setValue(tagList);
return tagCompound;
}
@Override
public void encode(TagCompound tag, NbtOutputStream out) throws IOException {
for (Tag itemTag : tag.getValue()) {
out.writeTag(itemTag);
}
out.writeTag(TagEnd.INSTANCE);
}
}

View File

@@ -0,0 +1,20 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagDouble;
import java.io.IOException;
public class TagDoubleCodec implements Codec<TagDouble> {
@Override
public TagDouble decode(NbtInputStream in) throws IOException {
return new TagDouble(in.readDouble());
}
@Override
public void encode(TagDouble tag, NbtOutputStream out) throws IOException {
out.writeDouble(tag.getValue());
}
}

View File

@@ -0,0 +1,18 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagEnd;
class TagEndCodec implements Codec<TagEnd> {
@Override
public TagEnd decode(NbtInputStream in) {
return TagEnd.INSTANCE;
}
@Override
public void encode(TagEnd tag, NbtOutputStream out) {
//nothing
}
}

View File

@@ -0,0 +1,20 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagFloat;
import java.io.IOException;
public class TagFloatCodec implements Codec<TagFloat> {
@Override
public TagFloat decode(NbtInputStream in) throws IOException {
return new TagFloat(in.readFloat());
}
@Override
public void encode(TagFloat tag, NbtOutputStream out) throws IOException {
out.writeFloat(tag.getValue());
}
}

View File

@@ -0,0 +1,29 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagIntArray;
import java.io.IOException;
public class TagIntArrayCodec implements Codec<TagIntArray> {
@Override
public TagIntArray decode(NbtInputStream in) throws IOException {
final int[] value = new int[in.readInt()];
for (int i = 0; i < value.length; i++) {
value[i] = in.readInt();
}
return new TagIntArray(value);
}
@Override
public void encode(TagIntArray tag, NbtOutputStream out) throws IOException {
out.writeInt(tag.getValue().length);
for (int item : tag.getValue()) {
out.writeInt(item);
}
}
}

View File

@@ -0,0 +1,20 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagInt;
import java.io.IOException;
class TagIntCodec implements Codec<TagInt> {
@Override
public TagInt decode(NbtInputStream in) throws IOException {
return new TagInt(in.readInt());
}
@Override
public void encode(TagInt tag, NbtOutputStream out) throws IOException {
out.writeInt(tag.getValue());
}
}

View File

@@ -0,0 +1,46 @@
package mc.nbt.codec.vanilla;
import mc.nbt.TypeTag;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.Tag;
import mc.nbt.tag.TagList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TagListCodec implements Codec<TagList> {
@Override
public TagList decode(NbtInputStream in) throws IOException {
final Codec typeCodec = CodecEnum.valueOfTypeTag(TypeTag.valueOfTypeId(in.readByte())).getCodec();
final int size = in.readInt();
List<Tag> tagList;
if (size > 0) {
tagList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
tagList.add(typeCodec.decode(in));
}
} else {
tagList = Collections.emptyList();
}
return new TagList(tagList);
}
@SuppressWarnings("unchecked")
@Override
public void encode(TagList tag, NbtOutputStream out) throws IOException {
out.writeByte(tag.getTypeList().getId());
out.writeInt(tag.getValue().size());
final Codec typeCodec = CodecEnum.valueOfTypeTag(tag.getTypeList()).getCodec();
for (Tag item : tag.getValue()) {
typeCodec.encode(item, out);
}
}
}

View File

@@ -0,0 +1,29 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagLongArray;
import java.io.IOException;
public class TagLongArrayCodec implements Codec<TagLongArray> {
@Override
public TagLongArray decode(NbtInputStream in) throws IOException {
final long[] value = new long[in.readInt()];
for (int i = 0; i < value.length; i++) {
value[i] = in.readLong();
}
return new TagLongArray(value);
}
@Override
public void encode(TagLongArray tag, NbtOutputStream out) throws IOException {
out.writeInt(tag.getValue().length);
for (long item : tag.getValue()) {
out.writeLong(item);
}
}
}

View File

@@ -0,0 +1,21 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagLong;
import java.io.IOException;
public class TagLongCodec implements Codec<TagLong> {
@Override
public TagLong decode(NbtInputStream in) throws IOException {
long value = in.readLong();
return new TagLong(value);
}
@Override
public void encode(TagLong tag, NbtOutputStream out) throws IOException {
out.writeLong(tag.getValue());
}
}

View File

@@ -0,0 +1,20 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagShort;
import java.io.IOException;
class TagShortCodec implements Codec<TagShort> {
@Override
public TagShort decode(NbtInputStream in) throws IOException {
return new TagShort(in.readShort());
}
@Override
public void encode(TagShort tag, NbtOutputStream out) throws IOException {
out.writeShort(tag.getValue());
}
}

View File

@@ -0,0 +1,20 @@
package mc.nbt.codec.vanilla;
import mc.nbt.codec.vanilla.io.NbtInputStream;
import mc.nbt.codec.vanilla.io.NbtOutputStream;
import mc.nbt.tag.TagString;
import java.io.IOException;
public class TagStringCodec implements Codec<TagString> {
@Override
public TagString decode(NbtInputStream in) throws IOException {
return new TagString(in.readString());
}
@Override
public void encode(TagString tag, NbtOutputStream out) throws IOException {
out.writeString(tag.getValue());
}
}

View File

@@ -1,7 +1,10 @@
package mc.nbt.io;
package mc.nbt.codec.vanilla.io;
import mc.nbt.TypeTag;
import mc.nbt.codec.vanilla.Codec;
import mc.nbt.codec.vanilla.CodecEnum;
import mc.nbt.tag.Tag;
import mc.nbt.tag.TagEnd;
import java.io.DataInputStream;
import java.io.IOException;
@@ -24,23 +27,20 @@ public class NbtInputStream extends InputStream {
this(inputStream, false);
}
public Tag readTag() {
Tag tag = null;
try {
tag = TypeTag.getTagById(read());
if (tag.getType() != TypeTag.END) {
tag.setName(readString());
}
tag.readSelf(this);
} catch (IOException e) {
e.printStackTrace(); //FIXME
}
public Tag readTag() throws IOException {
final TypeTag typeTag = TypeTag.valueOfTypeId(read());
if (typeTag == TypeTag.END) {
return TagEnd.INSTANCE;
} else {
final CodecEnum codecEnum = CodecEnum.valueOfTypeTag(typeTag);
final Codec codec = codecEnum.getCodec();
final String name = readString();
final Tag tag = codec.decode(this);
tag.setName(name);
return tag;
}
}
public byte readByte() throws IOException {
return dataInputStream.readByte();

View File

@@ -1,5 +1,8 @@
package mc.nbt.io;
package mc.nbt.codec.vanilla.io;
import mc.nbt.TypeTag;
import mc.nbt.codec.vanilla.Codec;
import mc.nbt.codec.vanilla.CodecEnum;
import mc.nbt.tag.Tag;
import java.io.DataOutputStream;
@@ -23,10 +26,16 @@ public class NbtOutputStream extends OutputStream {
this(outputStream, false);
}
@SuppressWarnings("unchecked")
public void writeTag(Tag tag) throws IOException {
writeByte(tag.getType().getId());
final TypeTag typeTag = tag.getType();
final CodecEnum codecEnum = CodecEnum.valueOfTypeTag(typeTag);
final Codec codec = codecEnum.getCodec();
writeByte(typeTag.getId());
writeString(tag.getName());
tag.writeSelf(this);
codec.encode(tag, this);
}
public void writeByte(int value) throws IOException {

View File

@@ -1,4 +1,4 @@
package mc.nbt.io;
package mc.nbt.codec.vanilla.io;
import mc.nbt.TypeTag;
import mc.nbt.tag.*;

View File

@@ -1,4 +1,4 @@
package mc.nbt.io;
package mc.nbt.codec.vanilla.io;
import mc.nbt.TypeTag;
import mc.nbt.tag.Tag;

View File

@@ -1,4 +1,4 @@
package mc.nbt.io;
package mc.nbt.codec.vanilla.io;
import mc.nbt.TypeTag;
import mc.nbt.tag.*;
@@ -32,7 +32,7 @@ class NbtOutputStreamTest {
@Test
void testWriteTagEnd() throws IOException {
nbtOutputStream.writeTag(new TagEnd());
nbtOutputStream.writeTag(TagEnd.INSTANCE);
Tag tag = createNbtInputStream().readTag();
assertEquals(TypeTag.END, tag.getType());
@@ -201,10 +201,11 @@ class NbtOutputStreamTest {
private static Stream<Arguments> streamOfTagList() {
final List<Tag> value = new ArrayList<>();
value.add(new TagLong("TestName", RandomUtils.nextLong()));
value.add(new TagLong(RandomUtils.nextLong()));
value.add(new TagLong(RandomUtils.nextLong()));
value.add(new TagLong(RandomUtils.nextLong()));
// value.add(new TagLong("TestName", RandomUtils.nextLong()));
// value.add(new TagLong(RandomUtils.nextLong()));
// value.add(new TagLong(RandomUtils.nextLong()));
// value.add(new TagLong(RandomUtils.nextLong()));
value.add(new TagLong(1L));
return Stream.of(
Arguments.of(new TagList(value)),