Example #1
0
        public void TransferTags(NbtWriter writer)
        {
            writer.WriteBool("piglin_safe", this.Element.PiglinSafe);
            writer.WriteBool("natural", this.Element.Natural);

            writer.WriteFloat("ambient_light", this.Element.AmbientLight);

            if (this.Element.FixedTime.HasValue)
            {
                writer.WriteLong("fixed_time", this.Element.FixedTime.Value);
            }

            writer.WriteString("infiniburn", this.Element.Infiniburn);

            writer.WriteBool("respawn_anchor_works", this.Element.RespawnAnchorWorks);
            writer.WriteBool("has_skylight", this.Element.HasSkylight);
            writer.WriteBool("bed_works", this.Element.BedWorks);

            writer.WriteString("effects", this.Element.Effects);

            writer.WriteBool("has_raids", this.Element.HasRaids);

            writer.WriteInt("logical_height", this.Element.LogicalHeight);

            writer.WriteFloat("coordinate_scale", this.Element.CoordinateScale);

            writer.WriteBool("ultrawarm", this.Element.Ultrawarm);
            writer.WriteBool("has_ceiling", this.Element.HasCeiling);
        }
Example #2
0
        public async Task WriteSlotAsync(ItemStack slot)
        {
            await this.WriteBooleanAsync(slot.Present);

            if (slot.Present)
            {
                await this.WriteVarIntAsync(slot.Id);

                await this.WriteByteAsync((sbyte)slot.Count);

                var writer = new NbtWriter(this, "");
                if (slot.Nbt == null)
                {
                    writer.EndCompound();
                    writer.Finish();
                    return;
                }

                //TODO write enchants
                writer.WriteShort("id", (short)slot.Id);
                writer.WriteInt("Damage", slot.Nbt.Damage);
                writer.WriteByte("Count", (byte)slot.Count);

                writer.EndCompound();

                writer.Finish();
            }
        }
Example #3
0
    public void Serialize(MinecraftStream minecraftStream)
    {
        using var stream     = new MinecraftStream();
        using var dataStream = new MinecraftStream();

        stream.WriteInt(Chunk.X);
        stream.WriteInt(Chunk.Z);

        //Chunk.CalculateHeightmap();
        var writer = new NbtWriter(stream, string.Empty);

        foreach (var(type, heightmap) in Chunk.Heightmaps)
        {
            if (type == ChunkData.HeightmapType.MotionBlocking)
            {
                writer.WriteTag(new NbtArray <long>(type.ToString().ToSnakeCase().ToUpper(), heightmap.GetDataArray().Cast <long>()));
            }
        }

        writer.EndCompound();
        writer.TryFinish();

        foreach (var section in Chunk.Sections)
        {
            if (section is { BlockStateContainer.IsEmpty: false })
Example #4
0
        public void ValueTest()
        {
            // write one named tag for every value type, and read it back
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                Assert.AreEqual(ms, writer.BaseStream);
                {
                    writer.WriteByte("byte", 1);
                    writer.WriteShort("short", 2);
                    writer.WriteInt("int", 3);
                    writer.WriteLong("long", 4L);
                    writer.WriteFloat("float", 5f);
                    writer.WriteDouble("double", 6d);
                    writer.WriteByteArray("byteArray", new byte[] { 10, 11, 12 });
                    writer.WriteIntArray("intArray", new[] { 20, 21, 22 });
                    writer.WriteString("string", "123");
                }
                Assert.IsFalse(writer.IsDone);
                writer.EndCompound();
                Assert.IsTrue(writer.IsDone);
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);

                TestFiles.AssertValueTest(file);
            }
        }
        public override void SendPacket(Stream s)
        {
            VarInt vi = new VarInt();

            MemoryStream ms = new MemoryStream();

            vi.SetValue(ProtocolVersion);
            ms.Write(vi.VarIntData, 0, vi.Length);

            vi.SetValue(Address.Length);
            ms.Write(vi.VarIntData, 0, vi.Length);

            NbtWriter.TagRawString(Address, ms);
            NbtWriter.TagShort(Port, ms);

            vi.SetValue(NextState);
            ms.Write(vi.VarIntData, 0, vi.Length);

            Packet.DataLength = (int)ms.Position;
            Packet.Data       = ms.ToArray();

            ms.Close();

            Packet.WritePacket(s);
        }
Example #6
0
        public void ByteArrayFromStream()
        {
            var data = new byte[64*1024];
            for (int i = 0; i < data.Length; i++) {
                data[i] = unchecked((byte)i);
            }

            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                {
                    byte[] buffer = new byte[1024];
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray1", dataStream, data.Length);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray2", dataStream, data.Length, buffer);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray3", dataStream, 1);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray4", dataStream, 1, buffer);
                    }

                    writer.BeginList("innerLists", NbtTagType.ByteArray, 4);
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, data.Length);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, data.Length, buffer);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, 1);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, 1, buffer);
                    }
                    writer.EndList();
                }
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                CollectionAssert.AreEqual(data, file.RootTag["byteArray1"].ByteArrayValue);
                CollectionAssert.AreEqual(data, file.RootTag["byteArray2"].ByteArrayValue);
                Assert.AreEqual(1, file.RootTag["byteArray3"].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["byteArray3"].ByteArrayValue[0]);
                Assert.AreEqual(1, file.RootTag["byteArray4"].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["byteArray4"].ByteArrayValue[0]);

                CollectionAssert.AreEqual(data, file.RootTag["innerLists"][0].ByteArrayValue);
                CollectionAssert.AreEqual(data, file.RootTag["innerLists"][1].ByteArrayValue);
                Assert.AreEqual(1, file.RootTag["innerLists"][2].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["innerLists"][2].ByteArrayValue[0]);
                Assert.AreEqual(1, file.RootTag["innerLists"][3].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["innerLists"][3].ByteArrayValue[0]);
            }
        }
