Пример #1
0
        public void Load()
        {
            lock (_chunkCache)
            {
                string filePath = FilePath;
                if (!File.Exists(filePath))
                {
                    // Welp, nothing to load.
                    IsLoaded = true;
                    return;
                }

                using (FileStream regionFile = File.OpenRead(filePath))
                {
                    AnvilRegionHeader header = LoadRegionHeader(regionFile);
                    RegionHeader = header;

                    //File.WriteAllLines(FilePath + ".header", header.GetAllChunkData().Select(h => string.Format("{0,-10}\t=>\t{1,-10}\t{2,-10}\t{3,-10}", h.ChunkCoordinates, h.LocationOffset, h.SectorCount, h.UpdatedTimestamp)).ToArray());

                    foreach (AnvilRegionHeaderChunkData data in header.GetAllChunkData())
                    {
                        // Attempt to load NbtFile for each chunk.
                        if (!data.ChunkExists)
                        {
                            continue;
                        }

                        regionFile.Seek(data.LocationOffset, SeekOrigin.Begin);
                        var lengthBuffer = new byte[4];
                        regionFile.Read(lengthBuffer, 0, 4);
                        Array.Reverse(lengthBuffer);

                        int nbtDataLength = BitConverter.ToInt32(lengthBuffer, 0) - 1;


                        int            compressionMode = regionFile.ReadByte();
                        NbtCompression compression     = compressionMode == 2
                                                                                                                ? NbtCompression.ZLib
                                                                                                                : (compressionMode == 1 ? NbtCompression.GZip : NbtCompression.None);

                        var nbtDataBuffer = new byte[nbtDataLength];
                        regionFile.Read(nbtDataBuffer, 0, nbtDataLength);

                        //Debug.WriteLine($"({data.ChunkCoordinates.X}, {data.ChunkCoordinates.Z}) Offset: {data.LocationOffset}, Header Length: {data.SectorCount}, NbtDataLength: {nbtDataLength}");

                        var nbtFile = new NbtFile();
                        nbtFile.LoadFromBuffer(nbtDataBuffer, 0, nbtDataLength, compression);

                        //File.WriteAllText(Path.Combine(Provider.BasePath, "region", FileName + $"_{data.ChunkCoordinates.X}-{data.ChunkCoordinates.Z}.txt"), nbtFile.ToString());

                        //Debug.WriteLine(
                        //	$"Region: ({X},{Z}), Chunk({data.ChunkCoordinates.X}, {data.ChunkCoordinates.Z}): NbtDataLength: {nbtDataLength}");

                        _containingChunks.TryAdd(data.ChunkCoordinates, nbtFile);
                    }
                }

                IsLoaded = true;
            }
        }
Пример #2
0
        public static NbtCompound LoadRootTagFromFile(string filePath, NbtCompression compression)
        {
            NbtFile file = new NbtFile();

            file.LoadFromFile(filePath, compression, null);
            return(file.RootTag);
        }
Пример #3
0
 /// <summary>
 /// Saves an NBT tag to a file.
 /// </summary>
 /// <param name="file">File to save to.</param>
 /// <param name="name">Name of the root tag.</param>
 /// <param name="compression">The compression to use.</param>
 /// <param name="encoding">The encoding to use for strings. Uses Java's weird MUTF8 encoding by default.</param>
 /// <param name="endianness">The endianness to use. PC = Big, Pocket Edition = Little.</param>
 /// <param name="ensureCompound">If true, throws an exception if the root tag isn't a compound.</param>
 public void Save(string file, string name,
                  NbtCompression compression, Encoding encoding = null,
                  Endianness endianness = Endianness.Big, bool ensureCompound = true)
 {
     using (var stream = File.Open(file, FileMode.OpenOrCreate))
         WriteTo(stream, name, compression, encoding, endianness, ensureCompound);
 }
Пример #4
0
 /// <summary>
 /// Loads an NBT tag from a file.
 /// </summary>
 /// <param name="file">File to load from.</param>
 /// <param name="name">Will be set to the name of the root tag.</param>
 /// <param name="compression">The compression to use, null or default to auto-detect.</param>
 /// <param name="encoding">The encoding to use for strings. Uses Java's weird MUTF8 encoding by default.</param>
 /// <param name="endianness">The endianness to use. PC = Big, Pocket Edition = Little.</param>
 /// <param name="ensureCompound">If true, throws an exception if the root tag isn't a compound.</param>
 public static TagBase Load(string file, out string name,
                            NbtCompression compression = null, Encoding encoding             = null,
                            Endianness endianness      = Endianness.Big, bool ensureCompound = true)
 {
     using (var stream = File.OpenRead(file))
         return(ReadFrom(stream, out name, compression, encoding, endianness, ensureCompound));
 }
Пример #5
0
 /// <summary> Loads NBT data from a stream. </summary>
 /// <param name="stream"> Stream from which data will be loaded. If compression is set to AutoDetect, this stream must support seeking. </param>
 /// <param name="compression"> Compression method to use for loading/saving this file. </param>
 /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is null. </exception>
 /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
 /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
 /// <exception cref="NotSupportedException"> If compression is set to AutoDetect, but the stream is not seekable. </exception>
 /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
 /// <exception cref="InvalidDataException"> If file compression could not be detected, decompressing failed, or given stream does not support reading. </exception>
 /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
 public NbtFile([NotNull] Stream stream, NbtCompression compression)
 {
     if (stream == null)
     {
         throw new ArgumentNullException("stream");
     }
     LoadFromStream(stream, compression);
 }
Пример #6
0
 public BaseReplayManager(GameManager gameManager, string replayFolder, int queueMaxLength, NbtCompression compressionMethod)
 {
     _gameManager       = gameManager;
     _replayFolderPath  = replayFolder;
     _compressionMethod = compressionMethod;
     _queueMaxLength    = queueMaxLength;
     _replayEvents      = new Queue <ReplayEvent <T> >(_queueMaxLength);
 }
