diff --git a/src/NGrib/BufferedBinaryReader.cs b/src/NGrib/BufferedBinaryReader.cs index c16067c..caf08e9 100644 --- a/src/NGrib/BufferedBinaryReader.cs +++ b/src/NGrib/BufferedBinaryReader.cs @@ -18,6 +18,7 @@ */ using System; +using System.Buffers; using System.IO; using System.Numerics; using NGrib.Grib2.Sections; @@ -44,8 +45,8 @@ public BufferedBinaryReader(Stream stream, bool leaveOpen = false, int bufferSiz { this.stream = stream; this.leaveOpen = leaveOpen; - this.bufferSize = bufferSize; - buffer = new byte[bufferSize]; + buffer = ArrayPool.Shared.Rent(bufferSize); + this.bufferSize = buffer.Length; MarkBufferAsUsed(); SaveCurrentPosition(); } @@ -77,7 +78,7 @@ private bool FillBuffer() private void EnsureAvailable(int numBytes) { if (NumBytesAvailable >= numBytes) return; - + // Try to read from the stream // and check that we were able to read the bytes we wanted if (!FillBuffer() && NumBytesAvailable < numBytes) @@ -86,12 +87,12 @@ private void EnsureAvailable(int numBytes) } } - public byte ReadByte() - { - EnsureAvailable(sizeof(byte)); - var val = buffer[bufferOffset]; - bufferOffset += sizeof(byte); - return val; + public byte ReadByte() + { + EnsureAvailable(sizeof(byte)); + var val = buffer[bufferOffset]; + bufferOffset += sizeof(byte); + return val; } public int ReadUInt8() => ReadByte(); @@ -106,13 +107,13 @@ public int ReadUInt16() return val; } - public int ReadInt16() - { - EnsureAvailable(sizeof(short)); - var val = BigEndianBitConverter.ToInt16(buffer, bufferOffset); - bufferOffset += sizeof(short); - return val; - } + public int ReadInt16() + { + EnsureAvailable(sizeof(short)); + var val = BigEndianBitConverter.ToInt16(buffer, bufferOffset); + bufferOffset += sizeof(short); + return val; + } public long ReadUInt32() { @@ -200,7 +201,7 @@ public int ReadIntN(int nbBit) var result = ReadUIntN(nbBit); return result.AsSignedInt(nbBit); } - + public BigInteger ReadUInt64() { EnsureAvailable(sizeof(ulong)); @@ -266,7 +267,7 @@ public SectionInfo ReadSectionInfo() { return new SectionInfo(Constants.IndicatorSectionLength, SectionCode.IndicatorSection); } - + if (sectionLength == Constants.GribFileEndCode) { return new SectionInfo(Constants.EndSectionLength, SectionCode.EndSection); @@ -309,6 +310,7 @@ public void Dispose() { stream.Close(); } + ArrayPool.Shared.Return(buffer); } public void SaveCurrentPosition() @@ -316,7 +318,7 @@ public void SaveCurrentPosition() savedPosition = Position; } - public long Position => stream.Position - NumBytesAvailable; + public long Position => stream.Position - NumBytesAvailable; public void SeekToSavedPosition() {