Example #7
0
        public void Write(int x, short y, int z, NbtNode node)
        {
            lock (this)
            {
                NbtWriter    writer = new NbtWriter();
                MemoryStream stream = new MemoryStream();
                writer.WriteFile(stream, node);
                byte[] buffer = Compress(stream.ToArray());
                _sizes.Add(buffer.Length);
                int usedSectors = ((buffer.Length + 5) % _sectorSize) == 0
                                      ? (buffer.Length + 5) / _sectorSize
                                      : (buffer.Length + 5) / _sectorSize + 1;
                MoveToHeaderPosition(x, y, z);
                _filePointer.Write(0);

                int sectorPostion = FindFreeSector(usedSectors);
                int sector        = (sectorPostion << 9) | usedSectors;

                MoveToHeaderPosition(x, y, z);

                _filePointer.Write(sector);

                _filePointer.Seek(_headerSize + sectorPostion * _sectorSize, SeekOrigin.Begin);
                _filePointer.Write(buffer.Length);
                _filePointer.Write((byte)2);  //Zlib Compression
                _filePointer.Write(buffer);
                _filePointer.Flush();
            }
        }
		public void Ctor_Stream_ArgumentNullException()
		{
			// Arrange
			Stream stream = null;

			// Act
			NbtWriter writer = new NbtWriter(stream);
		}
		public void Ctor_BinaryWriter_ArgumentNullException()
		{
			// Arrange
			BinaryWriter binaryWriter = null;

			// Act
			NbtWriter writer = new NbtWriter(binaryWriter);
		}
Example #10
0
File: Nbt.cs Project: Tobi406/SM3
        public void NbtWriteBasic()
        {
            using var nbtWriter = new NbtWriter();
            nbtWriter.WriteRoot(_testCompound);
            var array = nbtWriter.Stream.ToArray();

            Assert.True(_testBytes.SequenceEqual(array));
        }
Example #11
0
        static void WriteHeader([NotNull] Map mapToSave, [NotNull] string path, [NotNull] NbtWriter writer)
        {
            writer.WriteByte("FormatVersion", 1);

            // write name and UUID
            World  mapWorld = mapToSave.World;
            string mapName;

            if (mapWorld != null)
            {
                mapName = mapWorld.Name;
            }
            else
            {
                mapName = Path.GetFileNameWithoutExtension(path);
            }
            writer.WriteString("Name", mapName);
            writer.WriteByteArray("UUID", mapToSave.Guid.ToByteArray());

            // write map dimensions
            writer.WriteShort("X", (short)mapToSave.Width);
            writer.WriteShort("Y", (short)mapToSave.Height);
            writer.WriteShort("Z", (short)mapToSave.Length);

            // write spawn
            writer.BeginCompound("Spawn");
            {
                Position spawn = mapToSave.Spawn;
                writer.WriteShort("X", spawn.X);
                writer.WriteShort("Y", spawn.Z);
                writer.WriteShort("Z", spawn.Y);
                writer.WriteByte("H", spawn.R);
                writer.WriteByte("P", spawn.L);
            }
            writer.EndCompound();

            // write timestamps
            writer.WriteLong("TimeCreated", mapToSave.DateCreated.ToUnixTime());
            writer.WriteLong("LastModified", mapToSave.DateCreated.ToUnixTime());
            // TODO: TimeAccessed

            // TODO: write CreatedBy

            // Write map origin information
            writer.BeginCompound("MapGenerator");
            {
                writer.WriteString("Software", "fCraft " + Updater.CurrentRelease.VersionString);
                string genName;
                if (!mapToSave.Metadata.TryGetValue(MapGenUtil.ParamsMetaGroup,
                                                    MapGenUtil.GenNameMetaKey,
                                                    out genName))
                {
                    genName = "Unknown";
                }
                writer.WriteString("MapGeneratorName", genName);
            }
            writer.EndCompound();
        }
Example #12
0
		public void Ctor_Stream_ArgumentException()
		{
			// Arrange
			Stream stream = new MemoryStream();
			stream.Close();

			// Act
			NbtWriter writer = new NbtWriter(stream);
		}
Example #13
0
        public void WriteDimensionCodec(DimensionCodec value)
        {
            var writer = new NbtWriter(this, "");

            value.TransferTags(writer);

            writer.EndCompound();
            writer.TryFinish();
        }
Example #14
0
		public void Write_ByteTag_ArgumentNullException()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtByte tag = null;

			// Act
			writer.Write(tag);
		}
Example #15
0
 public void HugeNbtWriterTest()
 {
     // Tests writing byte arrays that exceed the max NbtBinaryWriter chunk size
     using (BufferedStream bs = new BufferedStream(Stream.Null)) {
         NbtWriter writer = new NbtWriter(bs, "root");
         writer.WriteByteArray("payload4", new byte[5 * 1024 * 1024]);
         writer.EndCompound();
         writer.Finish();
     }
 }
Example #16
0
        public Task WriteNbtAsync(NbtTag tag)
        {
            var writer = new NbtWriter(new MemoryStream(), "Item");

            writer.WriteTag(tag);

            writer.EndCompound();
            writer.Finish();

            return(Task.CompletedTask);
        }
Example #17
0
 public void HugeNbtWriterTest()
 {
     // There is a bug in .NET Framework 4.0+ that causes BufferedStream.Write(Byte[],Int32,Int32)
     // to throw an OverflowException when writing in chunks of 1 GiB or more.
     // We work around that by splitting up writes into at-most 512 MiB segments.
     using (BufferedStream bs = new BufferedStream(Stream.Null)) {
         NbtWriter writer = new NbtWriter(bs, "root");
         writer.WriteByteArray("payload4", new byte[1024 * 1024 * 1024]);
         writer.EndCompound();
         writer.Finish();
     }
 }
Example #18
0
        public void Serialize(MinecraftStream minecraftStream)
        {
            using var stream     = new MinecraftStream();
            using var dataStream = new MinecraftStream();

            stream.WriteInt(Chunk.X);
            stream.WriteInt(Chunk.Z);

            stream.WriteBoolean(true); // full chunk

            int chunkSectionY = 0, mask = 0;

            foreach (var section in Chunk.Sections)
            {
                if ((changedSectionFilter & 1 << chunkSectionY) != 0)
                {
                    mask |= 1 << chunkSectionY;
                    section.WriteTo(dataStream);
                }

                chunkSectionY++;
            }

            stream.WriteVarInt(mask);

            Chunk.CalculateHeightmap();
            var writer = new NbtWriter(stream, string.Empty);

            foreach (var(type, heightmap) in Chunk.Heightmaps)
            {
                writer.WriteLongArray(type.ToString().ToSnakeCase().ToUpper(), heightmap.GetDataArray().Cast <long>().ToArray());
            }
            writer.EndCompound();
            writer.Finish();

            Chunk.BiomeContainer.WriteTo(stream);

            dataStream.Position = 0;
            stream.WriteVarInt((int)dataStream.Length);
            dataStream.CopyTo(stream);

            stream.WriteVarInt(0);

            minecraftStream.Lock.Wait();
            minecraftStream.WriteVarInt(Id.GetVarIntLength() + (int)stream.Length);
            minecraftStream.WriteVarInt(Id);
            stream.Position = 0;
            stream.CopyTo(minecraftStream);
            minecraftStream.Lock.Release();
        }