Пример #7
0
        /// <summary>
        /// Loads an NBT tag from a file.
        /// Shorthand for ignoring the tag name.
        /// </summary>
        /// <param name="file">File to load from.</param>
        /// <param name="compression">The compression to use, null or default to auto-detect.</param>
        /// <param name="encoding">The encoding to use for strings. Uses Java's weird MUTF8 encoding by default.</param>
        /// <param name="endianness">The endianness to use. PC = Big, Pocket Edition = Little.</param>
        /// <param name="ensureCompound">If true, throws an exception if the root tag isn't a compound.</param>
        public static TagBase Load(string file,
                                   NbtCompression compression = null, Encoding encoding             = null,
                                   Endianness endianness      = Endianness.Big, bool ensureCompound = true)
        {
            string name;

            return(Load(file, out name, compression, encoding, endianness, ensureCompound));
        }
Пример #8
0
        /// <summary>
        /// Reads an NBT tag from a stream.
        /// Shorthand for ignoring the tag name.
        /// </summary>
        /// <param name="stream">The stream to load from.</param>
        /// <param name="compression">The compression to use, null or default to auto-detect.</param>
        /// <param name="encoding">The encoding to use for strings. Uses Java's weird MUTF8 encoding by default.</param>
        /// <param name="endianness">The endianness to use. PC = Big, Pocket Edition = Little.</param>
        /// <param name="ensureCompound">If true, throws an exception if the root tag isn't a compound.</param>
        public static TagBase ReadFrom(Stream stream,
                                       NbtCompression compression = null, Encoding encoding             = null,
                                       Endianness endianness      = Endianness.Big, bool ensureCompound = true)
        {
            string name;

            return(ReadFrom(stream, out name, compression, encoding, endianness, ensureCompound));
        }
Пример #9
0
 /// <summary> Loads NBT data from a file. </summary>
 /// <param name="fileName"> Name of the file from which data will be loaded. </param>
 /// <param name="compression"> Compression method to use for loading/saving this file. </param>
 /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is null. </exception>
 /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
 /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
 /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
 /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
 /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
 /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
 public NbtFile([NotNull] string fileName, NbtCompression compression)
 {
     if (fileName == null)
     {
         throw new ArgumentNullException("fileName");
     }
     LoadFromFile(fileName, compression);
 }
Пример #10
0
        public NbtFile GetChunk(long x, long z, long y)
        {
            long seek = 4 * (x % 32) + (z % 32) * 32;

            this.m_Reader.BaseStream.Seek(seek, SeekOrigin.Begin);
            byte[] offsetBytes = new byte[4] {
                0, 0, 0, 0
            };
            byte[] countBytes = new byte[1] {
                0
            };
            this.m_Reader.BaseStream.Read(offsetBytes, 1, 3);
            this.m_Reader.BaseStream.Read(countBytes, 0, 1);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(offsetBytes);
                Array.Reverse(countBytes);
            }
            int offset = BitConverter.ToInt32(offsetBytes, 0) * 4096;
            int count  = countBytes[0] * 4096;

            this.m_Reader.BaseStream.Seek(offset, SeekOrigin.Begin);
            byte[] lengthBytes      = new byte[4];
            byte[] compressionBytes = new byte[1];
            this.m_Reader.BaseStream.Read(lengthBytes, 0, 4);
            this.m_Reader.BaseStream.Read(compressionBytes, 0, 1);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(lengthBytes);
                Array.Reverse(compressionBytes);
            }
            int            length      = BitConverter.ToInt32(lengthBytes, 0) * 4096;
            int            compression = compressionBytes[0] * 4096;
            NbtCompression nbtComp     = NbtCompression.AutoDetect;

            /*switch (compression)
             * {
             *  case 0:
             *      nbtComp = NbtCompression.None;
             *      break;
             *  case 1:
             *      nbtComp = NbtCompression.GZip;
             *      break;
             *  case 2:
             *      nbtComp = NbtCompression.ZLib;
             *      break;
             * }*/
            if (length == 0)
            {
                return(null);
            }
            byte[]       data = new byte[length];
            MemoryStream mem  = new MemoryStream(data);

            this.m_Reader.BaseStream.Read(data, 0, length);
            return(new NbtFile(mem, nbtComp));
        }
Пример #11
0
        void LoadFromStreamInternal(String fileName, NbtCompression compression)
        {
            var file = new NbtFile();

            byte[] fileBytes = File.ReadAllBytes(fileName);
            using (var ms = new MemoryStream(fileBytes)) {
                file.LoadFromStream(ms, compression);
            }
        }
Пример #12
0
 // keep this private and only expose the static constructors below so callers don't have to include irrelevant information
 private ExportSettings(bool snbt, bool minified, bool json, NbtCompression compression, bool big_endian, bool bedrock_header)
 {
     Snbt          = snbt;
     Minified      = minified;
     Json          = json;
     Compression   = compression;
     BigEndian     = big_endian;
     BedrockHeader = bedrock_header;
 }
Пример #13
0
 public Schematic(short width, short length, short height, NbtCompression compression = NbtCompression.None)
 {
     Width       = width;
     Length      = length;
     Height      = height;
     Blocks      = new byte[width * length * height];
     Data        = new byte[Blocks.Length];
     Compression = compression;
 }
