package com.evilco.mc.nbt.tag;

import com.evilco.mc.nbt.stream.NbtInputStream;
import com.evilco.mc.nbt.stream.NbtOutputStream;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * @auhtor Johannes Donath <johannesd@evil-co.com>
 * @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.org>
 */
public class TagString extends AbstractTag {

	/**
	 * Stores the tag value.
	 */
	protected String value;

	/**
	 * Constructs a new TagString.
	 * @param name
	 * @param value
	 */
	public TagString (@Nonnull String name, @Nonnull String value) {
		super (name);
		this.setValue (value);
	}

	/**
	 * Constructs a new TagString.
	 * @param inputStream
	 * @param anonymous
	 * @throws IOException
	 */
	public TagString (@Nonnull NbtInputStream inputStream, boolean anonymous) throws IOException {
		super (inputStream, anonymous);

		// read size
		int size = inputStream.readShort ();

		// read bytes
		byte[] data = new byte[size];
		inputStream.readFully (data);

		// store value
		this.setValue (new String (data, ITag.STRING_CHARSET));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public byte getTagID () {
		return TagType.STRING.typeID;
	}

	/**
	 * Returns the tag value.
	 * @return
	 */
	public String getValue () {
		return this.value;
	}

	/**
	 * Sets a new tag value.
	 * @param s
	 */
	public void setValue (@Nonnull String s) {
		this.value = s;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void write (NbtOutputStream outputStream, boolean anonymous) throws IOException {
		super.write (outputStream, anonymous);

		// write length
		outputStream.writeShort (this.value.length ());

		// write string
		outputStream.write (this.value.getBytes (ITag.STRING_CHARSET));
	}
}
@@ -1625,24 +1625,25 @@
 nonymous);%0D%0A
+%09
 %0D%0A%09%09// write
@@ -1649,16 +1649,225 @@
 e length
+ - since getBytes can produce an array of a different length than the original string%0D%0A%09%09// the length of the output array is the one to write%0D%0A%09%09byte%5B%5D outputBytes = this.value.getBytes (ITag.STRING_CHARSET);
 %0D%0A%09%09outp
@@ -1891,28 +1891,26 @@
 rt (
-this.value
+outputBytes
 .length
- ()
 );%0D%0A
@@ -1956,49 +1956,19 @@
 te (
-this.value.getBytes (ITag.STRING_CHARSET)
+outputBytes
 );%0D%0A
@@ -1972,8 +1972,10 @@
 ;%0D%0A%09%7D%0D%0A%7D
+%0D%0A

Use the actual length of bytes written in NBTTag String