Example #19
0
 public DefaultPacketCodec(Stream baseStream)
 {
     _baseStream = baseStream;
     if (baseStream.CanRead)
     {
         _nbtReader    = new NbtReader(baseStream);
         _binaryReader = new EndianBinaryReader(baseStream, Endianness.BigEndian, EncodingType.UTF8, BooleanSize.U8);
     }
     if (baseStream.CanWrite)
     {
         _nbtWriter    = new NbtWriter(baseStream);
         _binaryWriter = new EndianBinaryWriter(baseStream, Endianness.BigEndian, EncodingType.UTF8, BooleanSize.U8);
     }
 }
Example #20
0
		public void Write_ByteTag()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtByte tag = new NbtByte("asdf", 123);
			byte[] expected = new byte[] { 0x01, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x7B };

			// Act
			writer.Write(tag);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #21
0
        public void WriteTooLongOfString()
        {
            using (var ms = new MemoryStream())
            {
                StringBuilder builder = new StringBuilder();
                while (builder.Length < 40000)
                {
                    builder.Append(builder.Length.ToString());
                }

                var writer = new NbtWriter(ms, "root");
                {
                    Assert.Throws <NbtFormatException>(() => writer.WriteString(builder.ToString()));
                }
            }
        }
Example #22
0
        public void TestSaveEmpty()
        {
            RemoveTestFile();

            NbtCompound expected = new NbtCompound();

            using (NbtWriter w = OpenTestFile())
                w.SaveTree(expected);

            NbtCompound loaded;

            using (NbtReader r = ReadTestFile())
                loaded = r.GetTree();

            Assert.AreEqual(expected, loaded);
        }
Example #23
0
 public void Save(Map mapToSave, string path)
 {
     using (FileStream fs = new FileStream(path, FileMode.Create)) {
         using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) {
             using (BufferedStream bs = new BufferedStream(gs, 8192)) {
                 NbtWriter writer = new NbtWriter(bs, RootTagName);
                 {
                     WriteHeader(mapToSave, path, writer);
                     writer.WriteByteArray("BlockArray", mapToSave.Blocks);
                     WriteMetadata(mapToSave, writer);
                 }
                 writer.EndCompound();
                 writer.Finish();
             }
         }
     }
 }
Example #24
0
 public void MissingNameTest()
 {
     using (var ms = new MemoryStream()) {
         NbtWriter writer = new NbtWriter(ms, "test");
         // All tags (aside from list elements) must be named
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtByte(123)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtShort(123)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtInt(123)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtLong(123)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtFloat(123)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtDouble(123)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtString("value")));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtByteArray(new byte[0])));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtIntArray(new int[0])));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtList(NbtTagType.Byte)));
         Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtCompound()));
     }
 }
Example #25
0
        public void TestSaveCompound()
        {
            NbtCompound expected = new NbtCompound();

            expected.Name = "RootCompound";
            expected.Attach(new NbtString {
                Name = "TestString", Value = "Test Value 123"
            });

            using (NbtWriter w = OpenTestFile())
                w.SaveTree(expected);

            NbtCompound loaded;

            using (NbtReader r = ReadTestFile())
                loaded = r.GetTree();

            Assert.AreEqual(expected, loaded);
        }
Example #26
0
        static void WriteMetadata([NotNull] Map mapToSave, [NotNull] NbtWriter writer)
        {
            writer.BeginCompound("Metadata");
            {
                // write fCraft's native metadata
                writer.BeginCompound("fCraft");
                {
                    string oldEntry = null;
                    foreach (MetadataEntry <string> entry in mapToSave.Metadata)
                    {
                        if (oldEntry != entry.Group)
                        {
                            // TODO: Modify MetadataCollection to allow easy iteration group-at-a-time
                            if (oldEntry != null)
                            {
                                writer.EndCompound();
                            }
                            oldEntry = entry.Group;
                            writer.BeginCompound(entry.Group);
                        }
                        writer.WriteString(entry.Key, entry.Value);
                    }
                    if (oldEntry != null)
                    {
                        writer.EndCompound();
                    }
                }
                writer.EndCompound();

                // TODO: write CPE metadata here

                // write foreign metadata
                if (MapUtility.PreserveForeignMetadata && mapToSave.ForeignMetadata != null)
                {
                    foreach (NbtTag metaGroup in mapToSave.ForeignMetadata)
                    {
                        writer.WriteTag(metaGroup);
                    }
                }
            }
            writer.EndCompound();
        }
Example #27
0
        public void ComplexStringsTest()
        {
            // Use a fixed seed for repeatability of this test
            Random rand = new Random(0);

            // Generate random Unicode strings
            const int     numStrings     = 1024;
            List <string> writtenStrings = new List <string>();

            for (int i = 0; i < numStrings; i++)
            {
                writtenStrings.Add(GenRandomUnicodeString(rand));
            }

            using (var ms = new MemoryStream()) {
                // Write a list of strings
                NbtWriter writer = new NbtWriter(ms, "test");
                writer.BeginList("stringList", NbtTagType.String, numStrings);
                foreach (string s in writtenStrings)
                {
                    writer.WriteString(s);
                }
                writer.EndList();
                writer.EndCompound();
                writer.Finish();

                // Rewind!
                ms.Position = 0;

                // Let's read what we have written, and check contents
                NbtFile file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                NbtCompound rootTag     = (NbtCompound)file.RootTag;
                var         readStrings =
                    rootTag.Get <NbtList>("stringList")
                    .ToArray <NbtString>()
                    .Select(tag => tag.StringValue);

                // Make sure that all read/written strings match exactly
                CollectionAssert.AreEqual(writtenStrings, readStrings);
            }
        }
Example #28
0
 public void WriteTagTest()
 {
     using (var ms = new MemoryStream()) {
         var writer = new NbtWriter(ms, "root");
         {
             foreach (NbtTag tag in TestFiles.MakeValueTest().Tags)
             {
                 writer.WriteTag(tag);
             }
             writer.EndCompound();
             Assert.IsTrue(writer.IsDone);
             writer.Finish();
         }
         ms.Position = 0;
         var  file      = new NbtFile();
         long bytesRead = file.LoadFromBuffer(ms.ToArray(), 0, (int)ms.Length, NbtCompression.None);
         Assert.AreEqual(bytesRead, ms.Length);
         TestFiles.AssertValueTest(file);
     }
 }