Пример #14
0
        public static string ReadRootTagName([NotNull] Stream stream, NbtCompression compression, bool bigEndian,
                                             int bufferSize)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (bufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("bufferSize", bufferSize, "DefaultBufferSize cannot be negative.");
            }
            // detect compression, based on the first byte
            if (compression == NbtCompression.AutoDetect)
            {
                compression = DetectCompression(stream);
            }

            switch (compression)
            {
            case NbtCompression.GZip:
                using (var decStream = new GZipStream(stream, CompressionMode.Decompress, true))
                {
                    if (bufferSize > 0)
                    {
                        return(GetRootNameInternal(new BufferedStream(decStream, bufferSize), bigEndian));
                    }
                    else
                    {
                        return(GetRootNameInternal(decStream, bigEndian));
                    }
                }

            case NbtCompression.None:
                return(GetRootNameInternal(stream, bigEndian));

            case NbtCompression.ZLib:
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException(WrongZLibHeaderMessage);
                }
                stream.ReadByte();
                using (var decStream = new DeflateStream(stream, CompressionMode.Decompress, true))
                {
                    if (bufferSize > 0)
                    {
                        return(GetRootNameInternal(new BufferedStream(decStream, bufferSize), bigEndian));
                    }
                    else
                    {
                        return(GetRootNameInternal(decStream, bigEndian));
                    }
                }

            default:
                throw new ArgumentOutOfRangeException("compression");
            }
        }
Пример #15
0
 public static void SaveTagToFile(NbtCompound rootTag, string filePath, NbtCompression compression)
 {
     try
     {
         new NbtFile(rootTag).SaveToFile(filePath, compression);
     }catch (Exception ex)
     {
         throw new ReplayException("Unable to save tag to file.", ex);
     }
 }
Пример #16
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="buffer"> Buffer to write data to. May not be <c>null</c>. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream should begin. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> is less than zero; or if <paramref name="index"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public long SaveToBuffer([NotNull] byte[] buffer, int index, NbtCompression compression)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            using (var ms = new MemoryStream(buffer, index, buffer.Length - index)) {
                return(SaveToStream(ms, compression));
            }
        }
Пример #17
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="fileName"> File to write data to. May not be <c>null</c>. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while creating the file. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public int SaveToFile([NotNull] string fileName, NbtCompression compression)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            using (FileStream saveFile = File.Create(fileName)) {
                return(SaveToStream(saveFile, compression));
            }
        }
Пример #18
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="buffer"> Buffer to write data to. May not be <c>null</c>. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream should begin. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> is less than zero; or if <paramref name="index"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public int SaveToBuffer([NotNull] byte[] buffer, int index, NbtCompression compression)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            using (MemoryStream ms = new MemoryStream(buffer, index, buffer.Length - index)) {
                SaveToStream(ms, compression);
                return((int)ms.Position);
            }
        }
Пример #19
0
        /// <summary> Loads NBT data from a byte array. Existing <c>RootTag</c> will be replaced. <c>FileName</c> will be set to null. </summary>
        /// <param name="buffer"> Stream from which data will be loaded. If <paramref name="compression"/> is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream begins. Must not be negative. </param>
        /// <param name="length"> Maximum number of bytes to read from the given buffer. Must not be negative.
        /// An <see cref="EndOfStreamException"/> is thrown if NBT stream is longer than the given length. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <returns> Number of bytes read from the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> or <paramref name="length"/> is less than zero;
        /// if the sum of <paramref name="index"/> and <paramref name="length"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="EndOfStreamException"> If NBT stream extends beyond the given <paramref name="length"/>. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
        public long LoadFromBuffer([NotNull] byte[] buffer, int index, int length, NbtCompression compression)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            using (var ms = new MemoryStream(buffer, index, length)) {
                LoadFromStream(ms, compression, null);
                FileName = null;
                return(ms.Position);
            }
        }
Пример #20
0
        /// <summary> Loads NBT data from a file. Existing <c>RootTag</c> will be replaced. </summary>
        /// <param name="fileName"> Name of the file from which data will be loaded. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
        public int LoadFromFile([NotNull] string fileName, NbtCompression compression,
                                [CanBeNull] TagSelector selector)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            using (FileStream readFileStream = File.OpenRead(fileName)) {
                LoadFromStream(readFileStream, compression, selector);
                FileName = fileName;
                return((int)readFileStream.Position);
            }
        }
Пример #21
0
        /// <summary> Loads NBT data from a byte array. Existing <c>RootTag</c> will be replaced. <c>FileName</c> will be set to null. </summary>
        /// <param name="buffer"> Stream from which data will be loaded. If <paramref name="compression"/> is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream begins. Must not be negative. </param>
        /// <param name="length"> Maximum number of bytes to read from the given buffer. Must not be negative.
        /// An <see cref="EndOfStreamException"/> is thrown if NBT stream is longer than the given length. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> or <paramref name="length"/> is less than zero;
        /// if the sum of <paramref name="index"/> and <paramref name="length"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="EndOfStreamException"> If NBT stream extends beyond the given <paramref name="length"/>. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        public int LoadFromBuffer([NotNull] byte[] buffer, int index, int length, NbtCompression compression,
                                  [CanBeNull] TagSelector selector)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            using (MemoryStream ms = new MemoryStream(buffer, index, length)) {
                LoadFromStream(ms, compression, selector);
                FileName = null;
                return((int)ms.Position);
            }
        }
Пример #22
0
 public NbtReader(Stream input, NbtCompression compressionMode = NbtCompression.None)
 {
     if (compressionMode == NbtCompression.GZip)
     {
         this.BaseStream = new GZipStream(input, CompressionMode.Decompress);
     }
     else if (compressionMode == NbtCompression.ZLib)
     {
         this.BaseStream = new ZLibStream(input, CompressionMode.Decompress);
     }
     else
     {
         this.BaseStream = input;
     }
 }