Example #29
0
        public void WriteMixedCodec(MixedCodec value)
        {
            var writer = new NbtWriter(this, "");

            var list = new NbtList(NbtTagType.Compound, "value");

            foreach (var(_, codec) in value.Dimensions)
            {
                codec.Write(list);
            }

            var dimensions = new NbtCompound(value.Dimensions.Name)
            {
                new NbtTag <string>("type", value.Dimensions.Name),

                list
            };

            #region biomes

            var biomes = new NbtList(NbtTagType.Compound, "value");

            foreach (var(_, biome) in value.Biomes)
            {
                biome.Write(biomes);
            }

            var biomeCompound = new NbtCompound(value.Biomes.Name)
            {
                new NbtTag <string>("type", value.Biomes.Name),

                biomes
            };
            #endregion

            writer.WriteTag(dimensions);
            writer.WriteTag(biomeCompound);

            writer.EndCompound();
            writer.TryFinish();
        }
Example #30
0
        public void ByteArrayFromStream()
        {
            var data = new byte[64*1024];
            for (int i = 0; i < data.Length; i++) {
                data[i] = unchecked((byte)i);
            }

            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                {
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray", dataStream, data.Length);
                    }
                }
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                CollectionAssert.AreEqual(file.RootTag["byteArray"].ByteArrayValue, data);
            }
        }
		public void Do_SerializeObject(NbtTagType tagType, string name, object value, NbtTagType? elementType, bool writeHeader, byte[] expected)
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			InstanceProxy contextProxy = InstanceProxy.For("Konves.Nbt", "Konves.Nbt.Serialization.SerializationContext", writer);

			// Act
			contextProxy.Invoke("SerializeObject", tagType, name, value, elementType, writeHeader);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #32
0
        public void CompoundListTest()
        {
            // test writing various combinations of compound tags and list tags
            const string testString = "Come on and slam, and welcome to the jam.";
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "Test");
                {
                    writer.BeginCompound("EmptyCompy"); {}
                    writer.EndCompound();

                    writer.BeginCompound("OuterNestedCompy");
                    {
                        writer.BeginCompound("InnerNestedCompy");
                        {
                            writer.WriteInt("IntTest", 123);
                            writer.WriteString("StringTest", testString);
                        }
                        writer.EndCompound();
                    }
                    writer.EndCompound();

                    writer.BeginList("ListOfInts", NbtTagType.Int, 3);
                    {
                        writer.WriteInt(1);
                        writer.WriteInt(2);
                        writer.WriteInt(3);
                    }
                    writer.EndList();

                    writer.BeginCompound("CompoundOfListsOfCompounds");
                    {
                        writer.BeginList("ListOfCompounds", NbtTagType.Compound, 1);
                        {
                            writer.BeginCompound();
                            {
                                writer.WriteInt("TestInt", 123);
                            }
                            writer.EndCompound();
                        }
                        writer.EndList();
                    }
                    writer.EndCompound();

                    writer.BeginList("ListOfEmptyLists", NbtTagType.List, 3);
                    {
                        writer.BeginList(NbtTagType.List, 0); {}
                        writer.EndList();
                        writer.BeginList(NbtTagType.List, 0); {}
                        writer.EndList();
                        writer.BeginList(NbtTagType.List, 0); {}
                        writer.EndList();
                    }
                    writer.EndList();
                }
                writer.EndCompound();
                writer.Finish();

                ms.Seek(0, SeekOrigin.Begin);
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                Console.WriteLine(file.ToString());
            }
        }
Example #33
0
        public void ValueTest()
        {
            // write one named tag for every value type, and read it back
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                {
                    writer.WriteByte("byte", 1);
                    writer.WriteShort("short", 2);
                    writer.WriteInt("int", 3);
                    writer.WriteLong("long", 4L);
                    writer.WriteFloat("float", 5f);
                    writer.WriteDouble("double", 6d);
                    writer.WriteByteArray("byteArray", new byte[] { 10, 11, 12 });
                    writer.WriteIntArray("intArray", new[] { 20, 21, 22 });
                    writer.WriteString("string", "123");
                }
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);

                TestFiles.AssertValueTest(file);
            }
        }
Example #34
0
		public void Write_IntTag()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtInt tag = new NbtInt("asdf", 305419896);
			byte[] expected = new byte[] { 0x03, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x12, 0x34, 0x56, 0x78 };

			// Act
			writer.Write(tag);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #35