Пример #23
0
        void ReadRootTagInternal(String fileName, NbtCompression compression)
        {
            Assert.Throws <ArgumentOutOfRangeException>(() => NbtFile.ReadRootTagName(fileName, compression, true, -1));

            Assert.AreEqual("Level", NbtFile.ReadRootTagName(fileName));
            Assert.AreEqual("Level", NbtFile.ReadRootTagName(fileName, compression, true, 0));

            byte[] fileBytes = File.ReadAllBytes(fileName);
            using (var ms = new MemoryStream(fileBytes)) {
                using (var nss = new NonSeekableStream(ms)) {
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => NbtFile.ReadRootTagName(nss, compression, true, -1));
                    NbtFile.ReadRootTagName(nss, compression, true, 0);
                }
            }
        }
Пример #24
0
        /// <summary> Loads NBT data from a file. Existing RootTag will be replaced. </summary>
        /// <param name="fileName"> Name of the file from which data will be loaded. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is null. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
        public void LoadFromFile([NotNull] string fileName, NbtCompression compression)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(String.Format("Could not find NBT file: {0}", fileName),
                                                fileName);
            }

            using (FileStream readFileStream = File.OpenRead(fileName)) {
                LoadFromStream(readFileStream, compression);
            }
            FileName = fileName;
        }
Пример #25
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="fileName"> File to write data to. May not be <c>null</c>. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while creating the file. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public long SaveToFile([NotNull] string fileName, NbtCompression compression)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            using (
                var saveFile = new FileStream(fileName,
                                              FileMode.Create,
                                              FileAccess.Write,
                                              FileShare.None,
                                              FileStreamBufferSize,
                                              FileOptions.SequentialScan)) {
                return(SaveToStream(saveFile, compression));
            }
        }
Пример #26
0
        void ReloadFileInternal(String fileName, NbtCompression compression, bool bigEndian, bool buffered)
        {
            var loadedFile = new NbtFile(Path.Combine(TestFiles.DirName, fileName))
            {
                BigEndian = bigEndian
            };

            if (!buffered)
            {
                loadedFile.BufferSize = 0;
            }
            long bytesWritten = loadedFile.SaveToFile(Path.Combine(TestDirName, fileName), compression);
            long bytesRead    = loadedFile.LoadFromFile(Path.Combine(TestDirName, fileName), NbtCompression.AutoDetect,
                                                        null);

            Assert.AreEqual(bytesWritten, bytesRead);
            TestFiles.AssertNbtBigFile(loadedFile);
        }
Пример #27
0
        /// <summary> Loads NBT data from a file. Existing <c>RootTag</c> will be replaced. </summary>
        /// <param name="fileName"> Name of the file from which data will be loaded. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
        public long LoadFromFile([NotNull] string fileName, NbtCompression compression, [CanBeNull] TagSelector selector)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            using (
                var readFileStream = new FileStream(fileName,
                                                    FileMode.Open,
                                                    FileAccess.Read,
                                                    FileShare.Read,
                                                    FileStreamBufferSize,
                                                    FileOptions.SequentialScan)) {
                LoadFromStream(readFileStream, compression, selector);
                FileName = fileName;
                return(readFileStream.Position);
            }
        }
Пример #28
0
        public void Load()
        {
            if (IsCorrupt || IsExternal)
            {
                return;
            }
            var stream = Region.GetStream();

            stream.Seek(Offset + 4, SeekOrigin.Begin);
            int compression = stream.ReadByte();

            if (compression == -1)
            {
                IsCorrupt = true;
                Remove();
            }
            else
            {
                if ((compression & (1 << 7)) != 0)
                {
                    IsExternal          = true;
                    ExternalCompression = (byte)compression;
                }
                else
                {
                    var file = new fNbt.NbtFile();
                    try
                    {
                        file.LoadFromStream(stream, NbtCompression.AutoDetect);
                        Compression = file.FileCompression;
                        SetData(file.GetRootTag <NbtCompound>());
                    }
                    catch
                    {
                        IsCorrupt = true;
                        Remove();
                    }
                }
            }
            stream.Dispose();
            OnLoaded?.Invoke(this, EventArgs.Empty);
        }
Пример #29
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="stream"> Stream to write data to. May not be <c>null</c>. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the stream. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="NbtFormatException"> If RootTag is null;
        /// or if RootTag is unnamed;
        /// or if one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public long SaveToStream([NotNull] Stream stream, NbtCompression compression)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            switch (compression) {
                case NbtCompression.AutoDetect:
                    throw new ArgumentException("AutoDetect is not a valid NbtCompression value for saving.");
                case NbtCompression.ZLib:
                case NbtCompression.GZip:
                case NbtCompression.None:
                    break;
                default:
                    throw new ArgumentOutOfRangeException("compression");
            }

            if (rootTag.Name == null) {
                throw new NbtFormatException(
                    "Cannot save NbtFile: Root tag is not named. Its name may be an empty string, but not null.");
            }

            long startOffset = 0;
            if (stream.CanSeek) {
                startOffset = stream.Position;
            } else {
                stream = new ByteCountingStream(stream);
            }

            switch (compression) {
                case NbtCompression.ZLib:
                    stream.WriteByte(0x78);
                    stream.WriteByte(0x01);
                    int checksum;
                    using (var compressStream = new ZLibStream(stream, CompressionMode.Compress, true)) {
                        var bufferedStream = new BufferedStream(compressStream, WriteBufferSize);
                        RootTag.WriteTag(new NbtBinaryWriter(bufferedStream, BigEndian));
                        bufferedStream.Flush();
                        checksum = compressStream.Checksum;
                    }
                    byte[] checksumBytes = BitConverter.GetBytes(checksum);
                    if (BitConverter.IsLittleEndian) {
                        // Adler32 checksum is big-endian
                        Array.Reverse(checksumBytes);
                    }
                    stream.Write(checksumBytes, 0, checksumBytes.Length);
                    break;

                case NbtCompression.GZip:
                    using (var compressStream = new GZipStream(stream, CompressionMode.Compress, true)) {
                        // use a buffered stream to avoid GZipping in small increments (which has a lot of overhead)
                        var bufferedStream = new BufferedStream(compressStream, WriteBufferSize);
                        RootTag.WriteTag(new NbtBinaryWriter(bufferedStream, BigEndian));
                        bufferedStream.Flush();
                    }
                    break;

                case NbtCompression.None: {
                    var writer = new NbtBinaryWriter(stream, BigEndian);
                    RootTag.WriteTag(writer);
                }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("compression");
            }

            if (stream.CanSeek) {
                return stream.Position - startOffset;
            } else {
                return ((ByteCountingStream)stream).BytesWritten;
            }
        }