0
        public void ErrorTest()
        {
            byte[]       dummyByteArray = { 1, 2, 3, 4, 5 };
            int[]        dummyIntArray  = { 1, 2, 3, 4, 5 };
            byte[]       dummyBuffer    = new byte[1024];
            MemoryStream dummyStream    = new MemoryStream(dummyByteArray);

            using (var ms = new MemoryStream()) {
                // null constructor parameters, or a non-writable stream
                Assert.Throws <ArgumentNullException>(() => new NbtWriter(null, "root"));
                Assert.Throws <ArgumentNullException>(() => new NbtWriter(ms, null));
                Assert.Throws <ArgumentException>(() => new NbtWriter(new NonWritableStream(), "root"));

                var writer = new NbtWriter(ms, "root");
                {
                    // use negative list size
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.BeginList("list", NbtTagType.Int, -1));
                    writer.BeginList("listOfLists", NbtTagType.List, 1);
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.BeginList(NbtTagType.Int, -1));
                    writer.BeginList(NbtTagType.Int, 0);
                    writer.EndList();
                    writer.EndList();

                    writer.BeginList("list", NbtTagType.Int, 1);

                    // invalid list type
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.BeginList(NbtTagType.End, 0));
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.BeginList("list", NbtTagType.End, 0));

                    // call EndCompound when not in a compound
                    Assert.Throws <NbtFormatException>(writer.EndCompound);

                    // end list before all elements have been written
                    Assert.Throws <NbtFormatException>(writer.EndList);

                    // write the wrong kind of tag inside a list
                    Assert.Throws <NbtFormatException>(() => writer.WriteShort(0));

                    // write a named tag where an unnamed tag is expected
                    Assert.Throws <NbtFormatException>(() => writer.WriteInt("NamedInt", 0));

                    // write too many list elements
                    writer.WriteTag(new NbtInt());
                    Assert.Throws <NbtFormatException>(() => writer.WriteInt(0));
                    writer.EndList();

                    // write a null tag
                    Assert.Throws <ArgumentNullException>(() => writer.WriteTag(null));

                    // write an unnamed tag where a named tag is expected
                    Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtInt()));
                    Assert.Throws <NbtFormatException>(() => writer.WriteInt(0));

                    // end a list when not in a list
                    Assert.Throws <NbtFormatException>(writer.EndList);

                    // unacceptable nulls: WriteString
                    Assert.Throws <ArgumentNullException>(() => writer.WriteString(null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteString("NullString", null));

                    // unacceptable nulls: WriteByteArray from array
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray(null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray(null, 0, 5));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray("NullByteArray", null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray("NullByteArray", null, 0, 5));

                    // unacceptable nulls: WriteByteArray from stream
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray(null, 5));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray(null, 5, null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray(dummyStream, 5, null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray("NullBuffer", dummyStream, 5, null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteByteArray("NullStream", null, 5));
                    Assert.Throws <ArgumentNullException>(
                        () => writer.WriteByteArray("NullStream", null, 5, dummyByteArray));

                    // unacceptable nulls: WriteIntArray
                    Assert.Throws <ArgumentNullException>(() => writer.WriteIntArray(null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteIntArray(null, 0, 5));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteIntArray("NullIntArray", null));
                    Assert.Throws <ArgumentNullException>(() => writer.WriteIntArray("NullIntArray", null, 0, 5));

                    // non-readable streams are unacceptable
                    Assert.Throws <ArgumentException>(() => writer.WriteByteArray(new NonReadableStream(), 0));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteByteArray(new NonReadableStream(), 0, new byte[10]));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteByteArray("NonReadableStream", new NonReadableStream(), 0));

                    // trying to write array with out-of-range offset/count
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.WriteByteArray(dummyByteArray, -1, 5));
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.WriteByteArray(dummyByteArray, 0, -1));
                    Assert.Throws <ArgumentException>(() => writer.WriteByteArray(dummyByteArray, 0, 6));
                    Assert.Throws <ArgumentException>(() => writer.WriteByteArray(dummyByteArray, 1, 5));
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => writer.WriteByteArray("OutOfRangeByteArray", dummyByteArray, -1, 5));
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => writer.WriteByteArray("OutOfRangeByteArray", dummyByteArray, 0, -1));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteByteArray("OutOfRangeByteArray", dummyByteArray, 0, 6));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteByteArray("OutOfRangeByteArray", dummyByteArray, 1, 5));

                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.WriteIntArray(dummyIntArray, -1, 5));
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.WriteIntArray(dummyIntArray, 0, -1));
                    Assert.Throws <ArgumentException>(() => writer.WriteIntArray(dummyIntArray, 0, 6));
                    Assert.Throws <ArgumentException>(() => writer.WriteIntArray(dummyIntArray, 1, 5));
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => writer.WriteIntArray("OutOfRangeIntArray", dummyIntArray, -1, 5));
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => writer.WriteIntArray("OutOfRangeIntArray", dummyIntArray, 0, -1));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteIntArray("OutOfRangeIntArray", dummyIntArray, 0, 6));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteIntArray("OutOfRangeIntArray", dummyIntArray, 1, 5));

                    // out-of-range values for stream-reading overloads of WriteByteArray
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.WriteByteArray(dummyStream, -1));
                    Assert.Throws <ArgumentOutOfRangeException>(() => writer.WriteByteArray("BadLength", dummyStream, -1));
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => writer.WriteByteArray(dummyStream, -1, dummyByteArray));
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => writer.WriteByteArray("BadLength", dummyStream, -1, dummyByteArray));
                    Assert.Throws <ArgumentException>(() => writer.WriteByteArray(dummyStream, 5, new byte[0]));
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteByteArray("BadLength", dummyStream, 5, new byte[0]));

                    // trying to read from non-readable stream
                    Assert.Throws <ArgumentException>(
                        () => writer.WriteByteArray("ByteStream", new NonReadableStream(), 0));

                    // finish too early
                    Assert.Throws <NbtFormatException>(writer.Finish);

                    writer.EndCompound();
                    writer.Finish();

                    // write tag after finishing
                    Assert.Throws <NbtFormatException>(() => writer.WriteTag(new NbtInt()));
                }
            }
        }
Example #36
0
		public void Write_Double()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			double value = 3.14159265358979311599796346854E0;
			byte[] expected = new byte[] { 0x06, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x40, 0x09, 0x21, 0xFB, 0x54, 0x44, 0x2D, 0x18 };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #37
0
		public void Write_StringTag()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtString tag = new NbtString("asdf", "jkl;");
			byte[] expected = new byte[] { 0x08, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x00, 0x04, 0x6A, 0x6B, 0x6C, 0x3B };

			// Act
			writer.Write(tag);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
 public void Serialize(NbtWriter nbtWriter, object o)
 {
     throw new NotImplementedException();
 }
Example #39
0
		public void Write_ListTag()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtList tag = new NbtList("asdf", NbtTagType.String, new NbtString[] {
				new NbtString(string.Empty, "jkl;1"),
				new NbtString(string.Empty, "jkl;2"),
				new NbtString(string.Empty, "jkl;3"),
				new NbtString(string.Empty, "jkl;4")
			});
			byte[] expected = new byte[] { 0x09, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x31, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x32, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x33, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x34 };

			// Act
			writer.Write(tag);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #40
0
		public void Write_List()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			NbtTagType elementType = NbtTagType.String;
			NbtString[] value = new NbtString[] {
				new NbtString(string.Empty, "jkl;1"),
				new NbtString(string.Empty, "jkl;2"),
				new NbtString(string.Empty, "jkl;3"),
				new NbtString(string.Empty, "jkl;4")
			};
			byte[] expected = new byte[] { 0x09, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x31, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x32, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x33, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x34 };

			// Act
			writer.Write(name, elementType, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #41
0
		public void Write_Compound()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			NbtTag[] value = new NbtTag[]
		    {
		        new NbtDouble("asdf", 3.14159265358979311599796346854E0),
		        new NbtShort("asdf", 12345)
		    };
			byte[] expected = new byte[] { 0x0A, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x06, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x40, 0x09, 0x21, 0xFB, 0x54, 0x44, 0x2D, 0x18, 0x02, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x30, 0x39, 0x00 };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #42
0
 public void HugeNbtWriterTest()
 {
     // There is a bug in .NET Framework 4.0+ that causes BufferedStream.Write(Byte[],Int32,Int32)
     // to throw an OverflowException when writing in chunks of 1 GiB or more.
     // We work around that by splitting up writes into at-most 512 MiB segments.
     using (BufferedStream bs = new BufferedStream(Stream.Null)) {
         NbtWriter writer = new NbtWriter(bs, "root");
         writer.WriteByteArray("payload4", new byte[1024*1024*1024]);
         writer.EndCompound();
         writer.Finish();
     }
 }
Example #43
0
		public void Write_Byte()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			byte value = 123;
			byte[] expected = new byte[] { 0x01, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x7B };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
		internal SerializationContext(NbtWriter nbtWriter)
			: this(nbtWriter, new Dictionary<Type, SerializationInfo[]>()) { }
Example #45
0
		public void Write_Int()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			int value = 305419896;
			byte[] expected = new byte[] { 0x03, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x12, 0x34, 0x56, 0x78 };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
		internal SerializationContext(NbtWriter nbtWriter, Dictionary<Type, SerializationInfo[]> serializationInfoCache)
		{
			m_nbtWriter = nbtWriter;
			m_serializationInfoCache = serializationInfoCache;
		}
Example #47
0
        public void ByteArrayFromStream()
        {
            var data = new byte[64 * 1024];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = unchecked ((byte)i);
            }

            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                {
                    byte[] buffer = new byte[1024];
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray1", dataStream, data.Length);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray2", dataStream, data.Length, buffer);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray3", dataStream, 1);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray4", dataStream, 1, buffer);
                    }

                    writer.BeginList("innerLists", NbtTagType.ByteArray, 4);
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, data.Length);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, data.Length, buffer);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, 1);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, 1, buffer);
                    }
                    writer.EndList();
                }
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                CollectionAssert.AreEqual(data, file.RootTag["byteArray1"].ByteArrayValue);
                CollectionAssert.AreEqual(data, file.RootTag["byteArray2"].ByteArrayValue);
                Assert.AreEqual(1, file.RootTag["byteArray3"].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["byteArray3"].ByteArrayValue[0]);
                Assert.AreEqual(1, file.RootTag["byteArray4"].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["byteArray4"].ByteArrayValue[0]);

                CollectionAssert.AreEqual(data, file.RootTag["innerLists"][0].ByteArrayValue);
                CollectionAssert.AreEqual(data, file.RootTag["innerLists"][1].ByteArrayValue);
                Assert.AreEqual(1, file.RootTag["innerLists"][2].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["innerLists"][2].ByteArrayValue[0]);
                Assert.AreEqual(1, file.RootTag["innerLists"][3].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["innerLists"][3].ByteArrayValue[0]);
            }
        }
Example #48
0
		public void Write_Float()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			float value = -3.1415927F;
			byte[] expected = new byte[] { 0x05, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0xC0, 0x49, 0x0F, 0xDB };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #49
0
        public void ErrorTest()
        {
            using (var ms = new MemoryStream()) {
                // null constructor parameters, or a non-writable stream
                Assert.Throws<ArgumentNullException>(() => new NbtWriter(null, "root"));
                Assert.Throws<ArgumentNullException>(() => new NbtWriter(ms, null));
                Assert.Throws<ArgumentException>(() => new NbtWriter(new NonWritableStream(), "root"));

                var writer = new NbtWriter(ms, "root");
                {
                    // use negative list size
                    Assert.Throws<ArgumentOutOfRangeException>(() => writer.BeginList("list", NbtTagType.Int, -1));
                    writer.BeginList("listOfLists", NbtTagType.List, 1);
                    Assert.Throws<ArgumentOutOfRangeException>(() => writer.BeginList(NbtTagType.Int, -1));
                    writer.BeginList(NbtTagType.Int, 0);
                    writer.EndList();
                    writer.EndList();

                    writer.BeginList("list", NbtTagType.Int, 1);

                    // invalid list type
                    Assert.Throws<ArgumentOutOfRangeException>(() => writer.BeginList(NbtTagType.End, 0));

                    // call EndCompound when not in a compound
                    Assert.Throws<NbtFormatException>(writer.EndCompound);

                    // end list before all elements have been written
                    Assert.Throws<NbtFormatException>(writer.EndList);

                    // write the wrong kind of tag inside a list
                    Assert.Throws<NbtFormatException>(() => writer.WriteShort(0));

                    // write a named tag where an unnamed tag is expected
                    Assert.Throws<NbtFormatException>(() => writer.WriteInt("NamedInt", 0));

                    // write too many list elements
                    writer.WriteTag(new NbtInt());
                    Assert.Throws<NbtFormatException>(() => writer.WriteInt(0));
                    writer.EndList();

                    // write a null tag
                    Assert.Throws<ArgumentNullException>(() => writer.WriteTag(null));

                    // write an unnamed tag where a named tag is expected
                    Assert.Throws<NbtFormatException>(() => writer.WriteTag(new NbtInt()));
                    Assert.Throws<NbtFormatException>(() => writer.WriteInt(0));

                    // end a list when not in a list
                    Assert.Throws<NbtFormatException>(writer.EndList);

                    // write null values where unacceptable
                    Assert.Throws<ArgumentNullException>(() => writer.WriteString("NullString", null));
                    Assert.Throws<ArgumentNullException>(() => writer.WriteByteArray("NullByteArray", null));
                    Assert.Throws<ArgumentNullException>(() => writer.WriteIntArray("NullIntArray", null));
                    Assert.Throws<ArgumentNullException>(() => writer.WriteString(null));
                    Assert.Throws<ArgumentNullException>(() => writer.WriteByteArray(null));
                    Assert.Throws<ArgumentNullException>(() => writer.WriteIntArray(null));

                    // trying to read from non-readable stream
                    Assert.Throws<ArgumentException>(
                        () => writer.WriteByteArray("ByteStream", new NonReadableStream(), 0));

                    // finish too early
                    Assert.Throws<NbtFormatException>(writer.Finish);

                    writer.EndCompound();
                    writer.Finish();

                    // write tag after finishing
                    Assert.Throws<NbtFormatException>(() => writer.WriteTag(new NbtInt()));
                }
            }
        }