Пример #30
0
 void ReloadFileInternal(String fileName, NbtCompression compression, bool bigEndian, bool buffered)
 {
     var loadedFile = new NbtFile(Path.Combine(TestFiles.DirName, fileName)) {
         BigEndian = bigEndian
     };
     if (!buffered) {
         loadedFile.BufferSize = 0;
     }
     long bytesWritten = loadedFile.SaveToFile(Path.Combine(TestDirName, fileName), compression);
     long bytesRead = loadedFile.LoadFromFile(Path.Combine(TestDirName, fileName), NbtCompression.AutoDetect,
                                              null);
     Assert.AreEqual(bytesWritten, bytesRead);
     TestFiles.AssertNbtBigFile(loadedFile);
 }
Пример #31
0
 public byte[] SaveToBuffer(NbtCompression compression)
 {
     using (var ms = new MemoryStream()) {
         SaveToStream(ms, compression);
         return ms.ToArray();
     }
 }
Пример #32
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="fileName"> File to write data to. May not be <c>null</c>. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while creating the file. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public long SaveToFile([NotNull] string fileName, NbtCompression compression)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            using (
                var saveFile = new FileStream(fileName,
                                              FileMode.Create,
                                              FileAccess.Write,
                                              FileShare.None,
                                              FileStreamBufferSize,
                                              FileOptions.SequentialScan)) {
                return SaveToStream(saveFile, compression);
            }
        }
Пример #33
0
 /// <summary> Loads NBT data from a stream. Existing <c>RootTag</c> will be replaced </summary>
 /// <param name="stream"> Stream from which data will be loaded. If compression is set to AutoDetect, this stream must support seeking. </param>
 /// <param name="compression"> Compression method to use for loading/saving this file. </param>
 /// <returns> Number of bytes read from the stream. </returns>
 /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is <c>null</c>. </exception>
 /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
 /// <exception cref="NotSupportedException"> If <paramref name="compression"/> is set to AutoDetect, but the stream is not seekable. </exception>
 /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
 /// <exception cref="InvalidDataException"> If file compression could not be detected, decompressing failed, or given stream does not support reading. </exception>
 /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
 public long LoadFromStream([NotNull] Stream stream, NbtCompression compression)
 {
     return LoadFromStream(stream, compression, null);
 }
Пример #34
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="buffer"> Buffer to write data to. May not be <c>null</c>. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream should begin. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> is less than zero; or if <paramref name="index"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public long SaveToBuffer([NotNull] byte[] buffer, int index, NbtCompression compression)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            using (var ms = new MemoryStream(buffer, index, buffer.Length - index)) {
                return SaveToStream(ms, compression);
            }
        }
Пример #35
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is null. </summary>
        /// <param name="fileName"> File to write data to. May not be null. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is null. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the compression mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while creating the file. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public void SaveToFile( [NotNull] string fileName, NbtCompression compression )
        {
            if( fileName == null ) throw new ArgumentNullException( "fileName" );

            using( FileStream saveFile = File.Create( fileName ) ) {
                SaveToStream( saveFile, compression );
            }
        }
Пример #36
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is <c>null</c>. </summary>
        /// <param name="buffer"> Buffer to write data to. May not be <c>null</c>. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream should begin. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <returns> Number of bytes written to the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the <paramref name="compression"/> mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> is less than zero; or if <paramref name="index"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="UnauthorizedAccessException"> Specified file is read-only, or a permission issue occurred. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public int SaveToBuffer( [NotNull] byte[] buffer, int index, NbtCompression compression )
        {
            if( buffer == null )
                throw new ArgumentNullException( "buffer" );

            using( MemoryStream ms = new MemoryStream( buffer, index, buffer.Length - index ) ) {
                SaveToStream( ms, compression );
                return (int)ms.Position;
            }
        }
Пример #37
0
 void LoadFromStreamInternal(String fileName, NbtCompression compression)
 {
     var file = new NbtFile();
     byte[] fileBytes = File.ReadAllBytes(fileName);
     using (var ms = new MemoryStream(fileBytes)) {
         file.LoadFromStream(ms, compression);
     }
 }
Пример #38
0
        void ReadRootTagInternal(String fileName, NbtCompression compression)
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => NbtFile.ReadRootTagName(fileName, compression, true, -1));

            Assert.AreEqual("Level", NbtFile.ReadRootTagName(fileName));
            Assert.AreEqual("Level", NbtFile.ReadRootTagName(fileName, compression, true, 0));

            byte[] fileBytes = File.ReadAllBytes(fileName);
            using (var ms = new MemoryStream(fileBytes)) {
                using (var nss = new NonSeekableStream(ms)) {
                    Assert.Throws<ArgumentOutOfRangeException>(
                        () => NbtFile.ReadRootTagName(nss, compression, true, -1));
                    NbtFile.ReadRootTagName(nss, compression, true, 0);
                }
            }
        }