Example #50
0
        internal void SaveNBT(NbtWriter writer)
        {
            writer.BeginCompound();

            // Identity
            writer.WriteInt("ID", Id);
            writer.WriteString("N", Name);
            if (DisplayedName != null)
            {
                writer.WriteString("DN", DisplayedName);
            }
            if (Email != null)
            {
                writer.WriteString("E", Email);
            }

            // Network information
            if (AccountType != AccountType.Unknown)
            {
                writer.WriteByte("AT", (byte)AccountType);
            }
            if (!Equals(LastIP, IPAddress.None))
            {
                writer.WriteByteArray("IP", LastIP.GetAddressBytes());
            }
            if (LastFailedLoginDate != DateTime.MinValue)
            {
                writer.WriteLong("LFD", LastFailedLoginDate.ToUnixTime());
                writer.WriteByteArray("LFIP", LastFailedLoginIP.GetAddressBytes());
            }
            if (BandwidthUseMode != BandwidthUseMode.Default)
            {
                writer.WriteByte("BUM", (byte)BandwidthUseMode);
            }

            // Online status
            writer.WriteLong("LFD", FirstLoginDate.ToUnixTime());
            writer.WriteLong("LLD", LastLoginDate.ToUnixTime());
            DateTime lastSeen;

            if (IsOnline)
            {
                lastSeen = DateTime.UtcNow;
            }
            else
            {
                lastSeen = LastSeen;
            }
            writer.WriteLong("LS", lastSeen.ToUnixTime());
            writer.WriteByte("IH", (byte)(IsHidden ? 1 : 0));

            // Rank information
            writer.WriteString("R", Rank.FullName);
            if (PreviousRank != null)
            {
                writer.WriteString("PR", PreviousRank.FullName);
            }
            if (RankChangeDate != DateTime.MinValue)
            {
                writer.WriteLong("RCD", RankChangeDate.ToUnixTime());
            }
            if (RankChangedBy != null)
            {
                writer.WriteString("RCB", RankChangedBy);
            }
            if (RankChangeReason != null)
            {
                writer.WriteString("RCR", RankChangeReason);
            }
            writer.WriteByte("RCT", (byte)RankChangeType);

            // Kicks
            if (TimesKicked > 0)
            {
                writer.WriteInt("TK", TimesKicked);
                writer.WriteLong("LKD", LastKickDate.ToUnixTime());
                if (LastKickBy != null)
                {
                    writer.WriteString("LKB", LastKickBy);
                }
                if (LastKickReason != null)
                {
                    writer.WriteString("LKR", LastKickReason);
                }
            }

            // Bans
            if (BanStatus != BanStatus.NotBanned)
            {
                writer.WriteByte("BS", (byte)BanStatus);
            }

            if (BanDate != DateTime.MinValue)
            {
                writer.WriteLong("BD", BanDate.ToUnixTime());
            }
            if (BannedBy != null)
            {
                writer.WriteString("BB", BannedBy);
            }
            if (BanReason != null)
            {
                writer.WriteString("BR", BanReason);
            }
            if (UnbanDate != DateTime.MinValue)
            {
                writer.WriteLong("UD", UnbanDate.ToUnixTime());
            }
            if (UnbannedBy != null)
            {
                writer.WriteString("UB", UnbannedBy);
            }
            if (UnbanReason != null)
            {
                writer.WriteString("UR", UnbanReason);
            }

            // Freeze
            if (IsFrozen)
            {
                writer.WriteByte("IF", 1);
                if (FrozenBy != null)
                {
                    writer.WriteString("FB", FrozenBy);
                }
                writer.WriteLong("FD", FrozenOn.ToUnixTime());
            }

            // Mute
            if (IsMuted)
            {
                writer.WriteLong("MU", MutedUntil.ToUnixTime());
                if (MutedBy != null)
                {
                    writer.WriteString("MB", MutedBy);
                }
            }

            // Stats
            writer.WriteInt("BBC", BlocksBuilt);
            writer.WriteInt("BDC", BlocksDeleted);
            writer.WriteLong("BRC", BlocksDrawn);
            writer.WriteInt("MW", MessagesWritten);
            writer.WriteInt("TV", TimesVisited);

            int    seconds;
            Player pObject = PlayerObject;

            if (pObject != null)
            {
                seconds = (int)TotalTime.Add(TimeSinceLastLogin).TotalSeconds;
            }
            else
            {
                seconds = (int)TotalTime.TotalSeconds;
            }
            writer.WriteInt("TT", seconds);
            if (TimesKickedOthers > 0)
            {
                writer.WriteInt("TKO", TimesKickedOthers);
            }
            if (TimesBannedOthers > 0)
            {
                writer.WriteInt("TBO", TimesBannedOthers);
            }

            writer.EndCompound();
        }
Example #51
0
        public void ListTest()
        {
            // write short (1-element) lists of every possible kind
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "Test");
                writer.BeginList("LotsOfLists", NbtTagType.List, 11);
                {
                    writer.BeginList(NbtTagType.Byte, 1);
                    writer.WriteByte(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.ByteArray, 1);
                    writer.WriteByteArray(new byte[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.Compound, 1);
                    writer.BeginCompound();
                    writer.EndCompound();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Double, 1);
                    writer.WriteDouble(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Float, 1);
                    writer.WriteFloat(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Int, 1);
                    writer.WriteInt(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.IntArray, 1);
                    writer.WriteIntArray(new[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.List, 1);
                    writer.BeginList(NbtTagType.List, 0);
                    writer.EndList();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Long, 1);
                    writer.WriteLong(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Short, 1);
                    writer.WriteShort(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.String, 1);
                    writer.WriteString("ponies");
                    writer.EndList();
                }
                writer.EndList();
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var reader = new NbtReader(ms);
                Assert.DoesNotThrow(() => reader.ReadAsTag());
            }
        }
Example #52
0
		public void Write_FloatTag()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtFloat tag = new NbtFloat("asdf", -3.1415927F);
			byte[] expected = new byte[] { 0x05, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0xC0, 0x49, 0x0F, 0xDB };

			// Act
			writer.Write(tag);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #53
0
 public void WriteTagTest()
 {
     using (var ms = new MemoryStream()) {
         var writer = new NbtWriter(ms, "root");
         {
             foreach (NbtTag tag in TestFiles.MakeValueTest().Tags) {
                 writer.WriteTag(tag);
             }
             writer.EndCompound();
             writer.Finish();
         }
         ms.Position = 0;
         var file = new NbtFile();
         file.LoadFromBuffer(ms.ToArray(), 0, (int)ms.Length, NbtCompression.None);
         TestFiles.AssertValueTest(file);
     }
 }