Пример #39
0
        /// <summary> Saves this NBT file to a stream. Nothing is written to stream if RootTag is null. </summary>
        /// <param name="stream"> Stream to write data to. May not be null. </param>
        /// <param name="compression"> Compression mode to use for saving. May not be AutoDetect. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is null. </exception>
        /// <exception cref="ArgumentException"> If AutoDetect was given as the compression mode. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
        /// <exception cref="InvalidDataException"> If given stream does not support writing. </exception>
        /// <exception cref="NbtFormatException"> If one of the NbtCompound tags contained unnamed tags;
        /// or if an NbtList tag had Unknown list type and no elements. </exception>
        public void SaveToStream( [NotNull] Stream stream, NbtCompression compression )
        {
            if( stream == null ) throw new ArgumentNullException( "stream" );

            switch( compression ) {
                case NbtCompression.AutoDetect:
                    throw new ArgumentException( "AutoDetect is not a valid NbtCompression value for saving." );
                case NbtCompression.ZLib:
                case NbtCompression.GZip:
                case NbtCompression.None:
                    break;
                default:
                    throw new ArgumentOutOfRangeException( "compression" );
            }

            // do not write anything for empty tags
            if( RootTag == null ) return;

            switch( compression ) {
                case NbtCompression.ZLib:
                    stream.WriteByte( 0x78 );
                    stream.WriteByte( 0x01 );
                    int checksum;
                    using( var compressStream = new ZLibStream( stream, CompressionMode.Compress, true ) ) {
                        BufferedStream bufferedStream = new BufferedStream( compressStream, BufferSize );
                        RootTag.WriteTag( new NbtWriter( bufferedStream ), true );
                        bufferedStream.Flush();
                        checksum = compressStream.Checksum;
                    }
                    byte[] checksumBytes = BitConverter.GetBytes(checksum);
                    if( BitConverter.IsLittleEndian ) {
                        // Adler32 checksum is big-endian
                        Array.Reverse( checksumBytes );
                    }
                    stream.Write( checksumBytes, 0, checksumBytes.Length );
                    break;

                case NbtCompression.GZip:
                    using( var compressStream = new GZipStream( stream, CompressionMode.Compress, true ) ) {
                        // use a buffered stream to avoid gzipping in small increments (which has a lot of overhead)
                        BufferedStream bufferedStream = new BufferedStream( compressStream, BufferSize );
                        RootTag.WriteTag( new NbtWriter( bufferedStream ), true );
                        bufferedStream.Flush();
                    }
                    break;

                case NbtCompression.None:
                    RootTag.WriteTag( new NbtWriter( stream ), true );
                    break;
            }
        }
Пример #40
0
        /// <summary> Loads NBT data from a file. Existing <c>RootTag</c> will be replaced. </summary>
        /// <param name="fileName"> Name of the file from which data will be loaded. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
        public int LoadFromFile( [NotNull] string fileName, NbtCompression compression,
                                 [CanBeNull] TagSelector selector )
        {
            if( fileName == null )
                throw new ArgumentNullException( "fileName" );

            using( FileStream readFileStream = File.OpenRead( fileName ) ) {
                LoadFromStream( readFileStream, compression, selector );
                FileName = fileName;
                return (int)readFileStream.Position;
            }
        }
Пример #41
0
        /// <summary> Loads NBT data from a stream. Existing <c>RootTag</c> will be replaced </summary>
        /// <param name="stream"> Stream from which data will be loaded. If compression is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <returns> Number of bytes read from the stream. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="NotSupportedException"> If <paramref name="compression"/> is set to AutoDetect, but the stream is not seekable. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, decompressing failed, or given stream does not support reading. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        public int LoadFromStream( [NotNull] Stream stream, NbtCompression compression )
        {
            if( stream == null )
                throw new ArgumentNullException( "stream" );

            FileName = null;
            FileCompression = compression;

            // detect compression, based on the first byte
            if( compression == NbtCompression.AutoDetect ) {
                compression = DetectCompression( stream );
            }

            long startPosition = stream.Position;

            switch( compression ) {
                case NbtCompression.GZip:
                    using( var decStream = new GZipStream( stream, CompressionMode.Decompress, true ) ) {
                        if( bufferSize > 0 ) {
                            LoadFromStreamInternal( new BufferedStream( decStream, bufferSize ), null );
                        } else {
                            LoadFromStreamInternal( decStream, null );
                        }
                    }
                    break;

                case NbtCompression.None:
                    LoadFromStreamInternal( stream, null );
                    break;

                case NbtCompression.ZLib:
                    if( stream.ReadByte() != 0x78 ) {
                        throw new InvalidDataException( "Incorrect ZLib header. Expected 0x78 0x9C" );
                    }
                    stream.ReadByte();
                    using( var decStream = new DeflateStream( stream, CompressionMode.Decompress, true ) ) {
                        if( bufferSize > 0 ) {
                            LoadFromStreamInternal( new BufferedStream( decStream, bufferSize ), null );
                        } else {
                            LoadFromStreamInternal( decStream, null );
                        }
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException( "compression" );
            }

            return (int)( stream.Position - startPosition );
        }
Пример #42
0
 /// <summary> Loads NBT data from a stream. </summary>
 /// <param name="stream"> Stream from which data will be loaded. If compression is set to AutoDetect, this stream must support seeking. </param>
 /// <param name="compression"> Compression method to use for loading/saving this file. </param>
 /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is null. </exception>
 /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
 /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
 /// <exception cref="NotSupportedException"> If compression is set to AutoDetect, but the stream is not seekable. </exception>
 /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
 /// <exception cref="InvalidDataException"> If file compression could not be detected, decompressing failed, or given stream does not support reading. </exception>
 /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
 public NbtFile( [NotNull] Stream stream, NbtCompression compression )
 {
     if( stream == null ) throw new ArgumentNullException( "stream" );
     LoadFromStream( stream, compression );
 }
Пример #43
0
 /// <summary> Loads NBT data from a file. </summary>
 /// <param name="fileName"> Name of the file from which data will be loaded. </param>
 /// <param name="compression"> Compression method to use for loading/saving this file. </param>
 /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is null. </exception>
 /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
 /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
 /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
 /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
 /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
 /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
 public NbtFile( [NotNull] string fileName, NbtCompression compression )
 {
     if( fileName == null ) throw new ArgumentNullException( "fileName" );
     LoadFromFile( fileName, compression );
 }
Пример #44
0
        /// <summary> Loads NBT data from a byte array. Existing <c>RootTag</c> will be replaced. <c>FileName</c> will be set to null. </summary>
        /// <param name="buffer"> Stream from which data will be loaded. If <paramref name="compression"/> is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream begins. Must not be negative. </param>
        /// <param name="length"> Maximum number of bytes to read from the given buffer. Must not be negative.
        /// An <see cref="EndOfStreamException"/> is thrown if NBT stream is longer than the given length. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <returns> Number of bytes read from the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> or <paramref name="length"/> is less than zero;
        /// if the sum of <paramref name="index"/> and <paramref name="length"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="EndOfStreamException"> If NBT stream extends beyond the given <paramref name="length"/>. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
        public int LoadFromBuffer([NotNull] byte[] buffer, int index, int length, NbtCompression compression)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            using (var ms = new MemoryStream(buffer, index, length)) {
                LoadFromStream(ms, compression, null);
                FileName = null;
                return (int)ms.Position;
            }
        }