Example #54
0
		public void Write_Long()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			long value = 81985529216486895;
			byte[] expected = new byte[] { 0x04, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Example #55
0
        public async Task WriteSlotAsync(ItemStack slot)
        {
            if (slot is null)
            {
                slot = new ItemStack(0, 0)
                {
                    Present = true
                }
            }
            ;

            var item = slot.GetItem();

            await this.WriteBooleanAsync(slot.Present);

            if (slot.Present)
            {
                await this.WriteVarIntAsync(item.Id);

                await this.WriteByteAsync((sbyte)slot.Count);

                var writer = new NbtWriter(this, "");

                var itemMeta = slot.ItemMeta;

                //TODO write enchants
                if (itemMeta.HasTags())
                {
                    writer.WriteByte("Unbreakable", itemMeta.Unbreakable ? 1 : 0);

                    if (itemMeta.Durability > 0)
                    {
                        writer.WriteInt("Damage", itemMeta.Durability);
                    }

                    if (itemMeta.CustomModelData > 0)
                    {
                        writer.WriteInt("CustomModelData", itemMeta.CustomModelData);
                    }

                    if (itemMeta.CanDestroy != null)
                    {
                        writer.BeginList("CanDestroy", NbtTagType.String, itemMeta.CanDestroy.Count);

                        foreach (var block in itemMeta.CanDestroy)
                        {
                            writer.WriteString(block);
                        }

                        writer.EndList();
                    }

                    if (itemMeta.Name != null)
                    {
                        writer.BeginCompound("display");

                        writer.WriteString("Name", JsonConvert.SerializeObject(new List <ChatMessage> {
                            (ChatMessage)itemMeta.Name
                        }));

                        if (itemMeta.Lore != null)
                        {
                            writer.BeginList("Lore", NbtTagType.String, itemMeta.Lore.Count);

                            foreach (var lore in itemMeta.Lore)
                            {
                                writer.WriteString(JsonConvert.SerializeObject(new List <ChatMessage> {
                                    (ChatMessage)lore
                                }));
                            }

                            writer.EndList();
                        }

                        writer.EndCompound();
                    }
                    else if (itemMeta.Lore != null)
                    {
                        writer.BeginCompound("display");

                        writer.BeginList("Lore", NbtTagType.String, itemMeta.Lore.Count);

                        foreach (var lore in itemMeta.Lore)
                        {
                            writer.WriteString(JsonConvert.SerializeObject(new List <ChatMessage> {
                                (ChatMessage)lore
                            }));
                        }

                        writer.EndList();

                        writer.EndCompound();
                    }
                }

                writer.WriteString("id", item.UnlocalizedName);
                writer.WriteByte("Count", (byte)slot.Count);

                writer.EndCompound();
                writer.Finish();
            }
        }
Example #56
0
        public void CompoundListTest()
        {
            // test writing various combinations of compound tags and list tags
            const string testString = "Come on and slam, and welcome to the jam.";

            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "Test");
                {
                    writer.BeginCompound("EmptyCompy"); {}
                    writer.EndCompound();

                    writer.BeginCompound("OuterNestedCompy");
                    {
                        writer.BeginCompound("InnerNestedCompy");
                        {
                            writer.WriteInt("IntTest", 123);
                            writer.WriteString("StringTest", testString);
                        }
                        writer.EndCompound();
                    }
                    writer.EndCompound();

                    writer.BeginList("ListOfInts", NbtTagType.Int, 3);
                    {
                        writer.WriteInt(1);
                        writer.WriteInt(2);
                        writer.WriteInt(3);
                    }
                    writer.EndList();

                    writer.BeginCompound("CompoundOfListsOfCompounds");
                    {
                        writer.BeginList("ListOfCompounds", NbtTagType.Compound, 1);
                        {
                            writer.BeginCompound();
                            {
                                writer.WriteInt("TestInt", 123);
                            }
                            writer.EndCompound();
                        }
                        writer.EndList();
                    }
                    writer.EndCompound();


                    writer.BeginList("ListOfEmptyLists", NbtTagType.List, 3);
                    {
                        writer.BeginList(NbtTagType.List, 0); {}
                        writer.EndList();
                        writer.BeginList(NbtTagType.List, 0); {}
                        writer.EndList();
                        writer.BeginList(NbtTagType.List, 0); {}
                        writer.EndList();
                    }
                    writer.EndList();
                }
                writer.EndCompound();
                writer.Finish();

                ms.Seek(0, SeekOrigin.Begin);
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                Console.WriteLine(file.ToString());
            }
        }
Example #57
0
        public void ComplexStringsTest()
        {
            // Use a fixed seed for repeatability of this test
            Random rand = new Random(0);

            // Generate random Unicode strings
            const int numStrings = 1024;
            List<string> writtenStrings = new List<string>();
            for (int i = 0; i < numStrings; i++) {
                writtenStrings.Add(GenRandomUnicodeString(rand));
            }

            using (var ms = new MemoryStream()) {
                // Write a list of strings
                NbtWriter writer = new NbtWriter(ms, "test");
                writer.BeginList("stringList", NbtTagType.String, numStrings);
                foreach (string s in writtenStrings) {
                    writer.WriteString(s);
                }
                writer.EndList();
                writer.EndCompound();
                writer.Finish();

                // Rewind!
                ms.Position = 0;

                // Let's read what we have written, and check contents
                NbtFile file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                var readStrings =
                    file.RootTag.Get<NbtList>("stringList")
                        .ToArray<NbtString>()
                        .Select(tag => tag.StringValue);

                // Make sure that all read/written strings match exactly
                CollectionAssert.AreEqual(writtenStrings, readStrings);
            }
        }
Example #58
0
        public void ListTest()
        {
            // write short (1-element) lists of every possible kind
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "Test");
                writer.BeginList("LotsOfLists", NbtTagType.List, 11);
                {
                    writer.BeginList(NbtTagType.Byte, 1);
                    writer.WriteByte(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.ByteArray, 1);
                    writer.WriteByteArray(new byte[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.Compound, 1);
                    writer.BeginCompound();
                    writer.EndCompound();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Double, 1);
                    writer.WriteDouble(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Float, 1);
                    writer.WriteFloat(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Int, 1);
                    writer.WriteInt(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.IntArray, 1);
                    writer.WriteIntArray(new[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.List, 1);
                    writer.BeginList(NbtTagType.List, 0);
                    writer.EndList();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Long, 1);
                    writer.WriteLong(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Short, 1);
                    writer.WriteShort(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.String, 1);
                    writer.WriteString("ponies");
                    writer.EndList();
                }
                writer.EndList();
                Assert.IsFalse(writer.IsDone);
                writer.EndCompound();
                Assert.IsTrue(writer.IsDone);
                writer.Finish();

                ms.Position = 0;
                var reader = new NbtReader(ms);
                Assert.DoesNotThrow(() => reader.ReadAsTag());
            }
        }
		public void Serialize(NbtWriter nbtWriter, object o)
		{
			throw new NotImplementedException();
		}
Example #60
0
		public void Write_IntArray()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			int[] value = new int[] { 12345, 1337, 123456789, 55555555 };
			byte[] expected = new byte[] { 0x0B, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x30, 0x39, 0x00, 0x00, 0x05, 0x39, 0x07, 0x5B, 0xCD, 0x15, 0x03, 0x4F, 0xB5, 0xE3 };

			// Act
			writer.Write(name, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}