Пример #45
0
        /// <summary> Loads NBT data from a file. Existing <c>RootTag</c> will be replaced. </summary>
        /// <param name="fileName"> Name of the file from which data will be loaded. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the file. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
        public int LoadFromFile([NotNull] string fileName, NbtCompression compression, [CanBeNull] TagSelector selector)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            using (
                var readFileStream = new FileStream(fileName,
                                                    FileMode.Open,
                                                    FileAccess.Read,
                                                    FileShare.Read,
                                                    FileStreamBufferSize,
                                                    FileOptions.SequentialScan)) {
                LoadFromStream(readFileStream, compression, selector);
                FileName = fileName;
                return (int)readFileStream.Position;
            }
        }
Пример #46
0
        /// <summary> Loads NBT data from a byte array. Existing <c>RootTag</c> will be replaced. <c>FileName</c> will be set to null. </summary>
        /// <param name="buffer"> Stream from which data will be loaded. If <paramref name="compression"/> is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="index"> The index into <paramref name="buffer"/> at which the stream begins. Must not be negative. </param>
        /// <param name="length"> Maximum number of bytes to read from the given buffer. Must not be negative.
        /// An <see cref="EndOfStreamException"/> is thrown if NBT stream is longer than the given length. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the buffer. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="buffer"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>;
        /// if <paramref name="index"/> or <paramref name="length"/> is less than zero;
        /// if the sum of <paramref name="index"/> and <paramref name="length"/> is greater than the length of <paramref name="buffer"/>. </exception>
        /// <exception cref="EndOfStreamException"> If NBT stream extends beyond the given <paramref name="length"/>. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
        public long LoadFromBuffer([NotNull] byte[] buffer, int index, int length, NbtCompression compression,
                                   [CanBeNull] TagSelector selector)
        {
            if (buffer == null) throw new ArgumentNullException("buffer");

            using (var ms = new MemoryStream(buffer, index, length)) {
                LoadFromStream(ms, compression, selector);
                FileName = null;
                return ms.Position;
            }
        }
Пример #47
0
        /// <summary> Loads NBT data from a stream. Existing <c>RootTag</c> will be replaced </summary>
        /// <param name="stream"> Stream from which data will be loaded. If compression is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <param name="selector"> Optional callback to select which tags to load into memory. Root may not be skipped.
        /// No reference is stored to this callback after loading (don't worry about implicitly captured closures). May be <c>null</c>. </param>
        /// <returns> Number of bytes read from the stream. </returns>
        /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for <paramref name="compression"/>. </exception>
        /// <exception cref="NotSupportedException"> If <paramref name="compression"/> is set to AutoDetect, but the stream is not seekable. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, decompressing failed, or given stream does not support reading. </exception>
        /// <exception cref="NbtFormatException"> If an error occurred while parsing data in NBT format. </exception>
        public long LoadFromStream([NotNull] Stream stream, NbtCompression compression, [CanBeNull] TagSelector selector)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            FileName = null;

            // detect compression, based on the first byte
            if (compression == NbtCompression.AutoDetect) {
                FileCompression = DetectCompression(stream);
            } else {
                FileCompression = compression;
            }

            // prepare to count bytes read
            long startOffset = 0;
            if (stream.CanSeek) {
                startOffset = stream.Position;
            } else {
                stream = new ByteCountingStream(stream);
            }

            switch (FileCompression) {
                case NbtCompression.GZip:
                    using (var decStream = new GZipStream(stream, CompressionMode.Decompress, true)) {
                        if (bufferSize > 0) {
                            LoadFromStreamInternal(new BufferedStream(decStream, bufferSize), selector);
                        } else {
                            LoadFromStreamInternal(decStream, selector);
                        }
                    }
                    break;

                case NbtCompression.None:
                    LoadFromStreamInternal(stream, selector);
                    break;

                case NbtCompression.ZLib:
                    if (stream.ReadByte() != 0x78) {
                        throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                    }
                    stream.ReadByte();
                    using (var decStream = new DeflateStream(stream, CompressionMode.Decompress, true)) {
                        if (bufferSize > 0) {
                            LoadFromStreamInternal(new BufferedStream(decStream, bufferSize), selector);
                        } else {
                            LoadFromStreamInternal(decStream, selector);
                        }
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("compression");
            }

            // report bytes read
            if (stream.CanSeek) {
                return stream.Position - startOffset;
            } else {
                return ((ByteCountingStream)stream).BytesRead;
            }
        }
Пример #48
0
 public static string ReadRootTagName([NotNull] string fileName, NbtCompression compression, bool bigEndian,
                                      int bufferSize)
 {
     if (fileName == null) {
         throw new ArgumentNullException("fileName");
     }
     if (!File.Exists(fileName)) {
         throw new FileNotFoundException("Could not find the given NBT file.", fileName);
     }
     if (bufferSize < 0) {
         throw new ArgumentOutOfRangeException("bufferSize", bufferSize, "DefaultBufferSize cannot be negative.");
     }
     using (FileStream readFileStream = File.OpenRead(fileName)) {
         return ReadRootTagName(readFileStream, compression, bigEndian, bufferSize);
     }
 }
Пример #49
0
        /// <summary> Loads NBT data from a file. Existing RootTag will be replaced. </summary>
        /// <param name="fileName"> Name of the file from which data will be loaded. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="fileName"/> is null. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, or decompressing failed. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        /// <exception cref="IOException"> If an I/O error occurred while reading the file. </exception>
        public void LoadFromFile( [NotNull] string fileName, NbtCompression compression )
        {
            if( fileName == null ) throw new ArgumentNullException( "fileName" );
            if( !File.Exists( fileName ) ) {
                throw new FileNotFoundException( String.Format( "Could not find NBT file: {0}", fileName ),
                                                 fileName );
            }

            using( FileStream readFileStream = File.OpenRead( fileName ) ) {
                LoadFromStream( readFileStream, compression );
            }
            FileName = fileName;
        }
Пример #50
0
        /// <summary> Loads NBT data from a stream. Existing RootTag will be replaced </summary>
        /// <param name="stream"> Stream from which data will be loaded. If compression is set to AutoDetect, this stream must support seeking. </param>
        /// <param name="compression"> Compression method to use for loading/saving this file. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="stream"/> is null. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> If an unrecognized/unsupported value was given for compression. </exception>
        /// <exception cref="FileNotFoundException"> If given file was not found. </exception>
        /// <exception cref="NotSupportedException"> If compression is set to AutoDetect, but the stream is not seekable. </exception>
        /// <exception cref="EndOfStreamException"> If file ended earlier than expected. </exception>
        /// <exception cref="InvalidDataException"> If file compression could not be detected, decompressing failed, or given stream does not support reading. </exception>
        /// <exception cref="NbtFormatException"> If an error occured while parsing data in NBT format. </exception>
        public void LoadFromStream( [NotNull] Stream stream, NbtCompression compression )
        {
            if( stream == null ) throw new ArgumentNullException( "stream" );

            FileName = null;
            FileCompression = compression;

            // detect compression, based on the first byte
            if( compression == NbtCompression.AutoDetect ) {
                if( !stream.CanSeek ) {
                    throw new NotSupportedException( "Cannot auto-detect compression on a stream that's not seekable." );
                }
                int firstByte = stream.ReadByte();
                switch( firstByte ) {
                    case -1:
                        throw new EndOfStreamException();

                    case (byte)NbtTagType.Compound: // 0x0A
                        compression = NbtCompression.None;
                        break;

                    case 0x1F:
                        // gzip magic number
                        compression = NbtCompression.GZip;
                        break;

                    case 0x78:
                        // zlib header
                        compression = NbtCompression.ZLib;
                        break;

                    default:
                        throw new InvalidDataException( "Could not auto-detect compression format." );
                }
                stream.Seek( -1, SeekOrigin.Current );
            }

            switch( compression ) {
                case NbtCompression.GZip:
                    using( var decStream = new GZipStream( stream, CompressionMode.Decompress, true ) ) {
                        LoadFromStreamInternal( new BufferedStream( decStream, BufferSize ) );
                    }
                    break;

                case NbtCompression.None:
                    LoadFromStreamInternal( stream );
                    break;

                case NbtCompression.ZLib:
                    if( stream.ReadByte() != 0x78 ) {
                        throw new InvalidDataException( "Incorrect ZLib header. Expected 0x78 0x9C" );
                    }
                    stream.ReadByte();
                    using( var decStream = new DeflateStream( stream, CompressionMode.Decompress, true ) ) {
                        LoadFromStreamInternal( new BufferedStream( decStream, BufferSize ) );
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException( "compression" );
            }
        }
Пример #51
0
        public static string ReadRootTagName([NotNull] Stream stream, NbtCompression compression, bool bigEndian,
                                             int bufferSize)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (bufferSize < 0) {
                throw new ArgumentOutOfRangeException("bufferSize", bufferSize, "DefaultBufferSize cannot be negative.");
            }
            // detect compression, based on the first byte
            if (compression == NbtCompression.AutoDetect) {
                compression = DetectCompression(stream);
            }

            switch (compression) {
                case NbtCompression.GZip:
                    using (var decStream = new GZipStream(stream, CompressionMode.Decompress, true)) {
                        if (bufferSize > 0) {
                            return GetRootNameInternal(new BufferedStream(decStream, bufferSize), bigEndian);
                        } else {
                            return GetRootNameInternal(decStream, bigEndian);
                        }
                    }

                case NbtCompression.None:
                    return GetRootNameInternal(stream, bigEndian);

                case NbtCompression.ZLib:
                    if (stream.ReadByte() != 0x78) {
                        throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                    }
                    stream.ReadByte();
                    using (var decStream = new DeflateStream(stream, CompressionMode.Decompress, true)) {
                        if (bufferSize > 0) {
                            return GetRootNameInternal(new BufferedStream(decStream, bufferSize), bigEndian);
                        } else {
                            return GetRootNameInternal(decStream, bigEndian);
                        }
                    }

                default:
                    throw new ArgumentOutOfRangeException("compression");
            }
        }